@cloudflare/realtimekit 2.0.2-staging.5 → 2.0.2-staging.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.rn.js CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var CT=Object.defineProperty;var wT=(s,t,e)=>t in s?CT(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var h=(s,t,e)=>(wT(s,typeof t!="symbol"?t+"":t,e),e),Nl=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)};var a=(s,t,e)=>(Nl(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)},f=(s,t,e,r)=>(Nl(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e);var O=(s,t,e)=>(Nl(s,t,"access private method"),e);const qr=require("uuid"),vg=require("bowser"),S=require("@protobuf-ts/runtime"),RT=require("worker-timers"),bT=require("sdp-transform");function yg(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 Bc=yg(RT),Yt=yg(bT);function kT(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:kT});function MT(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:MT});const AT=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,n,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:(n=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:n.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")}))},ao="chrome",Eg="opera",Pg="firefox",_g="iexplorer",Cg="safari",wg="nwjs",Rg="electron",bg="react-native",Gu="unknown",sd={Chrome:ao,Chromium:ao,Opera:Eg,Firefox:Pg,"Internet Explorer":_g,Safari:Cg};function IT(){const{userAgent:s}=navigator,t={name:Gu,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=ao,t.version=e)}else t.name=ao,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function DT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:Rg,version:t}}return null}function OT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:wg,version:t}}}function NT(){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 LT(s){let t;const e=[NT,DT,OT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in sd?{name:sd[r],version:s.getBrowserVersion()}:(t=IT(),t||{name:Gu,version:void 0})}class VT{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=vg.getParser(navigator.userAgent),typeof t=="undefined"){const i=LT(this._bowser);e=i.name,r=i.version}else t.name in sd?(e=sd[t.name],r=t.version):(e=Gu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===ao}isOpera(){return this._name===Eg}isFirefox(){return this._name===Pg}isIExplorer(){return this._name===_g}isSafari(){return this._name===Cg}isNWJS(){return this._name===wg}isElectron(){return this._name===Rg}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 xT extends VT{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 xT;var Ze={},UT={get exports(){return Ze},set exports(s){Ze=s}},un=typeof Reflect=="object"?Reflect:null,Mh=un&&typeof un.apply=="function"?un.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Hc;un&&typeof un.ownKeys=="function"?Hc=un.ownKeys:Object.getOwnPropertySymbols?Hc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Hc=function(t){return Object.getOwnPropertyNames(t)};function $T(s){console&&console.warn&&console.warn(s)}var kg=Number.isNaN||function(t){return t!==t};function ne(){ne.init.call(this)}UT.exports=ne;Ze.once=qT;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var Ah=10;function ul(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return Ah},set:function(s){if(typeof s!="number"||s<0||kg(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Ah=s}});ne.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};ne.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||kg(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 Mg(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return Mg(this)};ne.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",n=this._events;if(n!==void 0)i=i&&n.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=n[t];if(d===void 0)return!1;if(typeof d=="function")Mh(d,this,e);else for(var l=d.length,u=Ng(d,l),r=0;r<l;++r)Mh(u[r],this,e);return!0};function Ag(s,t,e,r){var i,n,o;if(ul(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Mg(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,$T(c)}return s}ne.prototype.addListener=function(t,e){return Ag(this,t,e,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(t,e){return Ag(this,t,e,!0)};function BT(){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 Ig(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=BT.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(t,e){return ul(e),this.on(t,Ig(this,t,e)),this};ne.prototype.prependOnceListener=function(t,e){return ul(e),this.prependListener(t,Ig(this,t,e)),this};ne.prototype.removeListener=function(t,e){var r,i,n,o,c;if(ul(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(n=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():HT(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};ne.prototype.off=ne.prototype.removeListener;ne.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 n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[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 Dg(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?FT(i):Ng(i,i.length)}ne.prototype.listeners=function(t){return Dg(this,t,!0)};ne.prototype.rawListeners=function(t){return Dg(this,t,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Og.call(s,t)};ne.prototype.listenerCount=Og;function Og(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}ne.prototype.eventNames=function(){return this._eventsCount>0?Hc(this._events):[]};function Ng(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function HT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function FT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function qT(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Lg(s,t,n,{once:!0}),t!=="error"&&jT(s,i,{once:!0})})}function jT(s,t,e){typeof s.on=="function"&&Lg(s,"error",t,e)}function Lg(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(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var j;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(j||(j={}));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 GT=new Map([[D.PRECALL_TEST_BEGIN,j.MINOR_EVENT],[D.PRECALL_TEST_COMPLETE,j.MINOR_EVENT],[D.CALL_JOIN_BEGIN,j.MAJOR_EVENT],[D.NET_QUALITY_TEST_BEGIN,j.MINOR_EVENT],[D.NET_QUALITY_TEST_END,j.MINOR_EVENT],[D.WEBSOCKET_CONNECTED,j.MINOR_EVENT],[D.TRANSPORT_CONNECTED,j.MAJOR_EVENT],[D.AUDIO_ON,j.MINOR_EVENT],[D.AUDIO_OFF,j.MINOR_EVENT],[D.VIDEO_ON,j.MINOR_EVENT],[D.VIDEO_OFF,j.MINOR_EVENT],[D.PARTICIPANT_ROLE,j.MINOR_EVENT],[D.PING_STAT,j.MAJOR_EVENT],[D.DISCONNECT,j.MAJOR_EVENT],[D.RECONNECT_ATTEMPT,j.MAJOR_EVENT],[D.SCREENSHARE_START_REQUESTED,j.MINOR_EVENT],[D.SCREENSHARE_STARTED,j.MINOR_EVENT],[D.SCREENSHARE_STOPPED,j.MINOR_EVENT],[D.TAB_CHANGE,j.MINOR_EVENT],[D.BROWSER_BACKGROUNDED,j.MINOR_EVENT],[D.BROWSER_FOREGROUNDED,j.MINOR_EVENT],[D.DOMINANT_SPEAKER,j.MINOR_EVENT],[D.AUDIO_DEVICES_UPDATES,j.MINOR_EVENT],[D.VIDEO_DEVICES_UPDATES,j.MINOR_EVENT],[D.SPEAKER_DEVICES_UPDATES,j.MINOR_EVENT],[D.SELECTED_MICROHPONE_UPDATE,j.MINOR_EVENT],[D.SELECTED_CAMERA_UPDATE,j.MINOR_EVENT],[D.SELECTED_SPEAKER_UPDATE,j.MINOR_EVENT],[D.MEDIA_PERMISSION,j.MINOR_EVENT],[D.LEGACY_SWITCH,j.MINOR_EVENT],[D.AUDIO_PLAY_FAILED,j.MINOR_EVENT],[D.VIDEO_PLAY_FAILED,j.MINOR_EVENT],[D.AUDIO_TRACK_MUTED,j.MINOR_EVENT],[D.VIDEO_TRACK_MUTED,j.MINOR_EVENT],[D.IVS_PLAYER_REBUFFERING,j.MAJOR_EVENT],[D.IVS_PLAYER_AUDIO_BLOCKED,j.MAJOR_EVENT],[D.IVS_PLAYER_PLAYBACK_BLOCKED,j.MAJOR_EVENT],[D.IVS_PLAYER_ERROR,j.MAJOR_EVENT],[D.IVS_PLAYER_RECOVERABLE_ERROR,j.MAJOR_EVENT],[D.IVS_PLAYER_WORKER_ERROR,j.MAJOR_EVENT],[D.IVS_PLAYER_NETWORK_UNAVAILABLE,j.MAJOR_EVENT],[D.LIVESTREAM_LATENCY,j.MAJOR_EVENT],[D.IVS_PLAYER_ANALYTICS_EVENT,j.MINOR_EVENT],[D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,j.MINOR_EVENT],[D.IVS_PLAYER_QUALITY_CHANGED,j.MINOR_EVENT],[D.IVS_PLAYER_INITIALIZED,j.MINOR_EVENT],[D.EXPECTED_VIDEO_RESOLUTION,j.MINOR_EVENT],[D.EXPECTED_SCREENSHARE_RESOLUTION,j.MINOR_EVENT]]);class WT{constructor(){h(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class JT extends Ze{constructor({logger:e,peerId:r,apiHostnames:i,authToken:n}){super();h(this,"logger");h(this,"peerId");h(this,"eventStore");h(this,"apiEndpoint");h(this,"authToken");this.logger=e,this.peerId=r,this.authToken=n,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new WT}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,n=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(n)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),GT.get(e.event)===j.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(n=>{this.eventStore.add(n)}),i}return!1}}var Ih;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(Ih||(Ih={}));const Vg={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Nt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Nt||(Nt={}));var Dh;(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"})(Dh||(Dh={}));function Br(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function rd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function id({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const xg=240,Ug=720,$g=8,Bg=3,hl=10,pl=.02,gl=.03;function Qs({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 Hg({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const n=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((n+Number.EPSILON)*100)/100}function Fg({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function qg({packetsLost:s,packetsSent:t,jitter:e}){const i=Qs({stat:Fg({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:hl,rangeRankingDirection:"UP"}),o=Qs({stat:e,weight:.3,rangeMin:pl,rangeMax:gl,rangeRankingDirection:"UP"});return i+o}function KT({frameWidth:s,isScreenShare:t}){return s<(t?Ug:xg)}function zT({framesPerSecond:s,isScreenShare:t}){return s<(t?Bg:$g)}function YT({framesEncoded:s}){return s===0}function jg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Qs({stat:Fg({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:hl,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:pl,rangeMax:gl,rangeRankingDirection:"UP"}),l=KT({frameWidth:s,isScreenShare:n}),u=zT({framesPerSecond:t,isScreenShare:n}),p=YT({framesEncoded:o,isScreenShare:n});return Hg({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}function Gg({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function Wg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Qs({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Qs({stat:Gg({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:hl,rangeRankingDirection:"UP"}),l=Qs({stat:r,weight:.3,rangeMin:pl,rangeMax:gl,rangeRankingDirection:"UP"});return n+c+l}function QT({framesDecoded:s}){return s===0}function XT({framesPerSecond:s,isScreenShare:t}){return s<(t?Bg:$g)}function ZT({frameWidth:s,isScreenShare:t}){return s<(t?Ug:xg)}function Jg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Qs({stat:Gg({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:hl,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:pl,rangeMax:gl,rangeRankingDirection:"UP"}),l=ZT({frameWidth:s,isScreenShare:n}),u=XT({framesPerSecond:t,isScreenShare:n}),p=QT({framesDecoded:o,isScreenShare:n});return Hg({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}class er{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=er.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=er.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 wT=Object.defineProperty;var RT=(s,t,e)=>t in s?wT(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var h=(s,t,e)=>(RT(s,typeof t!="symbol"?t+"":t,e),e),Ll=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)};var a=(s,t,e)=>(Ll(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)=>(Ll(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e);var N=(s,t,e)=>(Ll(s,t,"access private method"),e);const qr=require("uuid"),yg=require("bowser"),T=require("@protobuf-ts/runtime"),bT=require("worker-timers"),kT=require("sdp-transform");function Eg(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 Bc=Eg(bT),Yt=Eg(kT);function MT(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:MT});function AT(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:AT});const IT=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,n,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:(n=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:n.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")}))},ao="chrome",Pg="opera",_g="firefox",Cg="iexplorer",wg="safari",Rg="nwjs",bg="electron",kg="react-native",Gu="unknown",sd={Chrome:ao,Chromium:ao,Opera:Pg,Firefox:_g,"Internet Explorer":Cg,Safari:wg};function DT(){const{userAgent:s}=navigator,t={name:Gu,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=ao,t.version=e)}else t.name=ao,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function OT(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:bg,version:t}}return null}function NT(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Rg,version:t}}}function LT(){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:kg,version:t}}function VT(s){let t;const e=[LT,OT,NT];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in sd?{name:sd[r],version:s.getBrowserVersion()}:(t=DT(),t||{name:Gu,version:void 0})}class xT{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=yg.getParser(navigator.userAgent),typeof t=="undefined"){const i=VT(this._bowser);e=i.name,r=i.version}else t.name in sd?(e=sd[t.name],r=t.version):(e=Gu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===ao}isOpera(){return this._name===Pg}isFirefox(){return this._name===_g}isIExplorer(){return this._name===Cg}isSafari(){return this._name===wg}isNWJS(){return this._name===Rg}isElectron(){return this._name===bg}isReactNative(){return this._name===kg||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 UT extends xT{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 me=new UT;var et={},$T={get exports(){return et},set exports(s){et=s}},un=typeof Reflect=="object"?Reflect:null,Mh=un&&typeof un.apply=="function"?un.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Hc;un&&typeof un.ownKeys=="function"?Hc=un.ownKeys:Object.getOwnPropertySymbols?Hc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Hc=function(t){return Object.getOwnPropertyNames(t)};function BT(s){console&&console.warn&&console.warn(s)}var Mg=Number.isNaN||function(t){return t!==t};function ne(){ne.init.call(this)}$T.exports=ne;et.once=jT;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var Ah=10;function hl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return Ah},set:function(s){if(typeof s!="number"||s<0||Mg(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Ah=s}});ne.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};ne.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Mg(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 Ag(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return Ag(this)};ne.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",n=this._events;if(n!==void 0)i=i&&n.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=n[t];if(d===void 0)return!1;if(typeof d=="function")Mh(d,this,e);else for(var l=d.length,u=Lg(d,l),r=0;r<l;++r)Mh(u[r],this,e);return!0};function Ig(s,t,e,r){var i,n,o;if(hl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Ag(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,BT(c)}return s}ne.prototype.addListener=function(t,e){return Ig(this,t,e,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(t,e){return Ig(this,t,e,!0)};function HT(){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 Dg(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=HT.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(t,e){return hl(e),this.on(t,Dg(this,t,e)),this};ne.prototype.prependOnceListener=function(t,e){return hl(e),this.prependListener(t,Dg(this,t,e)),this};ne.prototype.removeListener=function(t,e){var r,i,n,o,c;if(hl(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(n=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():FT(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this};ne.prototype.off=ne.prototype.removeListener;ne.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 n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[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 Og(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?qT(i):Lg(i,i.length)}ne.prototype.listeners=function(t){return Og(this,t,!0)};ne.prototype.rawListeners=function(t){return Og(this,t,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Ng.call(s,t)};ne.prototype.listenerCount=Ng;function Ng(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}ne.prototype.eventNames=function(){return this._eventsCount>0?Hc(this._events):[]};function Lg(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function FT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function qT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function jT(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Vg(s,t,n,{once:!0}),t!=="error"&&GT(s,i,{once:!0})})}function GT(s,t,e){typeof s.on=="function"&&Vg(s,"error",t,e)}function Vg(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(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var j;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(j||(j={}));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 WT=new Map([[D.PRECALL_TEST_BEGIN,j.MINOR_EVENT],[D.PRECALL_TEST_COMPLETE,j.MINOR_EVENT],[D.CALL_JOIN_BEGIN,j.MAJOR_EVENT],[D.NET_QUALITY_TEST_BEGIN,j.MINOR_EVENT],[D.NET_QUALITY_TEST_END,j.MINOR_EVENT],[D.WEBSOCKET_CONNECTED,j.MINOR_EVENT],[D.TRANSPORT_CONNECTED,j.MAJOR_EVENT],[D.AUDIO_ON,j.MINOR_EVENT],[D.AUDIO_OFF,j.MINOR_EVENT],[D.VIDEO_ON,j.MINOR_EVENT],[D.VIDEO_OFF,j.MINOR_EVENT],[D.PARTICIPANT_ROLE,j.MINOR_EVENT],[D.PING_STAT,j.MAJOR_EVENT],[D.DISCONNECT,j.MAJOR_EVENT],[D.RECONNECT_ATTEMPT,j.MAJOR_EVENT],[D.SCREENSHARE_START_REQUESTED,j.MINOR_EVENT],[D.SCREENSHARE_STARTED,j.MINOR_EVENT],[D.SCREENSHARE_STOPPED,j.MINOR_EVENT],[D.TAB_CHANGE,j.MINOR_EVENT],[D.BROWSER_BACKGROUNDED,j.MINOR_EVENT],[D.BROWSER_FOREGROUNDED,j.MINOR_EVENT],[D.DOMINANT_SPEAKER,j.MINOR_EVENT],[D.AUDIO_DEVICES_UPDATES,j.MINOR_EVENT],[D.VIDEO_DEVICES_UPDATES,j.MINOR_EVENT],[D.SPEAKER_DEVICES_UPDATES,j.MINOR_EVENT],[D.SELECTED_MICROHPONE_UPDATE,j.MINOR_EVENT],[D.SELECTED_CAMERA_UPDATE,j.MINOR_EVENT],[D.SELECTED_SPEAKER_UPDATE,j.MINOR_EVENT],[D.MEDIA_PERMISSION,j.MINOR_EVENT],[D.LEGACY_SWITCH,j.MINOR_EVENT],[D.AUDIO_PLAY_FAILED,j.MINOR_EVENT],[D.VIDEO_PLAY_FAILED,j.MINOR_EVENT],[D.AUDIO_TRACK_MUTED,j.MINOR_EVENT],[D.VIDEO_TRACK_MUTED,j.MINOR_EVENT],[D.IVS_PLAYER_REBUFFERING,j.MAJOR_EVENT],[D.IVS_PLAYER_AUDIO_BLOCKED,j.MAJOR_EVENT],[D.IVS_PLAYER_PLAYBACK_BLOCKED,j.MAJOR_EVENT],[D.IVS_PLAYER_ERROR,j.MAJOR_EVENT],[D.IVS_PLAYER_RECOVERABLE_ERROR,j.MAJOR_EVENT],[D.IVS_PLAYER_WORKER_ERROR,j.MAJOR_EVENT],[D.IVS_PLAYER_NETWORK_UNAVAILABLE,j.MAJOR_EVENT],[D.LIVESTREAM_LATENCY,j.MAJOR_EVENT],[D.IVS_PLAYER_ANALYTICS_EVENT,j.MINOR_EVENT],[D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,j.MINOR_EVENT],[D.IVS_PLAYER_QUALITY_CHANGED,j.MINOR_EVENT],[D.IVS_PLAYER_INITIALIZED,j.MINOR_EVENT],[D.EXPECTED_VIDEO_RESOLUTION,j.MINOR_EVENT],[D.EXPECTED_SCREENSHARE_RESOLUTION,j.MINOR_EVENT]]);class JT{constructor(){h(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class KT extends et{constructor({logger:e,peerId:r,apiHostnames:i,authToken:n}){super();h(this,"logger");h(this,"peerId");h(this,"eventStore");h(this,"apiEndpoint");h(this,"authToken");this.logger=e,this.peerId=r,this.authToken=n,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new JT}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,n=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(n)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),WT.get(e.event)===j.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(n=>{this.eventStore.add(n)}),i}return!1}}var Ih;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(Ih||(Ih={}));const xg={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Nt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Nt||(Nt={}));var Dh;(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"})(Dh||(Dh={}));function Br(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function rd({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function id({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Ug=240,$g=720,Bg=8,Hg=3,pl=10,gl=.02,ml=.03;function Qs({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 Fg({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const n=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((n+Number.EPSILON)*100)/100}function qg({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function jg({packetsLost:s,packetsSent:t,jitter:e}){const i=Qs({stat:qg({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:pl,rangeRankingDirection:"UP"}),o=Qs({stat:e,weight:.3,rangeMin:gl,rangeMax:ml,rangeRankingDirection:"UP"});return i+o}function zT({frameWidth:s,isScreenShare:t}){return s<(t?$g:Ug)}function YT({framesPerSecond:s,isScreenShare:t}){return s<(t?Hg:Bg)}function QT({framesEncoded:s}){return s===0}function Gg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Qs({stat:qg({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:pl,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:gl,rangeMax:ml,rangeRankingDirection:"UP"}),l=zT({frameWidth:s,isScreenShare:n}),u=YT({framesPerSecond:t,isScreenShare:n}),p=QT({framesEncoded:o,isScreenShare:n});return Fg({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}function Wg({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function Jg({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Qs({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Qs({stat:Wg({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:pl,rangeRankingDirection:"UP"}),l=Qs({stat:r,weight:.3,rangeMin:gl,rangeMax:ml,rangeRankingDirection:"UP"});return n+c+l}function XT({framesDecoded:s}){return s===0}function ZT({framesPerSecond:s,isScreenShare:t}){return s<(t?Hg:Bg)}function eS({frameWidth:s,isScreenShare:t}){return s<(t?$g:Ug)}function Kg({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Qs({stat:Wg({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:pl,rangeRankingDirection:"UP"}),d=Qs({stat:i,weight:1,rangeMin:gl,rangeMax:ml,rangeRankingDirection:"UP"}),l=eS({frameWidth:s,isScreenShare:n}),u=ZT({framesPerSecond:t,isScreenShare:n}),p=XT({framesDecoded:o,isScreenShare:n});return Fg({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:p,jitterQuality:d,packetsLostQuality:c})}class er{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=er.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=er.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(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class Kg extends Ze{constructor(e){super();h(this,"call");h(this,"timeOut");this.call=new er(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 eS=8,tS=1/1e3;class sS extends Kg{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(er.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(n){}}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)*eS/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const n=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(n*tS)})}}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 Wu extends Kg{constructor(e,r=er.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 rS extends Wu{constructor(t){super(t,er.isHost)}}class iS extends Wu{constructor(t){super(t,er.isRelay)}}class nS extends Wu{constructor(t){super(t,er.isReflexive)}}class aS{constructor(){h(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,n,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,(n=this.ipInformation)!=null&&n.ip&&(this.ipInformation.ip=Br(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=Br(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 zg=new aS,Oh=[{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 Nh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Yg{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 Qg extends Ze{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 Ze}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 n=((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&&n.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&&n.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 n=((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&&n.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&&n.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 n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.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&&n.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 n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.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&&n.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 n=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=n,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(),n=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 n}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=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 n}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 n=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return n&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var P,k,C,I,V,L,B,$,z,De,Tt,Kt,zr;const c=e,d=new Yg,l=r.length?new Set(r):void 0,u=[],p=[],m=[],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:_}=M,U=M,me={nominated:v!=null?v:_,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};m.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 _={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=_,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,_)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,_)}}break}case"remote-inbound-rtp":{const v=M,_={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,_);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(M.id))break;const v=M,_=n||this.outboundProducerMap.get(M.id),U=this.pausedProducerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const me=this.overallProducersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const ve=this.callStatsInstance.producers.get(_);if(((P=ve==null?void 0:ve.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(_)||d.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const N={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 b=v,Re={frameHeight:b.frameHeight,frameWidth:b.frameWidth,framesEncoded:b.framesEncoded,framesDropped:b.framesDropped,framesPerSecond:b.framesPerSecond,framesSent:b.framesSent,keyFramesEncoded:b.keyFramesEncoded,firCount:b.firCount,encoderImplementation:b.encoderImplementation,hugeFramesSent:b.hugeFramesSent,pliCount:b.pliCount,qpSum:b.qpSum,qualityLimitationDurations:b.qualityLimitationDurations,qualityLimitationReason:b.qualityLimitationReason,qualityLimitationResolutionChanges:b.qualityLimitationResolutionChanges,totalEncodeTime:b.targetBitrate,totalPacketSendDelay:b.totalPacketSendDelay,retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,scalabilityMode:b.scalabilityMode,powerEfficientEncoder:b.powerEfficientEncoder,...N};d.outboundVideoRtp.set(M.id,Re),d.producerStreamMap.get(_).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(_,me,Re)}else if(v.mediaType==="audio"||v.kind==="audio"){const b=v,Re={retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,...N};d.outboundAudioRtp.set(M.id,Re),d.producerStreamMap.get(_).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(_,me,Re)}}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,_=n||this.inboundConsumerMap.get(M.id),U=this.pausedConsumerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const me=this.overallConsumersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(_)||d.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const ve={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 N=v,b={frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesDecoded:N.framesDecoded,framesDropped:N.framesDropped,framesPerSecond:N.framesPerSecond,framesReceived:N.framesReceived,keyFramesDecoded:N.keyFramesDecoded,firCount:N.firCount,decoderImplementation:N.decoderImplementation,pliCount:N.pliCount,totalProcessingDelay:N.totalProcessingDelay,qpSum:N.qpSum||0,totalAssemblyTime:N.totalAssemblyTime||0,totalDecodeTime:N.totalDecodeTime||0,totalFreezesDuration:N.totalFreezesDuration||0,totalInterFrameDelay:N.totalInterFrameDelay||0,totalPausesDuration:N.totalPausesDuration||0,totalSquaredInterFrameDelay:N.totalSquaredInterFrameDelay||0,freezeCount:N.freezeCount||0,pauseCount:N.pauseCount||0,powerEfficientDecoder:N.powerEfficientDecoder,...ve};b.score=Jg({frameWidth:b.frameWidth||0,framesDecoded:(b.framesDecoded||0)-(((k=this.videoConsumerToStatsMap.get(_))==null?void 0:k.framesDecoded)||0),framesPerSecond:b.framesPerSecond||0,packetsLost:(b.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(_))==null?void 0:C.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((I=this.videoConsumerToStatsMap.get(_))==null?void 0:I.packetsReceived)||0),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),E.set(_,{score:+(b.score*10).toFixed(),frameWidth:b.frameWidth||0,frameHeight:b.frameHeight||0,framesPerSecond:b.framesPerSecond||0,packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(_))==null?void 0:V.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(_))==null?void 0:L.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(_))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,b),d.inboundVideoRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(_,me,b)}else if(v.mediaType==="audio"||v.kind==="audio"){const N=v,b={audioLevel:N.audioLevel,concealedSamples:N.concealedSamples,concealmentEvents:N.concealmentEvents,totalAudioEnergy:N.totalAudioEnergy,totalSamplesDuration:N.totalSamplesDuration,totalSamplesReceived:N.totalSamplesReceived,fecPacketsDiscarded:N.fecPacketsDiscarded||0,fecPacketsReceived:N.fecPacketsReceived||0,insertedSamplesForDeceleration:N.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:N.removedSamplesForAcceleration||0,silentConcealedSamples:N.silentConcealedSamples||0,playoutId:N.playoutId,...ve};b.score=Wg({concealmentEvents:(b.concealmentEvents||0)-((($=this.audioConsumerToStatsMap.get(_))==null?void 0:$.concealmentEvents)||0),packetsLost:(b.packetsLost||0)-(((z=this.audioConsumerToStatsMap.get(_))==null?void 0:z.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((De=this.audioConsumerToStatsMap.get(_))==null?void 0:De.packetsReceived)||0),jitter:b.jitter||0}),E.set(_,{score:+(b.score*10).toFixed(),packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((Tt=this.audioConsumerToStatsMap.get(_))==null?void 0:Tt.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((Kt=this.audioConsumerToStatsMap.get(_))==null?void 0:Kt.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((zr=this.audioConsumerToStatsMap.get(_))==null?void 0:zr.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,b),d.inboundAudioRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(_,me,b)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((M,v)=>{var _,U,me,ve,N,b,Re,Pa,_a,Ca,wa,Ra,ba,ka,Ma,Aa,Ia,Da,Oa,Na,La,Va,xa;if(M.outboundVideoRtpId.length>0){const ce=[];M.outboundVideoRtpId.forEach(Ol=>{ce.push(d.outboundVideoRtp.get(Ol))});const Y=this.getWorkingSimulcastVideoStats(ce);Y.score=jg({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((_=Y.remoteData)==null?void 0:_.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)-(((N=(ve=this.videoProducerToStatsMap.get(v))==null?void 0:ve.remoteData)==null?void 0:N.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((b=this.videoProducerToStatsMap.get(v))==null?void 0:b.framesEncoded)||0)}),T.set(v,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((Re=Y.remoteData)==null?void 0:Re.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:rd({packetsSent:(Y.packetsSent||0)-(((Pa=this.videoProducerToStatsMap.get(v))==null?void 0:Pa.packetsSent)||0),packetsLost:(((_a=Y.remoteData)==null?void 0:_a.packetsLost)||0)-(((wa=(Ca=this.videoProducerToStatsMap.get(v))==null?void 0:Ca.remoteData)==null?void 0:wa.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Y)}else if(M.outboundAudioRtpId.length>0){const ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);ce.score=qg({packetsSent:(ce.packetsSent||0)-(((ba=this.audioProducerToStatsMap.get(v))==null?void 0:ba.packetsSent)||0),packetsLost:(((ka=ce.remoteData)==null?void 0:ka.packetsLost)||0)-(((Aa=(Ma=this.audioProducerToStatsMap.get(v))==null?void 0:Ma.remoteData)==null?void 0:Aa.packetsLost)||0),jitter:((Ia=ce.remoteData)==null?void 0:Ia.jitter)||0}),T.set(v,{score:+(ce.score*10).toFixed(),bitrate:((ce.bytesSent||0)-(((Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.bytesSent)||0))*8/7,packetsLostPercentage:rd({packetsSent:(ce.packetsSent||0)-(((Oa=this.audioProducerToStatsMap.get(v))==null?void 0:Oa.packetsSent)||0),packetsLost:(((Na=ce.remoteData)==null?void 0:Na.packetsLost)||0)-(((Va=(La=this.audioProducerToStatsMap.get(v))==null?void 0:La.remoteData)==null?void 0:Va.packetsLost)||0)}),jitter:((xa=ce.remoteData)==null?void 0:xa.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ce)}}),m.forEach(M=>{const v=u.find(U=>U.id===M.localCandidateId?(M.localCandidateId=U.id,U):null),_=p.find(U=>U.id===M.remoteCandidateId?(M.remoteCandidateId=U.id,U):null);v&&(M.localCandidateType=v.type,M.localCandidateAddress=Br(v.address),M.localCandidatePort=v.port,M.localCandidateProtocol=v.protocol,M.localCandidateUrl=v.url,M.localCandidateNetworkType=v.networkType,M.localCandidateRelatedAddress=Br(v.relatedAddress),M.localCandidateRelatedPort=v.relatedPort),_&&(M.remoteCandidateType=_.type,M.remoteCandidateAddress=Br(_.address),M.remoteCandidatePort=_.port,M.remoteCandidateProtocol=_.protocol,M.remoteCandidateUrl=_.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=m),d.transport&&!d.transport.roundTripTime){let M=0,v=0;d.remoteInboundRtp.forEach((_,U)=>{_.roundTripTime&&_.roundTripTime>M&&(M=_.roundTripTime,v=_.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 n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,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,n)=>{var o,c;r.push({producerId:n,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(n))==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,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,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||Oh},i=new Promise((u,p)=>{try{const m=new rS(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),n=new Promise((u,p)=>{try{const m=new iS(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),o=new Promise((u,p)=>{try{const m=new nS(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),[c,d,l]=await Promise.all([i,n,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((n,o)=>{try{const c={iceServers:e||Oh},d=new sS(c);d.addListener("done",n),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 zg.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?Nh(l==null?void 0:l.loc):void 0}}const[i,n,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?Nh(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}}}class oS extends Qg{}class Xg extends Qg{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(),n=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...n.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(n,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,n=void 0,o=void 0){var P,k,C,I,V,L,B,$,z,De,Tt,Kt,zr;const c=e,d=new Yg,l=r.length?new Set(r):void 0,u=[],p=[],m=[],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:_}=M,U=M,me={nominated:v!=null?v:_,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};m.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 _={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=_,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,_)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,_)}}break}case"remote-inbound-rtp":{const v=M,_={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,_);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(M.id))break;const v=M,_=n||this.outboundProducerMap.get(M.id),U=this.pausedProducerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const me=this.overallProducersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const ve=this.callStatsInstance.producers.get(_);if(((P=ve==null?void 0:ve.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(_)||d.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const N={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 b=v,Re={frameHeight:b.frameHeight,frameWidth:b.frameWidth,framesEncoded:b.framesEncoded,framesDropped:b.framesDropped?b.framesDropped:b.droppedFrames,framesPerSecond:b.framesPerSecond?b.framesPerSecond:b.framerateMean,framesSent:b.framesSent,keyFramesEncoded:b.keyFramesEncoded,firCount:b.firCount,encoderImplementation:b.encoderImplementation,hugeFramesSent:b.hugeFramesSent,pliCount:b.pliCount,qpSum:b.qpSum,qualityLimitationReason:b.qualityLimitationReason,qualityLimitationDurations:b.qualityLimitationDurations,qualityLimitationResolutionChanges:b.qualityLimitationResolutionChanges,totalEncodeTime:b.totalEncodeTime,totalPacketSendDelay:b.totalEncodeTime,retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,scalabilityMode:b.scalabilityMode,powerEfficientEncoder:b.powerEfficientEncoder,...N};d.outboundVideoRtp.set(M.id,Re),d.producerStreamMap.get(_).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(_,me,Re)}else if(v.mediaType==="audio"||v.kind==="audio"){const b=v,Re={retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,...N};d.outboundAudioRtp.set(M.id,Re),d.producerStreamMap.get(_).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(_,me,Re)}}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,_=n||this.inboundConsumerMap.get(M.id),U=this.pausedConsumerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const me=this.overallConsumersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(_)||d.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const ve={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 N=v,b={frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesDecoded:N.framesDecoded,framesDropped:N.framesDropped?N.framesDropped:N.droppedFrames,framesPerSecond:N.framesPerSecond?N.framesPerSecond:N.framerateMean,framesReceived:N.framesReceived,keyFramesDecoded:N.keyFramesDecoded,firCount:N.firCount,decoderImplementation:N.decoderImplementation,pliCount:N.pliCount,totalProcessingDelay:N.totalProcessingDelay,qpSum:N.qpSum||0,totalAssemblyTime:N.totalAssemblyTime||0,totalDecodeTime:N.totalDecodeTime||0,totalFreezesDuration:N.totalFreezesDuration||0,totalInterFrameDelay:N.totalInterFrameDelay||0,totalPausesDuration:N.totalPausesDuration||0,totalSquaredInterFrameDelay:N.totalSquaredInterFrameDelay||0,freezeCount:N.freezeCount||0,pauseCount:N.pauseCount||0,powerEfficientDecoder:N.powerEfficientDecoder,...ve};b.score=Jg({frameWidth:b.frameWidth||0,framesDecoded:(b.framesDecoded||0)-(((k=this.videoConsumerToStatsMap.get(_))==null?void 0:k.framesDecoded)||0),framesPerSecond:b.framesPerSecond||0,packetsLost:(b.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(_))==null?void 0:C.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((I=this.videoConsumerToStatsMap.get(_))==null?void 0:I.packetsReceived)||0),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),E.set(_,{score:+(b.score*10).toFixed(),frameWidth:b.frameWidth||0,frameHeight:b.frameHeight||0,framesPerSecond:b.framesPerSecond||0,packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(_))==null?void 0:V.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(_))==null?void 0:L.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(_))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,b),d.inboundVideoRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(_,me,b)}else if(v.mediaType==="audio"||v.kind==="audio"){const N=v,b={audioLevel:N.audioLevel,concealedSamples:N.concealedSamples,concealmentEvents:N.concealmentEvents,totalAudioEnergy:N.totalAudioEnergy,totalSamplesDuration:N.totalSamplesDuration,totalSamplesReceived:N.totalSamplesReceived,fecPacketsDiscarded:N.fecPacketsDiscarded||0,fecPacketsReceived:N.fecPacketsReceived||0,insertedSamplesForDeceleration:N.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:N.removedSamplesForAcceleration||0,silentConcealedSamples:N.silentConcealedSamples||0,playoutId:N.playoutId,...ve};b.score=Wg({concealmentEvents:(b.concealmentEvents||0)-((($=this.audioConsumerToStatsMap.get(_))==null?void 0:$.concealmentEvents)||0),packetsLost:(b.packetsLost||0)-(((z=this.audioConsumerToStatsMap.get(_))==null?void 0:z.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((De=this.audioConsumerToStatsMap.get(_))==null?void 0:De.packetsReceived)||0),jitter:b.jitter||0}),E.set(_,{score:+(b.score*10).toFixed(),packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((Tt=this.audioConsumerToStatsMap.get(_))==null?void 0:Tt.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((Kt=this.audioConsumerToStatsMap.get(_))==null?void 0:Kt.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((zr=this.audioConsumerToStatsMap.get(_))==null?void 0:zr.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,b),d.inboundAudioRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(_,me,b)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((M,v)=>{var _,U,me,ve,N,b,Re,Pa,_a,Ca,wa,Ra,ba,ka,Ma,Aa,Ia,Da,Oa,Na,La,Va,xa;if(M.outboundVideoRtpId.length>0){const ce=[];M.outboundVideoRtpId.forEach(Ol=>{ce.push(d.outboundVideoRtp.get(Ol))});const Y=this.getWorkingSimulcastVideoStats(ce);Y.score=jg({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((_=Y.remoteData)==null?void 0:_.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)-(((N=(ve=this.videoProducerToStatsMap.get(v))==null?void 0:ve.remoteData)==null?void 0:N.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((b=this.videoProducerToStatsMap.get(v))==null?void 0:b.framesEncoded)||0)}),T.set(v,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((Re=Y.remoteData)==null?void 0:Re.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:rd({packetsSent:(Y.packetsSent||0)-(((Pa=this.videoProducerToStatsMap.get(v))==null?void 0:Pa.packetsSent)||0),packetsLost:(((_a=Y.remoteData)==null?void 0:_a.packetsLost)||0)-(((wa=(Ca=this.videoProducerToStatsMap.get(v))==null?void 0:Ca.remoteData)==null?void 0:wa.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Y)}else if(M.outboundAudioRtpId.length>0){const ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);ce.score=qg({packetsSent:(ce.packetsSent||0)-(((ba=this.audioProducerToStatsMap.get(v))==null?void 0:ba.packetsSent)||0),packetsLost:(((ka=ce.remoteData)==null?void 0:ka.packetsLost)||0)-(((Aa=(Ma=this.audioProducerToStatsMap.get(v))==null?void 0:Ma.remoteData)==null?void 0:Aa.packetsLost)||0),jitter:((Ia=ce.remoteData)==null?void 0:Ia.jitter)||0}),T.set(v,{score:+(ce.score*10).toFixed(),bitrate:((ce.bytesSent||0)-(((Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.bytesSent)||0))*8/7,packetsLostPercentage:rd({packetsSent:(ce.packetsSent||0)-(((Oa=this.audioProducerToStatsMap.get(v))==null?void 0:Oa.packetsSent)||0),packetsLost:(((Na=ce.remoteData)==null?void 0:Na.packetsLost)||0)-(((Va=(La=this.audioProducerToStatsMap.get(v))==null?void 0:La.remoteData)==null?void 0:Va.packetsLost)||0)}),jitter:((xa=ce.remoteData)==null?void 0:xa.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ce)}}),m.forEach(M=>{const v=u.find(U=>U.id===M.localCandidateId?(M.localCandidateId=U.id,U):null),_=p.find(U=>U.id===M.remoteCandidateId?(M.remoteCandidateId=U.id,U):null);v&&(M.localCandidateType=v.type,M.localCandidateAddress=Br(v.address),M.localCandidatePort=v.port,M.localCandidateProtocol=v.protocol,M.localCandidateUrl=v.url,M.localCandidateNetworkType=v.networkType,M.localCandidateRelatedAddress=Br(v.relatedAddress),M.localCandidateRelatedPort=v.relatedPort),_&&(M.remoteCandidateType=_.type,M.remoteCandidateAddress=Br(_.address),M.remoteCandidatePort=_.port,M.remoteCandidateProtocol=_.protocol,M.remoteCandidateUrl=_.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=m),d.transport&&!d.transport.roundTripTime){let M=0,v=0;d.remoteInboundRtp.forEach((_,U)=>{_.roundTripTime&&_.roundTripTime>M&&(M=_.roundTripTime,v=_.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,n)=>{const o=this.producerMap.get(n),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:n,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 n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const m=this.consumerMap.get(i).track.getSettings(),T=e.inboundVideoRtp.get(u);return T.frameHeight||(T.frameHeight=m.height,T.frameWidth=m.width,T.framesPerSecond=m.frameRate),T});n={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 n}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,n))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class cS extends Xg{}function nd(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 Lh(s,t,e){const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{nd(this,t,e,o)}):n}catch(n){nd(this,t,e,n)}return null},s}const K=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{nd(this,s,t,d)}):c}catch(c){nd(this,s,t,c)}return null},i},dS=(s,t)=>(e,r,i)=>{if(i)return Lh(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);o.value instanceof Function&&Object.defineProperty(e.prototype,n,Lh(o,s,t))}};var G=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(n=(i<3?o(n):i>3?o(t,e,n):o(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n};const W=console;let F=class extends Ze{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Vg.PROD,n,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 JT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new oS;break;case"Gecko":this.measurements=new Xg;break;case"WebKit":this.measurements=new cS;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 Ze,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(n=>{this.registerProducer(n)}),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(n=>{this.registerConsumer(n)}),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===Nt.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===Nt.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===Nt.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Nt.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===Nt.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===Nt.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===Nt.AUDIO&&D.AUDIO_PLAY_FAILED||e===Nt.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Nt.AUDIO&&D.AUDIO_TRACK_MUTED||e===Nt.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(n,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)}n({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(n=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}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,n;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&&(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!((d=n.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()]);n&&l?n.consumerReport=l:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.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:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.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}})}};G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerIceServers",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendConsumerSharedMediaStateEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPreCallTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareRequestedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendActiveSpeakerEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"devices",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"selectedDevice",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPermission",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPlaybackFailed",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaTrackMuted",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"tabChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserBackgrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserForegrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"legacySwitch",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"getPreCallTestResults",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendCallJoinBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendNetworkQualityTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendWebSocketConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendTransportConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendAudioToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendVideoToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendParticipantRoleToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"startPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"stopPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPingStatsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRebufferEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAudioBlockEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerInitializedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerWorkerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRecoverableErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAnalyticsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerQualityChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPlayerLiveLatency",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendDisconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendReconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedVideoResolution",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedScreenshareResolution",null);F=G([dS(TypeError,(s,t)=>W.error(t,s))],F);const lS=F;class Zg extends Ze{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=Vg.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:p}){var m,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 zg.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new lS(o,r,i,c,d,e,l,p),this.iceServers=n,(m=this.backend)==null||m.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(P){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.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(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(n=this.backend)==null||n.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 n;(n=this.backend)==null||n.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.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 n,o,c,d,l,u,p,m,T,E,P;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.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":(m=this.backend)==null||m.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":(P=this.backend)==null||P.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 n;(n=this.backend)==null||n.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedScreenshareResolution(e,r,i)})}}const uS=new Zg;uS.setMaxListeners(30);var mo;class hS{constructor(){g(this,mo,void 0)}get telemetry(){var t;return(t=a(this,mo))==null?void 0:t.getValue("telemetry")}init(t){f(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 As,Is;class pS extends Ze.EventEmitter{constructor(e){super();g(this,As,void 0);g(this,Is,void 0);h(this,"asyncPromiseTimeout");h(this,"logger");this.logger=e,f(this,As,new Map),f(this,Is,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,As).set(e,[]);const i=a(this,Is).get(e).map(()=>new Promise(n=>{a(this,As).get(e).push(n)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((n,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),a(this,As).delete(e)}onAsync(e,r){const i=a(this,As),n=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 a(this,Is).get(e)||a(this,Is).set(e,[]),a(this,Is).get(e).push(n),super.on(e,n)}reset(){f(this,As,new Map),f(this,Is,new Map),super.removeAllListeners()}}As=new WeakMap,Is=new WeakMap;var gS=typeof global=="object"&&global&&global.Object===Object&&global;const em=gS;var mS=typeof self=="object"&&self&&self.Object===Object&&self,fS=em||mS||Function("return this")();const ds=fS;var TS=ds.Symbol;const Ps=TS;var tm=Object.prototype,SS=tm.hasOwnProperty,vS=tm.toString,Ua=Ps?Ps.toStringTag:void 0;function yS(s){var t=SS.call(s,Ua),e=s[Ua];try{s[Ua]=void 0;var r=!0}catch(n){}var i=vS.call(s);return r&&(t?s[Ua]=e:delete s[Ua]),i}var ES=Object.prototype,PS=ES.toString;function _S(s){return PS.call(s)}var CS="[object Null]",wS="[object Undefined]",Vh=Ps?Ps.toStringTag:void 0;function Ji(s){return s==null?s===void 0?wS:CS:Vh&&Vh in Object(s)?yS(s):_S(s)}function _s(s){return s!=null&&typeof s=="object"}var RS="[object Symbol]";function ml(s){return typeof s=="symbol"||_s(s)&&Ji(s)==RS}function bS(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 kS=Array.isArray;const kt=kS;var MS=1/0,xh=Ps?Ps.prototype:void 0,Uh=xh?xh.toString:void 0;function sm(s){if(typeof s=="string")return s;if(kt(s))return bS(s,sm)+"";if(ml(s))return Uh?Uh.call(s):"";var t=s+"";return t=="0"&&1/s==-MS?"-0":t}var AS=/\s/;function IS(s){for(var t=s.length;t--&&AS.test(s.charAt(t)););return t}var DS=/^\s+/;function OS(s){return s&&s.slice(0,IS(s)+1).replace(DS,"")}function Gt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var $h=0/0,NS=/^[-+]0x[0-9a-f]+$/i,LS=/^0b[01]+$/i,VS=/^0o[0-7]+$/i,xS=parseInt;function Bh(s){if(typeof s=="number")return s;if(ml(s))return $h;if(Gt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Gt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=OS(s);var e=LS.test(s);return e||VS.test(s)?xS(s.slice(2),e?2:8):NS.test(s)?$h:+s}function Ju(s){return s}var US="[object AsyncFunction]",$S="[object Function]",BS="[object GeneratorFunction]",HS="[object Proxy]";function Ku(s){if(!Gt(s))return!1;var t=Ji(s);return t==$S||t==BS||t==US||t==HS}var FS=ds["__core-js_shared__"];const Ll=FS;var Hh=function(){var s=/[^.]+$/.exec(Ll&&Ll.keys&&Ll.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function qS(s){return!!Hh&&Hh in s}var jS=Function.prototype,GS=jS.toString;function Ki(s){if(s!=null){try{return GS.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var WS=/[\\^$.*+?()[\]{}|]/g,JS=/^\[object .+?Constructor\]$/,KS=Function.prototype,zS=Object.prototype,YS=KS.toString,QS=zS.hasOwnProperty,XS=RegExp("^"+YS.call(QS).replace(WS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ZS(s){if(!Gt(s)||qS(s))return!1;var t=Ku(s)?XS:JS;return t.test(Ki(s))}function ev(s,t){return s==null?void 0:s[t]}function zi(s,t){var e=ev(s,t);return ZS(e)?e:void 0}var tv=zi(ds,"WeakMap");const Yl=tv;var Fh=Object.create,sv=function(){function s(){}return function(t){if(!Gt(t))return{};if(Fh)return Fh(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const rv=sv;function iv(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 nv(){}function rm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var av=800,ov=16,cv=Date.now;function dv(s){var t=0,e=0;return function(){var r=cv(),i=ov-(r-e);if(e=r,i>0){if(++t>=av)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function lv(s){return function(){return s}}var uv=function(){try{var s=zi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const ad=uv;var hv=ad?function(s,t){return ad(s,"toString",{configurable:!0,enumerable:!1,value:lv(t),writable:!0})}:Ju;const pv=hv;var gv=dv(pv);const mv=gv;function fv(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function Tv(s,t,e,r){for(var i=s.length,n=e+(r?1:-1);r?n--:++n<i;)if(t(s[n],n,s))return n;return-1}function Sv(s){return s!==s}function vv(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function yv(s,t,e){return t===t?vv(s,t,e):Tv(s,Sv,e)}function Ev(s,t){var e=s==null?0:s.length;return!!e&&yv(s,t,0)>-1}var Pv=9007199254740991,_v=/^(?:0|[1-9]\d*)$/;function zu(s,t){var e=typeof s;return t=t==null?Pv:t,!!t&&(e=="number"||e!="symbol"&&_v.test(s))&&s>-1&&s%1==0&&s<t}function Yu(s,t,e){t=="__proto__"&&ad?ad(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function yc(s,t){return s===t||s!==s&&t!==t}var Cv=Object.prototype,wv=Cv.hasOwnProperty;function im(s,t,e){var r=s[t];(!(wv.call(s,t)&&yc(r,e))||e===void 0&&!(t in s))&&Yu(s,t,e)}function Ec(s,t,e,r){var i=!e;e||(e={});for(var n=-1,o=t.length;++n<o;){var c=t[n],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?Yu(e,c,d):im(e,c,d)}return e}var qh=Math.max;function Rv(s,t,e){return t=qh(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=qh(r.length-t,0),o=Array(n);++i<n;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),iv(s,this,c)}}function bv(s,t){return mv(Rv(s,t,Ju),s+"")}var kv=9007199254740991;function Qu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=kv}function Pc(s){return s!=null&&Qu(s.length)&&!Ku(s)}function Mv(s,t,e){if(!Gt(e))return!1;var r=typeof t;return(r=="number"?Pc(e)&&zu(t,e.length):r=="string"&&t in e)?yc(e[t],s):!1}function Av(s){return bv(function(t,e){var r=-1,i=e.length,n=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(n=s.length>3&&typeof n=="function"?(i--,n):void 0,o&&Mv(e[0],e[1],o)&&(n=i<3?void 0:n,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,n)}return t})}var Iv=Object.prototype;function fl(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Iv;return s===e}function Dv(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var Ov="[object Arguments]";function jh(s){return _s(s)&&Ji(s)==Ov}var nm=Object.prototype,Nv=nm.hasOwnProperty,Lv=nm.propertyIsEnumerable,Vv=jh(function(){return arguments}())?jh:function(s){return _s(s)&&Nv.call(s,"callee")&&!Lv.call(s,"callee")};const oo=Vv;function xv(){return!1}var am=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gh=am&&typeof module=="object"&&module&&!module.nodeType&&module,Uv=Gh&&Gh.exports===am,Wh=Uv?ds.Buffer:void 0,$v=Wh?Wh.isBuffer:void 0,Bv=$v||xv;const ga=Bv;var Hv="[object Arguments]",Fv="[object Array]",qv="[object Boolean]",jv="[object Date]",Gv="[object Error]",Wv="[object Function]",Jv="[object Map]",Kv="[object Number]",zv="[object Object]",Yv="[object RegExp]",Qv="[object Set]",Xv="[object String]",Zv="[object WeakMap]",ey="[object ArrayBuffer]",ty="[object DataView]",sy="[object Float32Array]",ry="[object Float64Array]",iy="[object Int8Array]",ny="[object Int16Array]",ay="[object Int32Array]",oy="[object Uint8Array]",cy="[object Uint8ClampedArray]",dy="[object Uint16Array]",ly="[object Uint32Array]",pe={};pe[sy]=pe[ry]=pe[iy]=pe[ny]=pe[ay]=pe[oy]=pe[cy]=pe[dy]=pe[ly]=!0;pe[Hv]=pe[Fv]=pe[ey]=pe[qv]=pe[ty]=pe[jv]=pe[Gv]=pe[Wv]=pe[Jv]=pe[Kv]=pe[zv]=pe[Yv]=pe[Qv]=pe[Xv]=pe[Zv]=!1;function uy(s){return _s(s)&&Qu(s.length)&&!!pe[Ji(s)]}function Xu(s){return function(t){return s(t)}}var om=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Qa=om&&typeof module=="object"&&module&&!module.nodeType&&module,hy=Qa&&Qa.exports===om,Vl=hy&&em.process,py=function(){try{var s=Qa&&Qa.require&&Qa.require("util").types;return s||Vl&&Vl.binding&&Vl.binding("util")}catch(t){}}();const ma=py;var Jh=ma&&ma.isTypedArray,gy=Jh?Xu(Jh):uy;const Tl=gy;var my=Object.prototype,fy=my.hasOwnProperty;function cm(s,t){var e=kt(s),r=!e&&oo(s),i=!e&&!r&&ga(s),n=!e&&!r&&!i&&Tl(s),o=e||r||i||n,c=o?Dv(s.length,String):[],d=c.length;for(var l in s)(t||fy.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||zu(l,d)))&&c.push(l);return c}function dm(s,t){return function(e){return s(t(e))}}var Ty=dm(Object.keys,Object);const Sy=Ty;var vy=Object.prototype,yy=vy.hasOwnProperty;function lm(s){if(!fl(s))return Sy(s);var t=[];for(var e in Object(s))yy.call(s,e)&&e!="constructor"&&t.push(e);return t}function Sl(s){return Pc(s)?cm(s):lm(s)}function Ey(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var Py=Object.prototype,_y=Py.hasOwnProperty;function Cy(s){if(!Gt(s))return Ey(s);var t=fl(s),e=[];for(var r in s)r=="constructor"&&(t||!_y.call(s,r))||e.push(r);return e}function _c(s){return Pc(s)?cm(s,!0):Cy(s)}var wy=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ry=/^\w*$/;function Zu(s,t){if(kt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||ml(s)?!0:Ry.test(s)||!wy.test(s)||t!=null&&s in Object(t)}var by=zi(Object,"create");const co=by;function ky(){this.__data__=co?co(null):{},this.size=0}function My(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Ay="__lodash_hash_undefined__",Iy=Object.prototype,Dy=Iy.hasOwnProperty;function Oy(s){var t=this.__data__;if(co){var e=t[s];return e===Ay?void 0:e}return Dy.call(t,s)?t[s]:void 0}var Ny=Object.prototype,Ly=Ny.hasOwnProperty;function Vy(s){var t=this.__data__;return co?t[s]!==void 0:Ly.call(t,s)}var xy="__lodash_hash_undefined__";function Uy(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=co&&t===void 0?xy:t,this}function Gi(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])}}Gi.prototype.clear=ky;Gi.prototype.delete=My;Gi.prototype.get=Oy;Gi.prototype.has=Vy;Gi.prototype.set=Uy;function $y(){this.__data__=[],this.size=0}function vl(s,t){for(var e=s.length;e--;)if(yc(s[e][0],t))return e;return-1}var By=Array.prototype,Hy=By.splice;function Fy(s){var t=this.__data__,e=vl(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():Hy.call(t,e,1),--this.size,!0}function qy(s){var t=this.__data__,e=vl(t,s);return e<0?void 0:t[e][1]}function jy(s){return vl(this.__data__,s)>-1}function Gy(s,t){var e=this.__data__,r=vl(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function rr(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])}}rr.prototype.clear=$y;rr.prototype.delete=Fy;rr.prototype.get=qy;rr.prototype.has=jy;rr.prototype.set=Gy;var Wy=zi(ds,"Map");const lo=Wy;function Jy(){this.size=0,this.__data__={hash:new Gi,map:new(lo||rr),string:new Gi}}function Ky(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function yl(s,t){var e=s.__data__;return Ky(t)?e[typeof t=="string"?"string":"hash"]:e.map}function zy(s){var t=yl(this,s).delete(s);return this.size-=t?1:0,t}function Yy(s){return yl(this,s).get(s)}function Qy(s){return yl(this,s).has(s)}function Xy(s,t){var e=yl(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function ir(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])}}ir.prototype.clear=Jy;ir.prototype.delete=zy;ir.prototype.get=Yy;ir.prototype.has=Qy;ir.prototype.set=Xy;var Zy="Expected a function";function eh(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(Zy);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],n=e.cache;if(n.has(i))return n.get(i);var o=s.apply(this,r);return e.cache=n.set(i,o)||n,o};return e.cache=new(eh.Cache||ir),e}eh.Cache=ir;var eE=500;function tE(s){var t=eh(s,function(r){return e.size===eE&&e.clear(),r}),e=t.cache;return t}var sE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,rE=/\\(\\)?/g,iE=tE(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(sE,function(e,r,i,n){t.push(i?n.replace(rE,"$1"):r||e)}),t});const nE=iE;function aE(s){return s==null?"":sm(s)}function um(s,t){return kt(s)?s:Zu(s,t)?[s]:nE(aE(s))}var oE=1/0;function El(s){if(typeof s=="string"||ml(s))return s;var t=s+"";return t=="0"&&1/s==-oE?"-0":t}function hm(s,t){t=um(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[El(t[e++])];return e&&e==r?s:void 0}function cE(s,t,e){var r=s==null?void 0:hm(s,t);return r===void 0?e:r}function pm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var dE=dm(Object.getPrototypeOf,Object);const th=dE;var lE="[object Object]",uE=Function.prototype,hE=Object.prototype,gm=uE.toString,pE=hE.hasOwnProperty,gE=gm.call(Object);function mE(s){if(!_s(s)||Ji(s)!=lE)return!1;var t=th(s);if(t===null)return!0;var e=pE.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&gm.call(e)==gE}function fE(){this.__data__=new rr,this.size=0}function TE(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function SE(s){return this.__data__.get(s)}function vE(s){return this.__data__.has(s)}var yE=200;function EE(s,t){var e=this.__data__;if(e instanceof rr){var r=e.__data__;if(!lo||r.length<yE-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new ir(r)}return e.set(s,t),this.size=e.size,this}function cs(s){var t=this.__data__=new rr(s);this.size=t.size}cs.prototype.clear=fE;cs.prototype.delete=TE;cs.prototype.get=SE;cs.prototype.has=vE;cs.prototype.set=EE;function PE(s,t){return s&&Ec(t,Sl(t),s)}function _E(s,t){return s&&Ec(t,_c(t),s)}var mm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Kh=mm&&typeof module=="object"&&module&&!module.nodeType&&module,CE=Kh&&Kh.exports===mm,zh=CE?ds.Buffer:void 0,Yh=zh?zh.allocUnsafe:void 0;function fm(s,t){if(t)return s.slice();var e=s.length,r=Yh?Yh(e):new s.constructor(e);return s.copy(r),r}function wE(s,t){for(var e=-1,r=s==null?0:s.length,i=0,n=[];++e<r;){var o=s[e];t(o,e,s)&&(n[i++]=o)}return n}function Tm(){return[]}var RE=Object.prototype,bE=RE.propertyIsEnumerable,Qh=Object.getOwnPropertySymbols,kE=Qh?function(s){return s==null?[]:(s=Object(s),wE(Qh(s),function(t){return bE.call(s,t)}))}:Tm;const sh=kE;function ME(s,t){return Ec(s,sh(s),t)}var AE=Object.getOwnPropertySymbols,IE=AE?function(s){for(var t=[];s;)pm(t,sh(s)),s=th(s);return t}:Tm;const Sm=IE;function DE(s,t){return Ec(s,Sm(s),t)}function vm(s,t,e){var r=t(s);return kt(s)?r:pm(r,e(s))}function Ql(s){return vm(s,Sl,sh)}function OE(s){return vm(s,_c,Sm)}var NE=zi(ds,"DataView");const Xl=NE;var LE=zi(ds,"Promise");const Zl=LE;var VE=zi(ds,"Set");const hn=VE;var Xh="[object Map]",xE="[object Object]",Zh="[object Promise]",ep="[object Set]",tp="[object WeakMap]",sp="[object DataView]",UE=Ki(Xl),$E=Ki(lo),BE=Ki(Zl),HE=Ki(hn),FE=Ki(Yl),Yr=Ji;(Xl&&Yr(new Xl(new ArrayBuffer(1)))!=sp||lo&&Yr(new lo)!=Xh||Zl&&Yr(Zl.resolve())!=Zh||hn&&Yr(new hn)!=ep||Yl&&Yr(new Yl)!=tp)&&(Yr=function(s){var t=Ji(s),e=t==xE?s.constructor:void 0,r=e?Ki(e):"";if(r)switch(r){case UE:return sp;case $E:return Xh;case BE:return Zh;case HE:return ep;case FE:return tp}return t});const fa=Yr;var qE=Object.prototype,jE=qE.hasOwnProperty;function GE(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&jE.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var WE=ds.Uint8Array;const od=WE;function rh(s){var t=new s.constructor(s.byteLength);return new od(t).set(new od(s)),t}function JE(s,t){var e=t?rh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var KE=/\w*$/;function zE(s){var t=new s.constructor(s.source,KE.exec(s));return t.lastIndex=s.lastIndex,t}var rp=Ps?Ps.prototype:void 0,ip=rp?rp.valueOf:void 0;function YE(s){return ip?Object(ip.call(s)):{}}function ym(s,t){var e=t?rh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var QE="[object Boolean]",XE="[object Date]",ZE="[object Map]",eP="[object Number]",tP="[object RegExp]",sP="[object Set]",rP="[object String]",iP="[object Symbol]",nP="[object ArrayBuffer]",aP="[object DataView]",oP="[object Float32Array]",cP="[object Float64Array]",dP="[object Int8Array]",lP="[object Int16Array]",uP="[object Int32Array]",hP="[object Uint8Array]",pP="[object Uint8ClampedArray]",gP="[object Uint16Array]",mP="[object Uint32Array]";function fP(s,t,e){var r=s.constructor;switch(t){case nP:return rh(s);case QE:case XE:return new r(+s);case aP:return JE(s,e);case oP:case cP:case dP:case lP:case uP:case hP:case pP:case gP:case mP:return ym(s,e);case ZE:return new r;case eP:case rP:return new r(s);case tP:return zE(s);case sP:return new r;case iP:return YE(s)}}function Em(s){return typeof s.constructor=="function"&&!fl(s)?rv(th(s)):{}}var TP="[object Map]";function SP(s){return _s(s)&&fa(s)==TP}var np=ma&&ma.isMap,vP=np?Xu(np):SP;const yP=vP;var EP="[object Set]";function PP(s){return _s(s)&&fa(s)==EP}var ap=ma&&ma.isSet,_P=ap?Xu(ap):PP;const CP=_P;var wP=1,RP=2,bP=4,Pm="[object Arguments]",kP="[object Array]",MP="[object Boolean]",AP="[object Date]",IP="[object Error]",_m="[object Function]",DP="[object GeneratorFunction]",OP="[object Map]",NP="[object Number]",Cm="[object Object]",LP="[object RegExp]",VP="[object Set]",xP="[object String]",UP="[object Symbol]",$P="[object WeakMap]",BP="[object ArrayBuffer]",HP="[object DataView]",FP="[object Float32Array]",qP="[object Float64Array]",jP="[object Int8Array]",GP="[object Int16Array]",WP="[object Int32Array]",JP="[object Uint8Array]",KP="[object Uint8ClampedArray]",zP="[object Uint16Array]",YP="[object Uint32Array]",ue={};ue[Pm]=ue[kP]=ue[BP]=ue[HP]=ue[MP]=ue[AP]=ue[FP]=ue[qP]=ue[jP]=ue[GP]=ue[WP]=ue[OP]=ue[NP]=ue[Cm]=ue[LP]=ue[VP]=ue[xP]=ue[UP]=ue[JP]=ue[KP]=ue[zP]=ue[YP]=!0;ue[IP]=ue[_m]=ue[$P]=!1;function Xa(s,t,e,r,i,n){var o,c=t&wP,d=t&RP,l=t&bP;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!Gt(s))return s;var u=kt(s);if(u){if(o=GE(s),!c)return rm(s,o)}else{var p=fa(s),m=p==_m||p==DP;if(ga(s))return fm(s,c);if(p==Cm||p==Pm||m&&!i){if(o=d||m?{}:Em(s),!c)return d?DE(s,_E(o,s)):ME(s,PE(o,s))}else{if(!ue[p])return i?s:{};o=fP(s,p,c)}}n||(n=new cs);var T=n.get(s);if(T)return T;n.set(s,o),CP(s)?s.forEach(function(k){o.add(Xa(k,t,e,k,s,n))}):yP(s)&&s.forEach(function(k,C){o.set(C,Xa(k,t,e,C,s,n))});var E=l?d?OE:Ql:d?_c:Sl,P=u?void 0:E(s);return fv(P||s,function(k,C){P&&(C=k,k=s[C]),im(o,C,Xa(k,t,e,C,s,n))}),o}var QP=4;function XP(s){return Xa(s,QP)}var ZP=1,e_=4;function ih(s){return Xa(s,ZP|e_)}var t_="__lodash_hash_undefined__";function s_(s){return this.__data__.set(s,t_),this}function r_(s){return this.__data__.has(s)}function uo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new ir;++t<e;)this.add(s[t])}uo.prototype.add=uo.prototype.push=s_;uo.prototype.has=r_;function i_(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 wm(s,t){return s.has(t)}var n_=1,a_=2;function Rm(s,t,e,r,i,n){var o=e&n_,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var p=-1,m=!0,T=e&a_?new uo:void 0;for(n.set(s,t),n.set(t,s);++p<c;){var E=s[p],P=t[p];if(r)var k=o?r(P,E,p,t,s,n):r(E,P,p,s,t,n);if(k!==void 0){if(k)continue;m=!1;break}if(T){if(!i_(t,function(C,I){if(!wm(T,I)&&(E===C||i(E,C,e,r,n)))return T.push(I)})){m=!1;break}}else if(!(E===P||i(E,P,e,r,n))){m=!1;break}}return n.delete(s),n.delete(t),m}function o_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function nh(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var c_=1,d_=2,l_="[object Boolean]",u_="[object Date]",h_="[object Error]",p_="[object Map]",g_="[object Number]",m_="[object RegExp]",f_="[object Set]",T_="[object String]",S_="[object Symbol]",v_="[object ArrayBuffer]",y_="[object DataView]",op=Ps?Ps.prototype:void 0,xl=op?op.valueOf:void 0;function E_(s,t,e,r,i,n,o){switch(e){case y_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case v_:return!(s.byteLength!=t.byteLength||!n(new od(s),new od(t)));case l_:case u_:case g_:return yc(+s,+t);case h_:return s.name==t.name&&s.message==t.message;case m_:case T_:return s==t+"";case p_:var c=o_;case f_:var d=r&c_;if(c||(c=nh),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=d_,o.set(s,t);var u=Rm(c(s),c(t),r,i,n,o);return o.delete(s),u;case S_:if(xl)return xl.call(s)==xl.call(t)}return!1}var P_=1,__=Object.prototype,C_=__.hasOwnProperty;function w_(s,t,e,r,i,n){var o=e&P_,c=Ql(s),d=c.length,l=Ql(t),u=l.length;if(d!=u&&!o)return!1;for(var p=d;p--;){var m=c[p];if(!(o?m in t:C_.call(t,m)))return!1}var T=n.get(s),E=n.get(t);if(T&&E)return T==t&&E==s;var P=!0;n.set(s,t),n.set(t,s);for(var k=o;++p<d;){m=c[p];var C=s[m],I=t[m];if(r)var V=o?r(I,C,m,t,s,n):r(C,I,m,s,t,n);if(!(V===void 0?C===I||i(C,I,e,r,n):V)){P=!1;break}k||(k=m=="constructor")}if(P&&!k){var L=s.constructor,B=t.constructor;L!=B&&"constructor"in s&&"constructor"in t&&!(typeof L=="function"&&L instanceof L&&typeof B=="function"&&B instanceof B)&&(P=!1)}return n.delete(s),n.delete(t),P}var R_=1,cp="[object Arguments]",dp="[object Array]",Ac="[object Object]",b_=Object.prototype,lp=b_.hasOwnProperty;function k_(s,t,e,r,i,n){var o=kt(s),c=kt(t),d=o?dp:fa(s),l=c?dp:fa(t);d=d==cp?Ac:d,l=l==cp?Ac:l;var u=d==Ac,p=l==Ac,m=d==l;if(m&&ga(s)){if(!ga(t))return!1;o=!0,u=!1}if(m&&!u)return n||(n=new cs),o||Tl(s)?Rm(s,t,e,r,i,n):E_(s,t,d,e,r,i,n);if(!(e&R_)){var T=u&&lp.call(s,"__wrapped__"),E=p&&lp.call(t,"__wrapped__");if(T||E){var P=T?s.value():s,k=E?t.value():t;return n||(n=new cs),i(P,k,e,r,n)}}return m?(n||(n=new cs),w_(s,t,e,r,i,n)):!1}function Pl(s,t,e,r,i){return s===t?!0:s==null||t==null||!_s(s)&&!_s(t)?s!==s&&t!==t:k_(s,t,e,r,Pl,i)}var M_=1,A_=2;function I_(s,t,e,r){var i=e.length,n=i,o=!r;if(s==null)return!n;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<n;){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 cs;if(r)var m=r(l,u,d,s,t,p);if(!(m===void 0?Pl(u,l,M_|A_,r,p):m))return!1}}return!0}function bm(s){return s===s&&!Gt(s)}function D_(s){for(var t=Sl(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,bm(i)]}return t}function km(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function O_(s){var t=D_(s);return t.length==1&&t[0][2]?km(t[0][0],t[0][1]):function(e){return e===s||I_(e,s,t)}}function N_(s,t){return s!=null&&t in Object(s)}function L_(s,t,e){t=um(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=El(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&Qu(i)&&zu(o,i)&&(kt(s)||oo(s)))}function V_(s,t){return s!=null&&L_(s,t,N_)}var x_=1,U_=2;function $_(s,t){return Zu(s)&&bm(t)?km(El(s),t):function(e){var r=cE(e,s);return r===void 0&&r===t?V_(e,s):Pl(t,r,x_|U_)}}function B_(s){return function(t){return t==null?void 0:t[s]}}function H_(s){return function(t){return hm(t,s)}}function F_(s){return Zu(s)?B_(El(s)):H_(s)}function q_(s){return typeof s=="function"?s:s==null?Ju:typeof s=="object"?kt(s)?$_(s[0],s[1]):O_(s):F_(s)}function j_(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var G_=j_();const W_=G_;var J_=function(){return ds.Date.now()};const Ul=J_;var K_="Expected a function",z_=Math.max,Y_=Math.min;function ah(s,t,e){var r,i,n,o,c,d,l=0,u=!1,p=!1,m=!0;if(typeof s!="function")throw new TypeError(K_);t=Bh(t)||0,Gt(e)&&(u=!!e.leading,p="maxWait"in e,n=p?z_(Bh(e.maxWait)||0,t):n,m="trailing"in e?!!e.trailing:m);function T($){var z=r,De=i;return r=i=void 0,l=$,o=s.apply(De,z),o}function E($){return l=$,c=setTimeout(C,t),u?T($):o}function P($){var z=$-d,De=$-l,Tt=t-z;return p?Y_(Tt,n-De):Tt}function k($){var z=$-d,De=$-l;return d===void 0||z>=t||z<0||p&&De>=n}function C(){var $=Ul();if(k($))return I($);c=setTimeout(C,P($))}function I($){return c=void 0,m&&r?T($):(r=i=void 0,o)}function V(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function L(){return c===void 0?o:I(Ul())}function B(){var $=Ul(),z=k($);if(r=arguments,i=this,d=$,z){if(c===void 0)return E(d);if(p)return clearTimeout(c),c=setTimeout(C,t),T(d)}return c===void 0&&(c=setTimeout(C,t)),o}return B.cancel=V,B.flush=L,B}function eu(s,t,e){(e!==void 0&&!yc(s[t],e)||e===void 0&&!(t in s))&&Yu(s,t,e)}function Q_(s){return _s(s)&&Pc(s)}function tu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function X_(s){return Ec(s,_c(s))}function Z_(s,t,e,r,i,n,o){var c=tu(s,e),d=tu(t,e),l=o.get(d);if(l){eu(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,p=u===void 0;if(p){var m=kt(d),T=!m&&ga(d),E=!m&&!T&&Tl(d);u=d,m||T||E?kt(c)?u=c:Q_(c)?u=rm(c):T?(p=!1,u=fm(d,!0)):E?(p=!1,u=ym(d,!0)):u=[]:mE(d)||oo(d)?(u=c,oo(c)?u=X_(c):(!Gt(c)||Ku(c))&&(u=Em(d))):p=!1}p&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),eu(s,e,u)}function Mm(s,t,e,r,i){s!==t&&W_(t,function(n,o){if(i||(i=new cs),Gt(n))Z_(s,t,o,e,Mm,r,i);else{var c=r?r(tu(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),eu(s,o,c)}},_c)}function eC(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 tC="[object Map]",sC="[object Set]",rC=Object.prototype,iC=rC.hasOwnProperty;function nC(s){if(s==null)return!0;if(Pc(s)&&(kt(s)||typeof s=="string"||typeof s.splice=="function"||ga(s)||Tl(s)||oo(s)))return!s.length;var t=fa(s);if(t==tC||t==sC)return!s.size;if(fl(s))return!lm(s).length;for(var e in s)if(iC.call(s,e))return!1;return!0}function aC(s,t){return Pl(s,t)}var oC=Av(function(s,t,e){Mm(s,t,e)});const lr=oC;var cC=1/0,dC=hn&&1/nh(new hn([,-0]))[1]==cC?function(s){return new hn(s)}:nv;const lC=dC;var uC=200;function Am(s,t,e){var r=-1,i=Ev,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=eC;else if(n>=uC){var l=t?null:lC(s);if(l)return nh(l);o=!1,i=wm,d=new uo}else d=t?[]:c;e:for(;++r<n;){var u=s[r],p=t?t(u):u;if(u=e||u!==0?u:0,o&&p===p){for(var m=d.length;m--;)if(d[m]===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 hC(s){return s&&s.length?Am(s):[]}function pC(s,t){return s&&s.length?Am(s,q_(t)):[]}function Fc(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 gC={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},up={STAGING:"staging",PROD:"prod"},mC={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 Ta(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function fC({baseURI:s}){return s.includes("staging.realtime")?up.STAGING:up.PROD}function pn({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function TC(s){const t=s.getValue("baseURI");return{location:pn({servicePrefix:"location",baseURI:t}),locationLegacy:pn({servicePrefix:"location-legacy",baseURI:t}),daCollector:pn({servicePrefix:"da-collector",baseURI:t})}}const SC='<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>',vC='<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>',Ic=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(n=>{n(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((n,o)=>{r.onload=()=>{n(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"}},yC=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,su="__rtk_plugins__",EC=[su];function Im(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(ri.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function PC(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"],n=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(n<o)return!1}return!0}function Dm(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var n;if([null,void 0,NaN].includes(s[r])||t&&(((n=t.match(/\./g))==null?void 0:n.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?Dm(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function hp(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Dm(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 Im(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(n){const o=Fc(n);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=Hr.getContext(this.meetingMetadata.peerId);return`https://${pn({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 n=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=n,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,n)=>{const o=n.value;return n.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 m=performance.now();m-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:m-u})}).catch(()=>{const m=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:m-u})}),p},n}}injectContext(t){var i;const e=qr.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:Fc(r.error)});const n=Hr.getContext(this.meetingMetadata.peerId);if(Im(n)&&(nC(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!PC(n,t))try{const c=hp(n,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:Fc(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 n=Hr.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:hp(n,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:n.getValue("sdkName"),logs:t});let c;const d={Authorization:`Bearer ${n.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(n){e||(this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Fc(n)}),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 _C(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)},n=l=>{var u;(u=e.get(l))==null||u.forEach(p=>{try{p(t[l])}catch(m){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,p=!0)=>{t[l]=u,p&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class CC{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 hS;this.contexts.set(t,_C(e)),this.contexts.get(t).setValue("peerSessionStore",new pS(i));const n=new Zg;return n.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",n),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 Hr=new CC,wC={"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"},qc={"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","0604":"Active plugins store is not available yet","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(qc).forEach(s=>{qc[s]=`{${wC[s.slice(0,2)]}} ${qc[s]}`});class R extends Error{constructor(e,r,i=void 0,n=!1){super(e);h(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?qc[this.code]:"";this.message=`${o}: ${c}
6
- ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=Hr.getContext(Hr.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 Dc(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 pp(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Dc(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Dc(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Dc(this,t,e,o)}):n}catch(n){Dc(this,t,e,n)}},s}function RC(s,t){return(e,r,i)=>{if(i)return pp(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,pp(o,s,t))}}}const et=s=>RC(Error,s);var Xs=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Xs||{}),q=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(q||{}),Zp;typeof process!="undefined"&&(Zp=process==null?void 0:process.env)!=null&&Zp.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Om=[-2,-1,0,1,2],bC=[0,1,2,3,4];function kC(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 MC=(s,t,e)=>{let r,i,n;if(t==0)r=i=n=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),n=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(n*255)]},AC=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let n,o;const c=(r+i)/2;if(r==i)n=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:n=(t-e)/d+(t<e?6:0);break;case t:n=(e-s)/d+2;break;case e:n=(s-t)/d+4;break}n/=6}return[n,o,c]},IC=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Nm=(s,t=Om,e=.4)=>{const r=[],[i,n,o]=kC(s),[c,d,l]=AC(i,n,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(k=>k===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const m=5-p,T=p+1,E=(100-u)/m,P=u/T;for(const k of t){let C;k<0?C=u+k*P*e:k>0?C=u+k*E*e:C=u;const[I,V,L]=MC(c,d,C/100);r.push(IC(I,V,L))}return r},gp={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"}},DC=s=>{const[t,e,r,i,n]=Nm(s,Om);return{300:t,400:e,500:r,600:i,700:n}},OC=s=>{if(s==="#FFFFFF")return gp.light.background;if(s==="#000000")return gp.dark.background;const[t,e,r,i,n]=Nm(s,bC);return{1e3:t,900:e,800:r,700:i,600:n}},NC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:DC("#2160FD"),background:OC("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Lm(){return ih(NC)}var LC={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:Lm(),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 VC(){return ih(LC)}var xC={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:Lm(),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 oh(){return ih(xC)}function UC(){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(n=>{var o;return(o=n.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 Sa extends Ze.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 n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}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 At extends Ze.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 n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}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 $C(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 mp=1080,fp=1920,BC=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let p=d*u,m=l*u,T,E,P,k,C=1;return p<e&&(C=e/p),Math.abs(C-1)<1e-14&&m<r&&(C=r/m),p*=C,m*=C,P=d/(p/e),k=l/(m/r),T=(d-P)*o,E=(l-k)*c,T<0&&(T=0),E<0&&(E=0),P>d&&(P=d),k>l&&(k=l),[T,E,P,k,s,t,e,r]};var Lt,ii,Ye,Vt,Pe,Qt,Ds,tt,ke,Tn,Sn,Os,vn;const kh=class extends At{constructor(e,r,i,n){const o=e.getValue("logger");super(o);g(this,Lt,void 0);g(this,ii,void 0);g(this,Ye,void 0);g(this,Vt,void 0);g(this,Pe,{height:mp,width:fp});g(this,Qt,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,Ds,void 0);g(this,tt,{});g(this,ke,void 0);g(this,Tn,void 0);g(this,Sn,void 0);g(this,Os,void 0);g(this,vn,!1);h(this,"cleanupEventListeners",()=>{a(this,ii).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,ke).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,ke).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(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"&&(a(this,ke).videoEnabled?a(this,ke).disableVideo():a(this,ke).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,ke).audioEnabled?a(this,ke).disableAudio():a(this,ke).enableAudio(),this.emit("micToggled")),e==="END"&&(a(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&&a(this,Os)==="active"){this.disable(!0);return}a(this,tt)!==void 0&&this.paintCanvas(),a(this,Ds)!==void 0&&f(this,Ds,requestAnimationFrame(()=>this.animate()))});h(this,"disable",(e=!1)=>{f(this,Os,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,Ds)),e!==!0&&document.body.removeChild(a(this,Ye)),f(this,Ds,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,ii,e),f(this,Os,"idle"),f(this,ke,r),f(this,Qt,{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),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Ic(SC),n=await Ic(vC)}catch(o){}return new kh(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,Sn,r);break;case"pin":f(this,Tn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,Sn,await Ic(r));break;case"pin":f(this,Tn,await Ic(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,Ye,document.createElement("div")),a(this,Ye).style.width="0.1px",a(this,Ye).style.height="0.1px",a(this,Ye).style.overflow="hidden",a(this,Ye).style.position="absolute",a(this,Ye).style.bottom="0",a(this,Ye).style.right="0",a(this,Ye).style.opacity="0",a(this,Ye).appendChild(a(this,Vt))}setupEventListeners(){a(this,ii).subscribe("stageStatus",this.handlePipMediaControls),a(this,ke).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,ke).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,ke).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Pe).height,e.width=a(this,Pe).width,f(this,Lt,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||a(this,ke).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,ke).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,tt)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,Lt)===void 0)return;const o=a(this,Lt).getContext("2d"),c=a(this,Lt).width,d=0,l=0,u=r-d*2,p=i-d*2,m=Math.floor(c/u),T=Math.floor(e/m),P=e%m*(u+d)+d,k=T*(p+d)+d,{displayText:C,image:I}=n!=null?n:{};o.fillStyle=C||I?a(this,Qt).videoBackground:a(this,Qt).background,o.strokeStyle=a(this,Qt).brand,o.beginPath(),o.moveTo(P+l,k),o.arcTo(P+u,k,P+u,k+l,l),o.arcTo(P+u,k+p,P+u-l,k+p,l),o.arcTo(P,k+p,P,k+p-l,l),o.arcTo(P,k,P+l,k,l),o.closePath(),o.fill(),o.stroke();const V=u/6,L=u/2+P,B=p/2+k;o.save(),(C||I)&&(o.beginPath(),o.arc(L,B,V,0,Math.PI*2),o.fillStyle=a(this,Qt).brand,o.fill(),I?(o.clip(),o.drawImage(I,L-V,B-V,V*2,V*2),o.restore()):C&&(o.fillStyle=a(this,Qt).textOnBrand,o.font=`${V/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(C,L,B)),this.drawIcons(n,P,k,Math.max(u,p)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,p=m=>{const T=a(this,Lt).getContext("2d");T.save(),T.fillStyle=a(this,Qt).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 m=="string"?(T.font=`${o/1.5}px sans-serif`,T.fillStyle=a(this,Qt).text,T.textAlign="center",T.textBaseline="top",T.fillText(m,o/2+l,u+c)):T.drawImage(m,l+c,u+c,o-c*2,o-c*2),l+=o+c,T.restore()};e.pinned&&p(a(this,Tn)),e.handRaised&&p(a(this,Sn)),e.reaction&&p(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,Lt)===void 0)return;const n=a(this,Lt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Pe).height-5;){let p=0;for(;p<a(this,Pe).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const m=o[d].element,[T,E,P,k,C,I,V,L]=BC(p,c,e,r,m.videoWidth,m.videoHeight);((u=m==null?void 0:m.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(m,T,E,P,k,-1*C,I,-1*V,L),n.restore()):n.drawImage(m,T,E,P,k,C,I,V,L),this.drawIcons(o[d],C,I,Math.max(V,L))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,p+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,Pe).width,a(this,Pe).height];case 2:return[Math.floor(a(this,Pe).width/2),a(this,Pe).height];case 3:case 4:return[Math.floor(a(this,Pe).width/2),Math.floor(a(this,Pe).height/2)];case 5:case 6:return[Math.floor(a(this,Pe).width/3),Math.floor(a(this,Pe).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Pe).width/3),Math.floor(a(this,Pe).height/3)];default:return[Math.floor(a(this,Pe).width/3),Math.floor(a(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=a(this,ke).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,vn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,Ye))try{document.body.removeChild(a(this,Ye))}catch(e){}this.removeAllSources(),f(this,Lt,void 0),f(this,Vt,void 0),f(this,Ds,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(a(this,vn))return;f(this,vn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Pe,{height:e!=null?e:mp,width:r!=null?r:fp}),i.height=a(this,Pe).height,i.width=a(this,Pe).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,Lt).captureStream(24),f(this,Vt,i),a(this,Vt).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,Vt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,tt)[e]!==void 0&&(a(this,tt)[e].enabled=!0)}disableSource(e){a(this,tt)[e]!==void 0&&(a(this,tt)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,tt)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?$C(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=a(this,tt)[e];i&&(a(this,tt)[e]={...i,...r})}removeSource(e){delete a(this,tt)[e]}removePinnedSource(){Object.values(a(this,tt)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,tt,{})}enable(){f(this,Os,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,ke).videoEnabled),this.updateMediaSession("MIC",a(this,ke).audioEnabled),document.body.appendChild(a(this,Ye)),f(this,Ds,requestAnimationFrame(()=>this.animate())),a(this,Vt).onloadedmetadata=()=>{a(this,Vt).requestPictureInPicture().then(()=>{f(this,Os,"active")})},a(this,Vt).readyState===4&&a(this,Vt).requestPictureInPicture().then(()=>{f(this,Os,"active")})}};let ru=kh;Lt=new WeakMap,ii=new WeakMap,Ye=new WeakMap,Vt=new WeakMap,Pe=new WeakMap,Qt=new WeakMap,Ds=new WeakMap,tt=new WeakMap,ke=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,Os=new WeakMap,vn=new WeakMap;var tr;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(tr||(tr={}));var Zs;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Zs||(Zs={}));class HC 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 Vm=new HC;class FC 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 qC=new FC;class jC extends S.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new jC;class GC extends S.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",tr]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ls=new GC;class WC 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 JC=new WC;class KC 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:()=>ls},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>JC}])}}const zC=new KC;class YC 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 QC=new YC;class XC extends S.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const xm=new XC;class ZC extends S.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls}])}}const ew=new ZC;class tw extends S.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls}])}}new tw;class sw 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 rw=new sw;class iw 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 nw=new iw;class aw 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 aw;class ow 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 ow;class cw 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",Zs]},{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:()=>Vm}])}}const Cc=new cw;class dw extends S.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Cc},{no:3,name:"producer_track",kind:"message",T:()=>nw},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const lw=new dw;class uw extends S.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>lw}}])}}const Um=new uw;class hw extends S.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Sp},{no:2,name:"receiver",kind:"message",T:()=>Sp}])}}const $m=new hw;class pw extends S.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Vm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>qC}])}}const Tp=new pw;class gw extends S.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Tp},{no:2,name:"video",kind:"message",T:()=>Tp}])}}const Sp=new gw;class mw 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 fw=new mw;class Tw 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 Bm=new Tw;class Sw 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 vw=new Sw;class yw 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:()=>vw},{no:9,name:"capabilities",kind:"message",T:()=>$m}])}}const Ew=new yw;class Pw extends S.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const _w=new Pw;class Cw extends S.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const ww=new Cw;class Rw 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 Rw;class bw 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:()=>fw},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Bm}])}}const kw=new bw;class Mw extends S.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>kw},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Aw=new Mw;class Iw extends S.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Bm},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const Dw=new Iw;class Ow extends S.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Dw},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Nw=new Ow;class Lw 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:()=>ls},{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 Vw=new Lw;class xw extends S.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new xw;class Uw extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const $w=new Uw;class Bw 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 Oc=new Bw;class Hw 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 Hw;class Fw extends S.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const qw=new Fw;class jw 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:()=>ls},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Gw=new jw;class Ww extends S.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Ww;class Jw extends S.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Hm=new Jw;class Kw 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 zw=new Kw;class Yw 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 Qw=new Yw;class Xw 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 Zw=new Xw;class eR 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 tR=new eR;class sR 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 rR=new sR;class iR extends S.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new iR;class nR 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:()=>Cc},{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:()=>$m}])}}const Fm=new nR;class aR 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 iu=new aR;class oR 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 cR=new oR;class dR extends S.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>cR}])}}const vp=new dR;class lR extends S.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new lR;class uR extends S.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>tR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Fm},{no:3,name:"selected_peers",kind:"message",T:()=>iu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const nu=new uR;class hR extends S.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const pR=new hR;class gR 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:()=>Um}])}}new gR;class mR 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:()=>Um},{no:3,name:"description",kind:"message",T:()=>ls}])}}const fR=new mR;class TR 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:()=>ls}])}}const SR=new TR;class vR extends S.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>rw}])}}new vR;class yR 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 yR;class ER extends S.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new ER;class PR extends S.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new PR;class _R extends S.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new _R;class CR extends S.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ls}])}}const wR=new CR;class RR extends S.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ls}])}}const bR=new RR;class kR extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new kR;class MR extends S.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new MR;class AR extends S.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new AR;class IR extends S.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const DR=new IR;class OR extends S.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const NR=new OR;class LR extends S.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const VR=new LR;class xR extends S.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Fm}])}}const yp=new xR;class UR 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 Ep=new UR;class $R extends S.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Ep},{no:3,name:"screenshare",kind:"message",T:()=>Ep}])}}const BR=new $R;class HR 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:()=>xm},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>BR}])}}new HR;class FR 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:()=>Cc}])}}const qR=new FR;class jR 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:()=>Cc},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Pp=new jR;class GR 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:()=>Cc}])}}const WR=new GR;class JR extends S.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const au=new JR;class KR extends S.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const _p=new KR;class zR extends S.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new zR;class YR extends S.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new YR;class QR extends S.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new QR;class XR 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 XR;class ZR extends S.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new ZR;class eb extends S.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new eb;class tb 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 $l=new tb;class sb 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 sb;class rb 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 ib=new rb;var qi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(qi||(qi={}));var zs;(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"})(zs||(zs={}));var ou;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(ou||(ou={}));var cu;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(cu||(cu={}));var cd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(cd||(cd={}));class nb 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 ab=new nb;class ob 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",zs,"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:()=>ab}])}}const _l=new ob;class cb extends S.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>_l}])}}const en=new cb;class db 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",zs,"STAGE_TYPE_"]}])}}const Cp=new db;class lb 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 ub=new lb;class hb extends S.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>_l}])}}const Bl=new hb;class pb extends S.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const wp=new pb;class gb 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:()=>fb},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const qm=new gb;class mb 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",qi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const fb=new mb;class Tb extends S.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>qm}])}}const Rp=new Tb;class Sb extends S.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const jm=new Sb;class vb 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 vb;class yb extends S.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>_l},{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",cd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const Eb=new yb;class Pb extends S.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>_l},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const _b=new Pb;class Cb extends S.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>qm}])}}new Cb;class wb extends S.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new wb;class Rb 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 ch=new Rb;class bb 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 kb=new bb;class Mb 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:()=>kb}])}}const bp=new Mb;class Ab extends S.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>bp},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>bp}])}}const Ib=new Ab;class Db extends S.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const Ob=new Db;class Nb extends S.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Ob}])}}const Lb=new Nb;class Vb 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:()=>ch}])}}const xb=new Vb;class Ub extends S.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>xb}])}}const kp=new Ub;class $b 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 Bb=new $b;class Hb extends S.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Bb}])}}new Hb;class Fb extends S.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const qb=new Fb;class jb extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>qb}])}}const Gb=new jb;class Wb extends S.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>zb}])}}const Jb=new Wb;class Kb 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:()=>ch}])}}const zb=new Kb;class Yb 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 Qb=new Yb;class Xb 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:()=>Qb}])}}const Zb=new Xb;class ek 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:()=>ch}])}}const Gm=new ek;class tk extends S.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Gm}])}}new tk;class sk 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 rk=new sk;class ik extends S.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>ok}])}}const nk=new ik;class ak 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 ok=new ak;class ck extends S.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Wm=new ck;class dk 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",cu,"BROADCAST_TYPE_"]}])}}const $a=new dk;class lk extends S.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const uk=new lk;class hk extends S.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const pk=new hk;class gk 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 mk=new gk;class fk extends S.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>mk}])}}const Mp=new fk;class Tk 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 Ap=new Tk;var du;(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"})(du||(du={}));var Ur;(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"})(Ur||(Ur={}));class Sk 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 vk=new Sk;class yk 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 Ek=new yk;class Pk 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 _k=new Pk;class Ck 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 wk=new Ck;class Rk extends S.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>_k},{no:2,name:"private",kind:"message",T:()=>wk}])}}const bk=new Rk;class kk 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 Mk=new kk;class Ak extends S.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ur,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ur,"STREAM_PERMISSION_TYPE_"]}])}}const Hl=new Ak;class Ik extends S.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Hl},{no:2,name:"audio",kind:"message",T:()=>Hl},{no:3,name:"screenshare",kind:"message",T:()=>Hl}])}}const Dk=new Ik;class Ok extends S.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>vk},{no:2,name:"plugins",kind:"message",T:()=>Ek},{no:3,name:"chat",kind:"message",T:()=>bk},{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",du,"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",ou,"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:()=>Mk},{no:23,name:"media",kind:"message",T:()=>Dk}])}}const dh=new Ok;class Nk extends S.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Lk=new Nk;class Vk 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 xk=new Vk;class Uk extends S.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>xk}])}}const $k=new Uk;class Bk extends S.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>dh}])}}const Jm=new Bk;class Hk extends S.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Jm}])}}const Fk=new Hk;class qk extends S.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Jm}])}}const Ip=new qk;class jk 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 Gk=new jk;class Wk extends S.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Gk},{no:2,name:"patch",kind:"message",T:()=>dh}])}}new Wk;class Jk extends S.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>dh}])}}new Jk;class Kk 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 Kk;class zk 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 Yk=new zk;class Qk 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:()=>Yk}])}}const Xk=new Qk;class Zk 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 eM=new Zk;class tM extends S.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Gr}])}}const Km=new tM;class sM 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 rM=new sM;class iM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const Fl=new iM;class nM 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 aM=new nM;class oM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const ql=new oM;class cM 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 cM;class dM extends S.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}new dM;class lM 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 uM=new lM;class hM 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 pM=new hM;class gM 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 Nc=new gM;class mM extends S.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const Lc=new mM;class fM 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 TM=new fM;class SM 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 Vc=new SM;class vM 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 yM=new vM;class EM 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 EM;class PM extends S.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new PM;class _M 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 _M;class CM 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 CM;class wM extends S.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new wM;class RM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new RM;class bM 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 kM=new bM;class MM 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:()=>kM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const AM=new MM;class IM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>AM}])}}new IM;class DM 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 OM=new DM;class NM extends S.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>OM}])}}new NM;class LM 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}])}}new LM;class VM 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}])}}new VM;class xM extends S.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new xM;class UM extends S.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new UM;class $M 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}])}}new $M;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}])}}new BM;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}])}}new HM;class FM 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}])}}new FM;class qM 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 lh=new qM;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:()=>lh}])}}const GM=new jM;class WM 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:()=>lh}])}}const JM=new WM;class KM 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:()=>lh}])}}const zM=new KM;class YM 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}])}}new YM;class QM 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 XM=new QM;class ZM extends S.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>XM}])}}new ZM;class eA 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}])}}new eA;class tA 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 sA=new tA;class rA 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:()=>sA}])}}const Dp=new rA;class iA 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}])}}new iA;class nA 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 Op=new nA;class aA extends S.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Np=new aA;class oA 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 cA=new oA;class dA extends S.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>cA}])}}const jl=new dA;class lA extends S.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const uA=new lA;class hA extends S.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const pA=new hA;class gA extends S.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Lp=new gA;class mA 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:()=>TA},{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 zm=new mA;class fA 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:()=>vA}])}}const TA=new fA;class SA 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 vA=new SA;class yA 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 EA=new yA;class PA 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 _A=new PA;class CA extends S.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>zm}])}}const Gl=new CA;class wA extends S.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>zm}])}}const RA=new wA;class bA 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",qi]}])}}const Vp=new bA;class kA 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 n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"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 n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>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(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new kA;class MA 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 lu=new MA;class AA extends S.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>lu}])}}new AA;class IA extends S.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>lu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>lu}])}}new IA;const DA=0,OA=1,NA=2,LA=3,VA=5,xA={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},UA={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},$A={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},BA={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Ym={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},HA={getUserPresets:0,updateUserPreset:1};function wc(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Qm(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const x=wc(DA,xA),qe=wc(OA,UA),ks=wc(NA,$A),Ms=wc(LA,BA),mr=Qm(Ym,16777216),os=Qm(Ym,50331648),jc=wc(VA,HA);var FA=Object.defineProperty,qA=Object.getOwnPropertyDescriptor,Wr=(s,t,e,r)=>{for(var i=r>1?void 0:r?qA(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FA(t,e,i),i},jt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(jt||{}),yt,yn;class nr{constructor(t,e){g(this,yt,void 0);g(this,yn,void 0);f(this,yt,e),f(this,yn,t)}get telemetry(){return a(this,yn).getValue("telemetry")}get logger(){return a(this,yn).getValue("logger")}getChatMessages(){return a(this,yt).sendMessagePromise(qe.getMessages)}async getChatMessagesPaginated(t,e,r,i){const n={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await a(this,yt).sendMessagePromise(qe.getPaginatedMessages,Xk.toBinary(n));return o.payload?eM.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,yt).sendMessage(qe.sendMessageToRoom,rM.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,yt).sendMessage(qe.sendMessageToPeers,aM.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 n={chatId:t,payloadType:r,payload:e};i!==void 0&&(n.pinned=i);const o=await a(this,yt).sendMessagePromise(qe.editMessage,uM.toBinary(n));return Lc.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,yt).sendMessagePromise(qe.deleteMessage,TM.toBinary(e));return{id:Vc.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await a(this,yt).sendMessagePromise(qe.searchChannelMessages,yM.toBinary(r));return Km.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,yt).sendMessagePromise(qe.pinMessage,pM.toBinary(r));return Nc.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case qe.sendMessageToRoom:{r=Fl.fromBinary.bind(Fl),i=Fl.create();break}case qe.sendMessageToPeers:{r=ql.fromBinary.bind(ql),i=ql.create();break}case qe.editMessage:{r=Lc.fromBinary.bind(Lc),i=Lc.create();break}case qe.pinMessage:{r=Nc.fromBinary.bind(Nc),i=Nc.create();break}case qe.deleteMessage:{r=Vc.fromBinary.bind(Vc),i=Vc.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,yt).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}yt=new WeakMap,yn=new WeakMap;Wr([y.trace("SocketService.getChatMessages")],nr.prototype,"getChatMessages",1);Wr([y.trace("SocketService.getChatMessagesPaginated")],nr.prototype,"getChatMessagesPaginated",1);Wr([y.trace("SocketService.sendMessageToRoom")],nr.prototype,"sendMessageToRoom",1);Wr([y.trace("SocketService.sendMessageToPeers")],nr.prototype,"sendMessageToPeers",1);Wr([y.trace("SocketService.sendMessage")],nr.prototype,"sendMessage",1);Wr([y.trace("SocketService.editMessage")],nr.prototype,"editMessage",1);Wr([y.trace("SocketService.deleteMessage")],nr.prototype,"deleteMessage",1);Wr([y.trace("SocketService.searchMessages")],nr.prototype,"searchMessages",1);function jA(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Es(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Es(e));const t={};return Object.keys(s).forEach(e=>{const r=qr.validate(e)?e:jA(e);t[r]=Es(s[e])}),t}function GA(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Xm(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Xm(e));const t={};return Object.keys(s).forEach(e=>{const r=qr.validate(e)?e:GA(e);t[r]=s[e]}),t}class uu extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);h(this,"status");h(this,"response");h(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(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 xp{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 n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.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 m=new AbortController,T=setTimeout(()=>m.abort(),d);c.signal=m.signal;const E=await fetch(r,c);clearTimeout(T);let P=null;const k=E.headers.get("content-type");k&&k.includes("application/json")?P=await E.json():P=await E.text();const C={};E.headers.forEach((V,L)=>{C[L]=V});const I={data:P,status:E.status,statusText:E.statusText,headers:C,config:t};if(!E.ok)throw I;return I}catch(m){if(m 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 m}}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 WA=3,JA=30,KA=8e3;class zA{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,"userDetails");h(this,"roomDetails");h(this,"context");this.context=t;const{timeout:r=KA,retry:i=WA,retryDelay:n=JA,baseURL:o=ri.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new xp({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new xp({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var m,T,E,P,k;const p=t.getValue("telemetry");try{p.injectContext(this.requests.defaults.headers.common);const C=await l(u);return u.url!==p.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:C.status,statusText:C.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),C}catch(C){if(!C)throw new R("Unknown network error occurred","0011");if(C instanceof R||C instanceof uu)throw C;((m=C.config)==null?void 0:m.url)!==p.logsEndpoint&&this.logger.error("xhr::fetch",{error:C,networkCall:{status:C.status,statusText:C.statusText,baseURL:((T=C.config)==null?void 0:T.baseURL)||this.requests.defaults.baseURL,url:(E=C.config)==null?void 0:E.url,retries:(P=C.config)==null?void 0:P.retry,method:(k=C.config)==null?void 0:k.method,isOnline:navigator.onLine?"online":"offline"}});const I=C instanceof Error&&C.message||"Network request failed";throw new R(I,"0011"),new uu(C)}}}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 YA=Object.defineProperty,QA=Object.getOwnPropertyDescriptor,ar=(s,t,e,r)=>{for(var i=r>1?void 0:r?QA(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&YA(t,e,i),i};class Cs extends zA{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 getPresignedUrls(e){const r=Ta(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:n,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:n,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=Es(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=Es((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 Es(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Xm(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")}}}ar([y.trace("APIClient.getICEServers")],Cs.prototype,"getICEServers",1);ar([y.trace("APIClient.startLivestreaming")],Cs.prototype,"startLivestreaming",1);ar([y.trace("APIClient.stopLivestreaming")],Cs.prototype,"stopLivestreaming",1);ar([y.trace("APIClient.getActiveLivestream")],Cs.prototype,"getActiveLivestream",1);ar([y.trace("APIClient.getUserDetails")],Cs.prototype,"getUserDetails",1);ar([y.trace("APIClient.startRecording")],Cs.prototype,"startRecording",1);ar([y.trace("APIClient.stopRecording")],Cs.prototype,"updateRecording",1);ar([y.trace("APIClient.getActiveRecording")],Cs.prototype,"getActiveRecording",1);ar([y.trace("APIClient.getActiveTranscript")],Cs.prototype,"getActiveTranscript",1);let hu;function XA(s,t){return hu=new Cs(s,t),hu}function gt(){return hu}const va={maxInvocations:5,period:1};function It(s,t){return function(e,r,i){const n=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,n.apply(this,d)},i}}var ZA=Object.defineProperty,eI=Object.getOwnPropertyDescriptor,ws=(s,t,e,r)=>{for(var i=r>1?void 0:r?eI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZA(t,e,i),i};const tI=["text","image","file","custom","poll"],Gc={maxInvocations:180,period:60};var X,ni,We,En,fd,Zm,fo,pu,eg;let Wt=(eg=class extends At{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,fd);g(this,fo);h(this,"messages");g(this,X,void 0);g(this,ni,void 0);g(this,We,void 0);g(this,En,void 0);h(this,"maxTextLimit",2e3);f(this,En,t),f(this,We,e),f(this,X,r),f(this,ni,i),this.messages=[]}get telemetry(){return a(this,En).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,n,o,c,d,l;if(t.length>this.maxTextLimit)throw new R("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,X).permissions)!=null&&n.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=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(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(a(this,X).id),r=a(this,ni).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,X).userId)),a(this,We).sendMessage(t,jt.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,X).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(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=gt(),{getLocation:p,putLocation:m}=await u.getPresignedUrls(t.name);await u.uploadFile(t,m);let T=[];e&&e.length>0&&(e.push(a(this,X).id),T=a(this,ni).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),T.push(a(this,X).userId)),a(this,We).sendMessage(p,jt.IMAGE,e)}catch(u){throw new R("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,n,o,c,d;if(e&&e.length>0){if(!((r=a(this,X).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,X).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,X).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(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=gt(),{getLocation:u,putLocation:p}=await l.getPresignedUrls(t.name);await l.uploadFile(t,p);let m=[];e&&e.length>0&&(e.push(a(this,X).id),m=a(this,ni).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),m.push(a(this,X).userId));const T=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,We).sendMessage(T,jt.FILE,e)}catch(l){throw new R("Error sending file message.","0500",this.logger)}}get rateLimits(){return Gc}updateRateLimits(t,e){Gc.maxInvocations=t,Gc.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,p,m,T,E,P,k,C,I,V;if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,X).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((p=(u=a(this,X).permissions)==null?void 0:u.chatPublic)!=null&&p.files)||!((T=(m=a(this,X).permissions)==null?void 0:m.chatPublic)!=null&&T.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async L=>{try{if(typeof L=="string")return{link:L};const B=gt(),{getLocation:$,putLocation:z}=await B.getPresignedUrls(L.name);return await B.uploadFile(L,z),{link:$,type:L.type,name:L.name,size:L.size}}catch(B){throw new R("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((P=(E=t.files)!=null?E:[])==null?void 0:P.map(async L=>r(L))),images:await Promise.all((C=(k=t.images)!=null?k:[])==null?void 0:C.map(async L=>r(L))),videos:await Promise.all((V=(I=t.videos)!=null?I:[])==null?void 0:V.map(async L=>r(L)))};a(this,We).sendMessage(JSON.stringify(i),jt.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,n,o;if(!((i=(r=a(this,X).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,X).permissions)==null?void 0:n.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,We).editMessage(t,e,jt.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,X).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(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=gt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,We).editMessage(t,l,jt.IMAGE)}catch(d){throw new R("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,X).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,X).permissions)==null?void 0:n.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=gt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,We).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),jt.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){a(this,We).deleteMessage(t)}async pin(t){if(!a(this,fo,pu))throw new R("Can`t pin message without joining room","0505");try{await a(this,We).setPinState(t,!0)}catch(e){throw new R(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,fo,pu))throw new R("Can`t unpin message without joining room","0505");try{await a(this,We).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 a(this,We).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>Za.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,We).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>Za.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,We).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>Za.formatSocketPeerMessage(o))}},X=new WeakMap,ni=new WeakMap,We=new WeakMap,En=new WeakMap,fd=new WeakSet,Zm=function(){return a(this,En).getValue("connectionHandler")},fo=new WeakSet,pu=function(){return a(this,fd,Zm).socketJoined===!0},eg);ws([y.trace("Chat.sendTextMessage"),It(Gc)],Wt.prototype,"sendTextMessage",1);ws([y.trace("Chat.sendImageMessage"),It({maxInvocations:20,period:60})],Wt.prototype,"sendImageMessage",1);ws([y.trace("Chat.sendFileMessage"),It({maxInvocations:20,period:60})],Wt.prototype,"sendFileMessage",1);ws([y.trace("Chat.sendMessage"),It({maxInvocations:180,period:60})],Wt.prototype,"sendMessage",1);ws([y.trace("Chat.editTextMessage")],Wt.prototype,"editTextMessage",1);ws([y.trace("Chat.editImageMessage")],Wt.prototype,"editImageMessage",1);ws([y.trace("Chat.editFileMessage")],Wt.prototype,"editFileMessage",1);ws([y.trace("Chat.editMessage")],Wt.prototype,"editMessage",1);ws([y.trace("Chat.deleteMessage")],Wt.prototype,"deleteMessage",1);Wt=ws([et("0500")],Wt);var sI=Object.defineProperty,rI=Object.getOwnPropertyDescriptor,iI=(s,t,e,r)=>{for(var i=r>1?void 0:r?rI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&sI(t,e,i),i},ai,tg;const ur=(tg=class{constructor(s,t,e,r){h(this,"chat");h(this,"chatSocketHandler");h(this,"self");g(this,ai,void 0);f(this,ai,s),this.chatSocketHandler=t,this.chat=new Wt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,ai).getValue("telemetry")}get logger(){return a(this,ai).getValue("logger")}static async init(s,t,e,r){return new ur(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:tI[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 jt.TEXT:{e.message=s.payload;break}case jt.IMAGE:{e.link=s.payload;break}case jt.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case jt.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return ur.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=Km.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>ur.formatSocketPeerMessage(e))}setupEvents(){a(this,ai).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(qe.sendMessageToRoom,s=>{if(!s.message)return;const t=ur.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(qe.sendMessageToPeers,s=>{const t=ur.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(qe.editMessage,s=>{if(!s.message)return;const t=ur.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(qe.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(qe.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=ur.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,tg);let Za=ur;iI([y.trace("ChatController.setupEvents")],Za.prototype,"setupEvents",1);var nI=Object.defineProperty,aI=Object.getOwnPropertyDescriptor,oI=(s,t,e,r)=>{for(var i=r>1?void 0:r?aI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&nI(t,e,i),i},Td,ef,Sd,tf,Pn,_n,To,sg;let gu=(sg=class extends At{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Td);g(this,Sd);h(this,"items");g(this,Pn,void 0);g(this,_n,void 0);g(this,To,void 0);f(this,To,t),f(this,Pn,e),f(this,_n,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,Sd,tf))throw new R("Can't create polls without joining room","0705");if(!a(this,Pn).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 a(this,_n).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,Pn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,_n).votePoll(t,e)}},Td=new WeakSet,ef=function(){return a(this,To).getValue("connectionHandler")},Sd=new WeakSet,tf=function(){var t;return((t=a(this,Td,ef))==null?void 0:t.socketJoined)===!0},Pn=new WeakMap,_n=new WeakMap,To=new WeakMap,sg);gu=oI([et("0700")],gu);var cI=Object.defineProperty,dI=Object.getOwnPropertyDescriptor,lI=(s,t,e,r)=>{for(var i=r>1?void 0:r?dI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cI(t,e,i),i},Tr,Cn,oi,rg;const tn=(rg=class{constructor(s,t,e){h(this,"polls");g(this,Tr,void 0);g(this,Cn,void 0);g(this,oi,void 0);this.polls=new gu(s,t,e),f(this,Cn,t),f(this,Tr,s),f(this,oi,e),this.setupEvents()}get telemetry(){return a(this,Tr).getValue("telemetry")}get logger(){return a(this,Tr).getValue("logger")}static async init(s,t,e){return new tn(s,t,e)}canViewPolls(){return a(this,Cn).permissions.polls.canView}setupEvents(){const s={[Ms.createPoll]:r=>{r.poll&&this.updatePoll(tn.formatSocketServicePoll(r.poll))},[Ms.updatePoll]:r=>{r.poll&&this.updatePoll(tn.formatSocketServicePoll(r.poll))},[Ms.votePoll]:r=>{r.poll&&this.updatePoll(tn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Tr).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,oi).on(r,s[r])})},e=()=>{a(this,Tr).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,oi).removeListeners(r)})};a(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 a(this,oi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=RA.fromBinary(s.payload);this.polls.items=t.map(e=>tn.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}}},Tr=new WeakMap,Cn=new WeakMap,oi=new WeakMap,rg);let sf=tn;lI([y.trace("PollController.setupEvents")],sf.prototype,"setupEvents",1);var uI=Object.defineProperty,hI=Object.getOwnPropertyDescriptor,pI=(s,t,e,r)=>{for(var i=r>1?void 0:r?hI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uI(t,e,i),i},rf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(rf||{}),wn,So,fu,ci,vo,ig;let mu=(ig=class extends At{constructor(t,e,r,i,n){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");f(this,wn,t),f(this,ci,e),this.viewType=r,f(this,vo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,So,fu).socketState}get mediaState(){return a(this,So,fu).mediaState}get meetingId(){return a(this,wn).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(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=a(this,ci).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,vo).broadcastMessage("spotlight",{userId:a(this,ci).userId,currentTab:this.selfActiveTab})}},wn=new WeakMap,So=new WeakSet,fu=function(){return a(this,wn).getValue("connectionHandler")},ci=new WeakMap,vo=new WeakMap,ig);mu=pI([et("0800")],mu);function gI(s){let t="",e=[""];const r=[e];let i=0,n=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[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var mI=Object.defineProperty,fI=Object.getOwnPropertyDescriptor,nf=(s,t,e,r)=>{for(var i=r>1?void 0:r?fI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mI(t,e,i),i},yo,ng;let Fr=(ng=class extends At{constructor(t){const e=t.getValue("logger");super(e);h(this,"transcripts");g(this,yo,void 0);f(this,yo,t),this.transcripts=[]}get telemetry(){return a(this,yo).getValue("telemetry")}static async init(t,e){const r=new Fr(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(n){i.error("Error fetching active transcriptions ",n)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,n,o,c,d]]=gI(t);return{id:qr.v4(),name:c,peerId:i,userId:n,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
8
- `).map(e=>Fr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=gt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Fr.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,ng);nf([y.trace("Ai.getActiveTranscript")],Fr.prototype,"getActiveTranscript",1);Fr=nf([et("0000")],Fr);var TI=Object.defineProperty,SI=Object.getOwnPropertyDescriptor,vI=(s,t,e,r)=>{for(var i=r>1?void 0:r?SI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&TI(t,e,i),i},Sr,Rn,Et,ag;const af=(ag=class{constructor(s,t,e,r,i,n){h(this,"meta");h(this,"ai");g(this,Sr,void 0);g(this,Rn,void 0);h(this,"aiSocketHandler");g(this,Et,void 0);f(this,Et,s),this.meta=new mu(s,t,t.config.viewType,e,n),this.ai=r,f(this,Sr,t),f(this,Rn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Et).getValue("telemetry")}get logger(){return a(this,Et).getValue("logger")}static async init(s,t,e,r,i){const n=await Fr.init(s,t.permissions.transcriptionEnabled);return new af(s,t,e,n,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,rf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Et).getValue("peerSessionStore").on(w.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Et).getValue("peerSessionStore").on(w.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Et).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})}}),a(this,Et).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Sr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Rn).broadcastMessage("spotlight",{userId:a(this,Sr).userId,currentTab:this.meta.selfActiveTab})),a(this,Et).getValue("peerSessionStore").on(w.PEER_JOINED_INTERNAL,async s=>{a(this,Sr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Rn).broadcastToPeers("spotlight",[s.id],{userId:a(this,Sr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Et).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)}),a(this,Et).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(x.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Fr.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);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Sr=new WeakMap,Rn=new WeakMap,Et=new WeakMap,ag);let of=af;vI([y.trace("MetaController.setupEvents")],of.prototype,"setupEvents",1);const Ba={},or={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var E,P;const l=(P=(this==null?void 0:this.peerId)||((E=d[0])==null?void 0:E.authToken))!=null?P:"",u=`${t}-${l}`,p=this==null?void 0:this.logger;if(Ba[u]){const k=new Error(`Unsupported concurrent calls on method: ${s}.`);throw k.name="UnsupportedConcurrentMethodExecution",p==null||p.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:k.stack},locker:{methodName:s,lockName:u}}),k}Ba[u]=!0;const m=setTimeout(()=>delete Ba[u],e),T=o.apply(this,d);return Promise.resolve(T).then(()=>{delete Ba[u],clearTimeout(m)}).catch(()=>{delete Ba[u],clearTimeout(m)}),T},n}}};var yI=Object.defineProperty,EI=Object.getOwnPropertyDescriptor,Yi=(s,t,e,r)=>{for(var i=r>1?void 0:r?EI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&yI(t,e,i),i},xt,vd,te,Eo,hs,Le,Po,Tu,bn,Wc;class Jr extends At{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);g(this,Po);g(this,bn);g(this,xt,void 0);g(this,vd,void 0);g(this,te,void 0);g(this,Eo,void 0);g(this,hs,void 0);g(this,Le,void 0);f(this,Le,e),f(this,xt,n),f(this,vd,o),f(this,te,r),f(this,Eo,i),f(this,hs,[]),this.setupEvents()}get telemetry(){return a(this,Le).getValue("telemetry")}get status(){return a(this,Le).getValue("stageStatus")}setupEvents(){const e={[w.GET_STAGE_REQUESTS]:async n=>{f(this,hs,n)},[w.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,hs).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Le).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Le).getValue("peerSessionStore").removeListener(n,o)})};a(this,te).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,te).permissions.acceptStageRequests?(r(),a(this,xt).getStageRequests()):(i(),f(this,hs,[]),this.emit("stageAccessRequestUpdate",a(this,hs))))}),a(this,te).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,te).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=a(this,Eo).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,hs,e),{stageRequests:a(this,hs)}}async requestAccess(){if(!a(this,te).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(a(this,te).permissions.stageAccess===q.Allowed){O(this,bn,Wc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,xt).requestAccess(),O(this,bn,Wc).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");a(this,xt).cancelRequestAccess(),O(this,bn,Wc).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,te).roomJoined)throw new R("Can`t grant for participant without joining room");if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new R("You do not have permission to perform this action","2001");return a(this,xt).grantAccess(e)}denyAccess(e){if(!a(this,te).roomJoined)throw new R("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new R("You do not have permission to perform this action","2001");return a(this,xt).denyAccess(e)}get peerId(){return a(this,Le).getValue("peerId")}async join(){const e=a(this,Le).getValue("viewType");if(this.status==="ON_STAGE")throw new R("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,te).permissions.stageAccess===q.NotAllowed)throw new R(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Le).setValue("stageStatus","ON_STAGE",!1),await a(this,xt).joinStage(),e===Xs.Livestream){await a(this,Le).getValue("selfController").joinRoom();return}a(this,Le).notify("stageStatus"),a(this,te).audioEnabled&&a(this,Po,Tu).shareMic(a(this,te).audioTrack),a(this,te).videoEnabled&&a(this,Po,Tu).shareWebcam(a(this,te).videoTrack)}async leave(){if(!a(this,te).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");a(this,te).setIsPinned(!1),a(this,Le).setValue("stageStatus","OFF_STAGE",!1),await a(this,xt).leaveStage(a(this,te).userId);try{await a(this,Le).getValue("peerSessionStore").emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Le).notify("stageStatus")}async kick(e){if(!a(this,te).roomJoined)throw new R("Can`t kick participant without joining room","2005");if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new R("You do not have permissions for kick","2001");return a(this,xt).kick(e)}}xt=new WeakMap,vd=new WeakMap,te=new WeakMap,Eo=new WeakMap,hs=new WeakMap,Le=new WeakMap,Po=new WeakSet,Tu=function(){return a(this,Le).getValue("roomNodeClient")},bn=new WeakSet,Wc=async function(e){this.status!==e&&a(this,Le).setValue("stageStatus",e)};Yi([y.trace("Stage.getStageRequests")],Jr.prototype,"getAccessRequests",1);Yi([y.trace("Stage.requestAccess")],Jr.prototype,"requestAccess",1);Yi([y.trace("Stage.cancelRequestAccess")],Jr.prototype,"cancelRequestAccess",1);Yi([y.trace("Stage.grantAccess")],Jr.prototype,"grantAccess",1);Yi([y.trace("Stage.denyAccess")],Jr.prototype,"denyAccess",1);Yi([or.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),y.trace("Stage.joinStage")],Jr.prototype,"join",1);Yi([y.trace("Stage.leaveStage")],Jr.prototype,"leave",1);function PI(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function uh(s){switch(s){case zs.UNSPECIFIED:return"OFF_STAGE";case zs.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case zs.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case zs.OFF_STAGE:return"OFF_STAGE";case zs.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var _I=Object.defineProperty,CI=Object.getOwnPropertyDescriptor,wI=(s,t,e,r)=>{for(var i=r>1?void 0:r?CI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_I(t,e,i),i},vr,Xt,yr,_o,st;class cf{constructor(t,e,r,i,n){h(this,"stage");g(this,vr,void 0);g(this,Xt,void 0);g(this,yr,void 0);g(this,_o,0);g(this,st,void 0);f(this,st,t),this.stage=new Jr(t,i,n,e,r),f(this,yr,e),f(this,vr,i),f(this,Xt,n),this.setupEvents()}get telemetry(){return a(this,st).getValue("telemetry")}get logger(){return a(this,st).getValue("logger")}setupEvents(){a(this,st).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,yr).on(x.grantStageAccess,()=>{a(this,vr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,yr).on(x.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,vr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,yr).on(x.denyStageAccess,()=>{a(this,vr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,yr).on(x.getStageRequests,async t=>{var r;if(a(this,vr).permissions.stageAccess!==q.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,st).getValue("peerSessionStore").emitAsync(w.GET_STAGE_REQUESTS,e),a(this,_o)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,_o,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Xt).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&&a(this,st).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=uh(t.stageType),r=a(this,st).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,st).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,st).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Xt).joined.get(t.peerId),r=a(this,Xt).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,st).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:a(this,Xt).viewMode,page:a(this,Xt).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&&a(this,st).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:a(this,Xt).viewMode,page:a(this,Xt).currentPage});break}a(this,st).getValue("peerSessionStore").emit(w.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}vr=new WeakMap,Xt=new WeakMap,yr=new WeakMap,_o=new WeakMap,st=new WeakMap;wI([y.trace("Stage.setupEvents")],cf.prototype,"setupEvents",1);var RI=Object.defineProperty,bI=Object.getOwnPropertyDescriptor,hh=(s,t,e,r)=>{for(var i=r>1?void 0:r?bI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&RI(t,e,i),i},di,Ns,Co,wo,li,og;let ho=(og=class extends Sa{constructor(t,e,r,i){const n=t.getValue("logger");super(n);h(this,"name");h(this,"icon");h(this,"id");h(this,"permissions");g(this,di,void 0);g(this,Ns,void 0);g(this,Co,void 0);g(this,wo,void 0);g(this,li,void 0);h(this,"active");h(this,"enabledBy");f(this,Co,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,f(this,wo,e.component),this.permissions=e.permissions,f(this,di,i),f(this,Ns,r),this.active=!1,this.enabledBy=""}get component(){return a(this,wo)}get telemetry(){return a(this,Co).getValue("telemetry")}set activePluginsStore(t){f(this,Ns,t)}activateForSelf(){f(this,li,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){f(this,li,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!a(this,Ns))throw new R("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,Ns).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,di).id}),this.enabledBy=a(this,di).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==a(this,di).id)return;if(!a(this,Ns))throw new R("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,li)?new Date().getTime()-a(this,li).getTime():0;await a(this,Ns).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},di=new WeakMap,Ns=new WeakMap,Co=new WeakMap,wo=new WeakMap,li=new WeakMap,og);hh([y.trace("Plugin.activatePlugin")],ho.prototype,"activate",1);hh([y.trace("Plugin.deactivatePlugin")],ho.prototype,"deactivate",1);ho=hh([et("0600")],ho);var Me,ui;class df extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();g(this,Me,void 0);g(this,ui,void 0);h(this,"onAddEvent");h(this,"onDeleteEvent");h(this,"onClearEvent");f(this,Me,new Sa(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,ui,new Map)}emit(e,...r){return a(this,Me).emit(e,...r)}on(e,r){return a(this,Me).on(e,r)}addListener(e,r){return a(this,Me).addListener(e,r)}off(e,r){return a(this,Me).off(e,r)}once(e,r){return a(this,Me).once(e,r)}prependListener(e,r){return a(this,Me).prependListener(e,r)}prependOnceListener(e,r){return a(this,Me).prependOnceListener(e,r)}removeListener(e,r){return a(this,Me).removeListener(e,r)}removeAllListeners(e){return a(this,Me).removeAllListeners(e)}listeners(e){return a(this,Me).listeners(e)}listenerCount(e){return a(this,Me).listenerCount(e)}getMaxListeners(){return a(this,Me).getMaxListeners()}setMaxListeners(e){return a(this,Me).setMaxListeners(e)}eventNames(){return a(this,Me).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,ui).set(e,o),r.on("*",o),i&&a(this,Me).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,ui).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Me).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,ui).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Me).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Me=new WeakMap,ui=new WeakMap;class Up extends df{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 kI=Object.defineProperty,MI=Object.getOwnPropertyDescriptor,AI=(s,t,e,r)=>{for(var i=r>1?void 0:r?MI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kI(t,e,i),i};let Su=class{constructor(s){h(this,"all");h(this,"active");this.all=new Up(s),this.active=new Up(s)}};Su=AI([et("0600")],Su);var II=Object.defineProperty,DI=Object.getOwnPropertyDescriptor,OI=(s,t,e,r)=>{for(var i=r>1?void 0:r?DI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&II(t,e,i),i},Zt,kn,Er,hi,yd,uf,Ro,vu,bo,yu,ko,Eu,cg;const lf=(cg=class{constructor(s,t,e,r){g(this,yd);g(this,Ro);g(this,bo);g(this,ko);h(this,"plugins");g(this,Zt,void 0);g(this,kn,void 0);g(this,Er,void 0);g(this,hi,null);f(this,Er,s),this.plugins=t,f(this,kn,e),f(this,Zt,r),this.setupEvents()}get telemetry(){return a(this,Er).getValue("telemetry")}get logger(){return a(this,Er).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new Su(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(su,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(p=>{const m=new ho(s,p,c,e);o.all.add(m)});const d=new lf(s,o,r,c);return c?O(l=d,ko,Eu).call(l):O(u=d,yd,uf).call(u),d}cleanup(){O(this,Ro,vu).call(this)}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)}),a(this,Er).getValue("peerSessionStore").onAsync(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!a(this,Zt)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await O(this,bo,yu).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},Zt=new WeakMap,kn=new WeakMap,Er=new WeakMap,hi=new WeakMap,yd=new WeakSet,uf=function(){const s=a(this,Er).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,Zt))try{f(this,Zt,await a(this,kn).create(su,!0)),O(this,Ro,vu).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,Zt)}),O(this,ko,Eu).call(this),this.logger.info("Active plugins store created after socket connected"),await O(this,bo,yu).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(w.SOCKET_STATE_UPDATE,t),f(this,hi,()=>{s.off(w.SOCKET_STATE_UPDATE,t)})},Ro=new WeakSet,vu=function(){a(this,hi)&&(a(this,hi).call(this),f(this,hi,null))},bo=new WeakSet,yu=async function(){try{await a(this,kn).refresh(a(this,Zt).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,Zt).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},ko=new WeakSet,Eu=function(){a(this,Zt).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},cg);let hf=lf;OI([y.trace("PluginController.setupEvents")],hf.prototype,"setupEvents",1);var Mo;class NI{constructor(t){h(this,"mediaJoined");h(this,"socketJoined");h(this,"socketJoinAttempted");h(this,"mediaJoinAttempted");h(this,"socketState");h(this,"mediaState");g(this,Mo,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},f(this,Mo,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&&(a(this,Mo).getValue("peerSessionStore").emit(w.SOCKET_STATE_UPDATE,r),this.socketState=r)}}Mo=new WeakMap;var LI=Object.defineProperty,VI=Object.getOwnPropertyDescriptor,Rc=(s,t,e,r)=>{for(var i=r>1?void 0:r?VI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&LI(t,e,i),i},Mn,An,In,Jc,dg;let Wi=(dg=class extends At{constructor(t,e){const r=t.getValue("logger");super(r);g(this,In);g(this,Mn,void 0);g(this,An,void 0);h(this,"recordingPeerIds",[]);h(this,"recordings",[]);f(this,An,t),f(this,Mn,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 a(this,An).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,Mn).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=gt(),{recording:r={}}=a(this,An).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 O(this,In,Jc).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await O(this,In,Jc).call(this,"pause",["RECORDING"],t)}async resume(t){await O(this,In,Jc).call(this,"resume",["PAUSED"],t)}},Mn=new WeakMap,An=new WeakMap,In=new WeakSet,Jc=async function(t,e,r){if(!a(this,Mn).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 n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new R("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await gt().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new R("Error while stopping recording","1000",this.logger)}})},dg);Rc([y.trace("Recording.start")],Wi.prototype,"start",1);Rc([y.trace("Recording.stop")],Wi.prototype,"stop",1);Rc([y.trace("Recording.stop")],Wi.prototype,"pause",1);Rc([y.trace("Recording.stop")],Wi.prototype,"resume",1);Wi=Rc([et("1000")],Wi);var xI=Object.defineProperty,UI=Object.getOwnPropertyDescriptor,$I=(s,t,e,r)=>{for(var i=r>1?void 0:r?UI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xI(t,e,i),i},pi;class pf{constructor(t,e,r){h(this,"recording");h(this,"room");g(this,pi,void 0);f(this,pi,t),this.recording=new Wi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,pi).getValue("telemetry")}get logger(){return a(this,pi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case qi.BROWSER:e="BROWSER";break;case qi.COMPOSITE:e="COMPOSITE";break;case qi.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,pi).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(x.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(x.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(x.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}pi=new WeakMap;$I([y.trace("RecordingController.setupEvents")],pf.prototype,"setupEvents",1);var gi;class BI{constructor(t){g(this,gi,void 0);f(this,gi,t)}hasFeature(t){return a(this,gi).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,gi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,gi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}gi=new WeakMap;class ph{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 ph(t.getValue("authToken"),t.getValue("logger"),new BI(t),t.getValue("callstats"))}}class gh{constructor(t){h(this,"internals");this.internals=t}static async init(t){const e=ph.init(t);return new gh(e)}}var HI=Object.defineProperty,FI=Object.getOwnPropertyDescriptor,Dt=(s,t,e,r)=>{for(var i=r>1?void 0:r?FI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&HI(t,e,i),i},Ne,he,de,Ls,Ut,Ao,_e;class ft extends Sa{constructor(e,r,i=dd,n=!0){const o=e.getValue("logger");super(o);g(this,Ne,void 0);g(this,he,void 0);g(this,de,void 0);g(this,Ls,void 0);g(this,Ut,void 0);g(this,Ao,void 0);g(this,_e,void 0);h(this,"audioUpdateInProgress");h(this,"videoUpdateInProgress");f(this,_e,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,Ne,new gf(e,r)),f(this,he,new u0(e,a(this,Ne),void 0,i)),f(this,de,new S0(e,a(this,Ne),void 0,i)),f(this,Ut,new m0(a(this,_e),a(this,Ne))),f(this,Ls,new p0(e,a(this,Ne))),f(this,Ao,n),a(this,he).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,he).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,de).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,de).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,Ut).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,_e).getValue("telemetry")}set context(e){f(this,_e,e)}async onVisibilityChange(){a(this,_e).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,_e).getValue("callstats").browserBackgrounded():(a(this,_e).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,_e).getValue("callstats").audioOn():a(this,_e).getValue("callstats").audioOff(),r?a(this,_e).getValue("callstats").videoOn():a(this,_e).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,Ne).getAudioAndVideoTrack(a(this,he).userSelectedDevice,a(this,de).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,Ne).getAudioTrack(!1,a(this,he).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Ne).getVideoTrack(a(this,de).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,_e).getValue("callstats").audioOff(),r&&!n&&a(this,_e).getValue("callstats").videoOff(),await a(this,he).setMediaTrack(i),await a(this,de).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,_e).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,_e).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,Ls).currentDevice)!=null&&o.deviceId&&a(this,_e).getValue("callstats").selectedDevice("SPEAKER",a(this,Ls).currentDevice),a(this,Ne).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,he).currentDevice,video:a(this,de).currentDevice,speaker:a(this,Ls).currentDevice}}get permissions(){return a(this,Ne).permissions}getAllDevices(){return a(this,Ne).getAvailableDevices()}getDeviceById(e,r){return a(this,Ne).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,he).mediaTrack}get audioTrack(){return a(this,he).transformedMediaTrack}get audioEnabled(){return a(this,he).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,he).enableTrack(!1,e):await a(this,he).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,he).mediaTrack&&!a(this,he).isCustomTrack?a(this,he).muteTrack():a(this,he).disableTrack()}getAudioDevices(e){return a(this,Ne).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,he).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,_e).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,Ls).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 a(this,Ls).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,_e).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 a(this,de).mediaTrack}get videoTrack(){return a(this,de).transformedMediaTrack}get videoEnabled(){return a(this,de).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,de).enableTrack(!1,e):await a(this,de).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,de).disableTrack()}getVideoDevices(e){return a(this,Ne).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,de).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,_e).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,de).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,Ut).audioMediaTrack,video:a(this,Ut).videoMediaTrack}}get screenShareEnabled(){return a(this,Ut).trackEnabled}async enableScreenShare(){await a(this,Ut).enableScreenShare()}async disableScreenShare(){a(this,Ut).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,Ut).updateConstraints(e)}getSpeakerDevices(e){return a(this,Ne).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,he).addMiddleware(e)}removeAudioMiddleware(e){return a(this,he).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,he).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,de).addMiddleware(e)}removeVideoMiddleware(e){return a(this,de).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,de).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,de).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,he).disableTrack(),a(this,de).disableTrack(),a(this,de).terminateMiddlewareWebWorker(),a(this,Ut).disableScreenShare(),a(this,Ne).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,Ao))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!dd(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(){a(this,he).disableTrack()}removeVideoTrack(){a(this,de).disableTrack(),a(this,de).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ne=new WeakMap,he=new WeakMap,de=new WeakMap,Ls=new WeakMap,Ut=new WeakMap,Ao=new WeakMap,_e=new WeakMap;Dt([y.trace("MediaHandler.setupStreams")],ft.prototype,"setupStreams",1);Dt([y.trace("MediaHandler.enableAudio")],ft.prototype,"enableAudio",1);Dt([y.trace("MediaHandler.disableAudio")],ft.prototype,"disableAudio",1);Dt([y.trace("MediaHandler.setAudioDevice")],ft.prototype,"setAudioDevice",1);Dt([y.trace("MediaHandler.enableVideo")],ft.prototype,"enableVideo",1);Dt([y.trace("MediaHandler.disableVideo")],ft.prototype,"disableVideo",1);Dt([y.trace("MediaHandler.setVideoDevice")],ft.prototype,"setVideoDevice",1);Dt([y.trace("MediaHandler.updateVideoConstraints")],ft.prototype,"updateVideoConstraints",1);Dt([y.trace("MediaHandler.enableScreenShare")],ft.prototype,"enableScreenShare",1);Dt([y.trace("MediaHandler.disableScreenShare")],ft.prototype,"disableScreenShare",1);Dt([y.trace("MediaHandler.updateScreenshareConstraints")],ft.prototype,"updateScreenshareConstraints",1);Dt([y.trace("MediaHandler.destruct")],ft.prototype,"destruct",1);Dt([y.trace("MediaHandler.onDeviceChange")],ft.prototype,"onDeviceChange",1);function xc(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 qI=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function dd(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:qI.some(i=>t==null?void 0:t.includes(i))}async function jI(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=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<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}var mi,Io;class GI{constructor(t){g(this,mi,void 0);g(this,Io,void 0);f(this,Io,t)}get logger(){return a(this,Io).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,mi))try{Bc.clearInterval(a(this,mi)),f(this,mi,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"),n=await Promise.all(t==null?void 0:t.map(m=>m({canvas:i,WorkerTimers:Bc})));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 m=0;m<n.length;m+=1)typeof n[m]=="function"&&await n[m](i,d)}catch(m){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:m})}};try{o.play()}catch(m){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,mi,Bc.setInterval(l,50))},!1);const p=i.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:e.getSettings()}),p}}mi=new WeakMap,Io=new WeakMap;const WI={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}}},JI=[[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}]]],KI=(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=JI,n=i.map(([p])=>p).sort((p,m)=>p-m);let o=Number.MAX_VALUE,c=0;return n.forEach((p,m)=>{Math.abs(p-r)<o&&(o=Math.abs(p-r),c=m)}),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 zI=VC(),Zi=Es(zI.config.media);function YI(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 fi,Ed;class QI{constructor(t,e){g(this,fi,void 0);g(this,Ed,void 0);h(this,"getScreenShareConstraints",()=>{var l,u,p,m,T,E,P,k,C;const t=(l=a(this,fi))==null?void 0:l.screenshare,e=(p=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?p:1920,r=(T=(m=t==null?void 0:t.height)==null?void 0:m.max)!=null?T:1080,i=(P=(E=t==null?void 0:t.frameRate)==null?void 0:E.max)!=null?P:5,n=(C=(k=t==null?void 0:t.frameRate)==null?void 0:k.ideal)!=null?C: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:n,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 n,o,c,d,l,u,p;const e={},r=(n=a(this,fi))==null?void 0:n.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=a(this,fi))==null?void 0:o.video,i=XP(WI);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,Ed,t),f(this,fi,e)}getUpdatedVideoConstraints(t){return t}}fi=new WeakMap,Ed=new WeakMap;class Wl extends Error{constructor(e,r,i){super(r);h(this,"constraints");h(this,"name");this.name=e,this.constraints=i}}class XI{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 ZI=Object.defineProperty,e0=Object.getOwnPropertyDescriptor,us=(s,t,e,r)=>{for(var i=r>1?void 0:r?e0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZI(t,e,i),i},Dn,$t,Ve,lg;let Mt=(lg=class extends XI{constructor(t,e){super();g(this,Dn,void 0);g(this,$t,void 0);g(this,Ve,void 0);f(this,Ve,t),f(this,$t,new QI(t,e)),f(this,Dn,new AbortController)}get telemetry(){return a(this,Ve).getValue("telemetry")}get logger(){return a(this,Ve).getValue("logger")}get constraintsBuilder(){return a(this,$t)}async destruct(){var t;(t=a(this,Dn))==null||t.abort()}handlePermissionErrors(t,e){const r=xc(t,e.name,e.message);return this.permissions[t]=r,a(this,Ve).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(C=>C.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(C=>C.deviceId===e));let m;e&&p?m=e:d&&((n=d[0])!=null&&n.deviceId)&&(m=(o=d[0])==null?void 0:o.deviceId);const T={audio:a(this,$t).getAudioConstraints(u).audio,video:a(this,$t).getVideoConstraints(m).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 P=E.getAudioTracks()[0];let k=E.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",k.label.includes("OBS Virtual")){const I=(await this.getVideoInputDevices()).find(V=>V.label.includes("OBS Virtual"));k=await this.getVideoTrack(I.deviceId)}return a(this,Ve).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Ve).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:P,videoTrack:k}}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",a(this,Ve).getValue("peerSessionStore").emit(w.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 n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(m=>m.deviceId!==l),u=a(this,$t).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 m=xc("audio",p.name,p.message),T=new Wl(p.name,p.message,u);if(m==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const P=a(this,$t).getAudioConstraints(E.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(P)}),o(E.deviceId)}throw T}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Ve).getValue("peerSessionStore").emit(w.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",a(this,Ve).getValue("peerSessionStore").emit(w.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 n;t&&i?n=t:(d=r[0])!=null&&d.deviceId&&(n=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let p=u;const{video:m}=p;e&&typeof m!="boolean"&&(p={video:{deviceId:m.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(p)});const[T]=(await navigator.mediaDevices.getUserMedia(p)).getVideoTracks();if(e&&typeof m!="boolean"&&typeof m.width=="object"){const{width:E,height:P}=T.getSettings(),{ideal:k}=m.width;T.applyConstraints({width:{ideal:k},height:{ideal:Math.floor(P*k/E)},frameRate:m.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(p)}),T}catch(p){const m=xc("video",p.name,p.message),T=new Wl(p.name,p.message,u);if(m==="COULD_NOT_START"){const E=r.shift();if(!E)throw T;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const P=a(this,$t).getVideoConstraints(E.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(P)}),o({video:P.video})}throw T}};try{const u=a(this,$t).getVideoConstraints(n),p=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Ve).getValue("peerSessionStore").emit(w.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)}),a(this,Ve).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=xc("video",r.name,r.message),n=new Wl(r.name,r.message,e),o={video:!0};if(aC(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,$t).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Ve).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 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 n=((o=i.label)==null?void 0:o.toLowerCase())||"";return dd(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,p;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((p=n.label)==null?void 0:p.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const m=r(i),T=r(n);if(m&&!T)return-1;if(!m&&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}`,n=new Set(e.map(p=>i(p))),o=await this.getAvailableDevices(),c=new Set(o.map(p=>i(p))),d={added:o.filter(p=>!n.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(m=>m.kind==="audioinput")&&a(this,Ve).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(m=>m.kind==="audioinput")),p.some(m=>m.kind==="videoinput")&&a(this,Ve).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(m=>m.kind==="videoinput")),p.some(m=>m.kind==="audiooutput")&&a(this,Ve).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(m=>m.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,Dn).signal})}}},Dn=new WeakMap,$t=new WeakMap,Ve=new WeakMap,lg);us([y.trace("WebMediaInterface.destruct")],Mt.prototype,"destruct",1);us([y.trace("WebMediaInterface.handlePermissionErrors")],Mt.prototype,"handlePermissionErrors",1);us([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Mt.prototype,"getAudioAndVideoTrack",1);us([y.trace("WebMediaInterface.getAudioTrack")],Mt.prototype,"getAudioTrack",1);us([y.trace("WebMediaInterface.getVideoTrack")],Mt.prototype,"getVideoTrack",1);us([y.trace("WebMediaInterface.getScreenShareTracks")],Mt.prototype,"getScreenShareTracks",1);us([y.trace("WebMediaInterface.getAvailableDevices")],Mt.prototype,"getAvailableDevices",1);us([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Mt.prototype,"getAvailableDevicesByKind",1);us([y.trace("WebMediaInterface.getDevice")],Mt.prototype,"getDevice",1);us([y.trace("WebMediaInterface.onDeviceChange")],Mt.prototype,"onDeviceChange",1);Mt=us([et("1600")],Mt);const gf=Mt,ji={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}},t0=(s=0)=>new Promise(t=>setTimeout(t,s)),s0=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):t0().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},r0=typeof AudioContext!="undefined"?AudioContext:null;class mh{constructor(t){h(this,"_AudioContext");h(this,"audioContext");h(this,"_audioContextRefContainers");const e={AudioContext:r0,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:mh}})}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 $p=new mh,i0=3,n0=250;function a0(s){const t={},e=$p.getOrCreate(t);let r=i0;function i(){return r-=1,s0(e,s.srcObject,n0).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{$p.release(t)})}async function Bp(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await a0(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var o0=Object.defineProperty,c0=Object.getOwnPropertyDescriptor,mf=(s,t,e,r)=>{for(var i=r>1?void 0:r?c0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&o0(t,e,i),i};let ld=class extends Sa{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);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=>ji.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>ji.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()&&yC.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))}};mf([y.trace("BaseMediaHandler.unmuteTrack")],ld.prototype,"unmuteTrack",1);ld=mf([et("1600")],ld);const ff=ld;var d0=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?l0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&d0(t,e,i),i};const Jl="[Realtimekit]nonSilentDeviceLabels";class Cl extends ff{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 jI(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(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse(ji.getItem(Jl,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Bp(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return ji.setItem(Jl,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await Bp(this.logger,r)){const p=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return ji.setItem(Jl,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}fh([y.trace("AudioMediaHandler.setTransformedTrack")],Cl.prototype,"setTransformedTrack",1);fh([y.trace("AudioMediaHandler.onTrackEnded")],Cl.prototype,"onTrackEnded",1);fh([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Cl.prototype,"conditionallyChangeTrack",1);const u0=Cl;var Ti;class h0{constructor(t,e){g(this,Ti,void 0);h(this,"currentDevice");h(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");h(this,"logger");h(this,"setUserPreferredDevice",t=>ji.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>ji.getItem(this.userPreferredDeviceKey,this.logger));f(this,Ti,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Ti).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,Ti)instanceof gf))return;let r=t;if(t||([r]=(await a(this,Ti).getAvailableDevicesByKind("audiooutput")).filter(d=>!dd(d))),!r)throw new R("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.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){}})}}Ti=new WeakMap;const p0=h0;var Do;class g0 extends Sa{constructor(e,r){const i=e.getValue("logger");super(i);h(this,"mediaInterface");h(this,"audioMediaTrack");h(this,"videoMediaTrack");g(this,Do,void 0);f(this,Do,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,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",a(this,Do).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 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")}}Do=new WeakMap;const m0=g0;var f0=Object.defineProperty,T0=Object.getOwnPropertyDescriptor,wl=(s,t,e,r)=>{for(var i=r>1?void 0:r?T0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&f0(t,e,i),i},On,Oo;class bc extends ff{constructor(e,r,i,n){super(e,r,i,n);g(this,On,void 0);g(this,Oo,{disablePerFrameCanvasRendering:!1});f(this,On,new GI(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 a(this,On).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Oo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,Oo,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(){a(this,On).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 n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;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}}On=new WeakMap,Oo=new WeakMap;wl([y.trace("VideoMediaHandler.setTransformedTrack")],bc.prototype,"setTransformedTrack",1);wl([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],bc.prototype,"setVideoMiddlewareGlobalConfig",1);wl([y.trace("VideoMediaHandler.onTrackEnded")],bc.prototype,"onTrackEnded",1);wl([y.trace("VideoMediaHandler.conditionallyChangeTrack")],bc.prototype,"conditionallyChangeTrack",1);const S0=bc,Hp=Es(oh());var rt,Si,No,Nn;const cn=class{constructor(t){g(this,rt,void 0);g(this,Si,void 0);g(this,No,void 0);g(this,Nn,void 0);if(!t)throw new R("Could not load preset.","0904");f(this,rt,t.config),f(this,No,t.name),f(this,Si,t.ui||Es(oh().ui)),f(this,Nn,t.permissions.plugins.config)}static fromResponse(t){return new cn(t)}static default(){return new cn(Hp)}static init(t,e=!0){return!t||e?new cn(Hp):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:a(this,Si).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,rt).viewType}get livestreamViewerQualities(){return a(this,rt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,rt).maxVideoStreams}get maxScreenShareCount(){return a(this,rt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,Nn)).filter(t=>a(this,Nn)[t].disabled)}get designTokens(){return a(this,Si).designTokens}get configDiff(){return a(this,Si).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,rt))==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,n,o,c,d,l,u,p,m,T,E,P,k,C,I,V,L,B,$,z,De;return{audio:{enableStereo:(i=(r=(e=(t=a(this,rt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Zi.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,rt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Zi.audio.enableHighBitrate},video:{quality:(m=(p=(u=(l=a(this,rt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:p.quality)!=null?m:Zi.video.quality,frameRate:(k=(P=(E=(T=a(this,rt))==null?void 0:T.media)==null?void 0:E.video)==null?void 0:P.frameRate)!=null?k:Zi.video.frameRate},screenshare:{quality:(L=(V=(I=(C=a(this,rt))==null?void 0:C.media)==null?void 0:I.screenshare)==null?void 0:V.quality)!=null?L:Zi.screenshare.quality,frameRate:(De=(z=($=(B=a(this,rt))==null?void 0:B.media)==null?void 0:$.screenshare)==null?void 0:z.frameRate)!=null?De:Zi.screenshare.frameRate}}}get name(){return a(this,No)}};let Pu=cn;rt=new WeakMap,Si=new WeakMap,No=new WeakMap,Nn=new WeakMap;var v0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,Tf=(s,t,e,r)=>{for(var i=r>1?void 0:r?y0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&v0(t,e,i),i},Ln,Lo;class Th extends At{constructor(e,r){const i=e.getValue("logger");super(i);g(this,Ln,void 0);h(this,"state","IDLE");h(this,"playbackUrl");h(this,"ingestionCredentials");h(this,"viewerCount");g(this,Lo,void 0);f(this,Ln,r),f(this,Lo,e),this.viewerCount=0}get telemetry(){return a(this,Lo).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(!a(this,Ln).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=gt(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,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(!a(this,Ln).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 gt().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)}}}Ln=new WeakMap,Lo=new WeakMap;Tf([y.trace("livestream.start")],Th.prototype,"start",1);Tf([y.trace("livestream.stop")],Th.prototype,"stop",1);var E0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,_0=(s,t,e,r)=>{for(var i=r>1?void 0:r?P0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&E0(t,e,i),i},Vn,xn,Vs,ps;class Sf{constructor(t,e,r){h(this,"livestream");g(this,Vn,void 0);g(this,xn,void 0);g(this,Vs,void 0);g(this,ps,void 0);f(this,ps,t),f(this,xn,e),this.livestream=new Th(t,e),f(this,Vs,r),this.setupEvents()}get logger(){return a(this,ps).getValue("logger")}get telemetry(){return a(this,ps).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=gt(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,Vs).on(x.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,xn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,Vs).on(x.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,xn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,Vs).on(x.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Vs).on(x.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Vs).on(x.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(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"&&(f(this,Vn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,ps).getValue("peerSessionStore").on(w.PEER_CLOSED,t=>{t.id===a(this,Vn)&&(f(this,Vn,void 0),this.livestream.setLivestreamState("IDLE"))}),a(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})}}}),a(this,ps).getValue("peerSessionStore").on(w.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Vn=new WeakMap,xn=new WeakMap,Vs=new WeakMap,ps=new WeakMap;_0([y.trace("LivestreamController.setupEvents")],Sf.prototype,"setupEvents",1);var C0=Object.defineProperty,w0=Object.getOwnPropertyDescriptor,kc=(s,t,e,r)=>{for(var i=r>1?void 0:r?w0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&C0(t,e,i),i},Je,Pr,_r,Pd,vf;class ya{constructor({name:t,socketHandler:e,meetingId:r}){g(this,Pd);h(this,"name","");g(this,Je,{});g(this,Pr,"");g(this,_r,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});h(this,"listeners",{});this.name=t,f(this,_r,e),f(this,Pr,r)}async set(t,e,r=!0,i=!1){a(this,Je)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,Je)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,Je)[t]})))}remoteSet(t,e){a(this,_r).storeInsertKeys(a(this,Pr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,Je)[e]=r}),a(this,_r).storeInsertKeys(a(this,Pr),this.name,t)}async update(t,e,r=!0){O(this,Pd,vf).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,Je)[t]&&delete a(this,Je)[t],e)return a(this,_r).storeDeleteKeys(a(this,Pr),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})=>{a(this,Je)[e]&&delete a(this,Je)[e]}),a(this,_r).storeDeleteKeys(a(this,Pr),this.name,t)}get(t){if(a(this,Je)[t])return a(this,Je)[t]}getAll(){return a(this,Je)}clear(){f(this,Je,{})}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){f(this,Je,t)}}Je=new WeakMap,Pr=new WeakMap,_r=new WeakMap,Pd=new WeakSet,vf=function(t,e,r=!0){let i;const n=a(this,Je)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)};kc([It(va,"rateLimitConfig")],ya.prototype,"remoteSet",1);kc([It(va,"bulkRateLimitConfig")],ya.prototype,"bulkSet",1);kc([It(va,"rateLimitConfig")],ya.prototype,"update",1);kc([It(va,"rateLimitConfig")],ya.prototype,"delete",1);kc([It(va,"bulkRateLimitConfig")],ya.prototype,"bulkDelete",1);var Cr,wr,Vo,_u,xo,es,_d,yf;class R0{constructor(t,e){g(this,Vo);g(this,_d);h(this,"stores",new Map);g(this,Cr,void 0);g(this,wr,"");g(this,xo,void 0);g(this,es,new Map);f(this,Cr,e),f(this,wr,t.getValue("meetingId")),f(this,xo,t),O(this,_d,yf).call(this)}create(t,e=!1){if(EC.includes(t)&&!e)throw new R(`'${t}' is a reserved store name.`,"0601");const r=new ya({name:t,socketHandler:a(this,Cr),meetingId:a(this,wr)});return a(this,Cr).storeGetKeys(a(this,wr),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,es).delete(t),o(Error("Failed"))},3e3);a(this,es).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,Cr).storeGetKeys(a(this,wr),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,es).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,es).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}Cr=new WeakMap,wr=new WeakMap,Vo=new WeakSet,_u=function(){return a(this,xo).getValue("peerId")},xo=new WeakMap,es=new WeakMap,_d=new WeakSet,yf=function(){[ks.storeInsertKeys,ks.storeGetKeys,ks.storeDeleteKeys].forEach(t=>{a(this,Cr).on(t,async e=>{var n,o;if(e.pluginId!==a(this,wr))return;const r=(n=e.storeItems)==null?void 0:n.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===ks.storeGetKeys){const c=a(this,es).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,es).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,es).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,es).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===ks.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Vo,_u)&&i.set(c,l,!1,!0)}),t===ks.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Vo,_u)&&i.delete(c,!1,!0)}))})})};function si(s){var t,e,r,i,n,o,c,d,l,u,p,m,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?(n=s.mediaPermissions)==null?void 0:n.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=(m=s.screenShareTracks)==null?void 0:m.video)==null?void 0:T.id}}}}:{}}var b0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,Ea=(s,t,e,r)=>{for(var i=r>1?void 0:r?k0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&b0(t,e,i),i};const M0=.8,A0=1.2;var Un,$n,Pt,vi,Fa,Rr,sn,yi,qa,Cd,Ef,xs,Uo,br,Ei,ja,Us,wd,$o,Cu,Rd,Pf,bd,_f,ug;let sr=(ug=class extends At{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,vi);g(this,Rr);g(this,yi);g(this,Cd);g(this,Ei);g(this,$o);g(this,Rd);g(this,bd);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,Un,void 0);h(this,"supportsRemoteControl",!1);g(this,$n,void 0);h(this,"presetName");g(this,Pt,void 0);g(this,xs,void 0);g(this,Uo,void 0);g(this,br,new Map);g(this,Us,1);g(this,wd,ah(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>A0&&a(this,Us)===1?(f(this,Us,0),a(this,Pt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Us)})):d<M0&&a(this,Us)===0&&(f(this,Us,1),a(this,Pt).getValue("peerSessionStore").emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Us)}))},2e3));f(this,Pt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:p,flags:m,stageStatus:T,customParticipantId:E,audioMuted:P,audioTrack:k,videoEnabled:C=!1,videoTrack:I,producers:V,metadata:L}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=p,this.flags=m,this.manualProducerConfig=gC,f(this,$n,T!=null?T:"ON_STAGE"),this.customParticipantId=E,this.audioEnabled=!P,this.audioTrack=k,this.videoEnabled=C,this.videoTrack=I,this.screenShareTracks={audio:void 0,video:void 0},this.producers=V!=null?V:[],this.presetName=L==null?void 0:L.preset_name,f(this,Un,!1),f(this,xs,r),f(this,Uo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),O(this,$o,Cu).call(this)}get stageStatus(){return a(this,$n)}get telemetry(){return a(this,Pt).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",O(this,$o,Cu)),a(this,Rr,sn)&&(this.on("audioUpdate",O(this,Rd,Pf)),this.on("screenShareUpdate",O(this,bd,_f)))}async pin(){if(!a(this,yi,qa))throw new R("Can`t pin participant without joining room","1205");if(!a(this,xs).permissions.pinParticipant)throw new R("You do not have permission to pin participants.","1201");return a(this,vi,Fa).pinPeer(this.id)}async unpin(){if(!a(this,yi,qa))throw new R("Can`t unpin participant without joining room","1205");if(!a(this,xs).permissions.pinParticipant)throw new R("You do not have permission to unpin participants.","1201");return a(this,vi,Fa).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,Un,t);const r=t?"pinned":"unpinned";(i=a(this,Ei,ja))==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}}),!a(this,yi,qa))throw new R("Can`t disable participant audio without joining room","1205");if(a(this,xs).permissions.canDisableParticipantAudio)return a(this,vi,Fa).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}}),!a(this,Cd,Ef))throw new R("Can`t kick participant without joining room","1205");if(a(this,xs).permissions.kickParticipant){await a(this,Pt).getValue("peerSessionStore").emitAsync(w.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}}),!a(this,yi,qa))throw new R("Can`t disable participant video without joining room","1205");if(a(this,xs).permissions.canDisableParticipantVideo)return a(this,vi,Fa).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 a(this,Uo).getUserPermissions(this.userId)}setStageStatus(t){f(this,$n,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Un)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,br).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,wd).call(this,t)),e.observe(t)),a(this,br).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Ei,ja))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,Ei,ja))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,br).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,br).delete(t),(n=a(this,Ei,ja))==null||n.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"}},Un=new WeakMap,$n=new WeakMap,Pt=new WeakMap,vi=new WeakSet,Fa=function(){return a(this,Pt).getValue("roomNodeClient")},Rr=new WeakSet,sn=function(){return a(this,Pt).getValue("audioPlayback")},yi=new WeakSet,qa=function(){return a(this,Pt).getValue("connectionHandler").mediaJoined},Cd=new WeakSet,Ef=function(){return a(this,Pt).getValue("connectionHandler").socketJoined},xs=new WeakMap,Uo=new WeakMap,br=new WeakMap,Ei=new WeakSet,ja=function(){return a(this,Pt).getValue("pip")},Us=new WeakMap,wd=new WeakMap,$o=new WeakSet,Cu=function(){Array.from(a(this,br).keys()).forEach(this.updateVideo)},Rd=new WeakSet,Pf=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,Rr,sn))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,Rr,sn))==null||e.removeParticipantTrack(this.id)},bd=new WeakSet,_f=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,Rr,sn))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,Rr,sn))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},ug);Ea([y.trace("Participant.disableAudio")],sr.prototype,"disableAudio",1);Ea([y.trace("Participant.kick")],sr.prototype,"kick",1);Ea([y.trace("Participant.disableVideo")],sr.prototype,"disableVideo",1);Ea([y.trace("Participant.getPermissions")],sr.prototype,"getPermissions",1);Ea([y.trace("Participant.setStageStatus")],sr.prototype,"setStageStatus",1);sr=Ea([et("1200")],sr);class Ha extends df{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},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 kr;class I0 extends Sa{constructor(e){super(e);g(this,kr,void 0);f(this,kr,new Map)}__set(e,r){return a(this,kr).set(e,r)}__clear(){return a(this,kr).clear()}get(e){return a(this,kr).get(e)}toArray(){return Array.from(a(this,kr).values())}}kr=new WeakMap;class D0{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 O0{constructor(){h(this,"_activeSpeakerPeers");h(this,"_compulsoryPeers");this._activeSpeakerPeers=new D0,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 Cf=new O0;var N0=Object.defineProperty,L0=Object.getOwnPropertyDescriptor,Rs=(s,t,e,r)=>{for(var i=r>1?void 0:r?L0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&N0(t,e,i),i};const V0=["ACTIVE_GRID","PAGINATED","MANUAL"];var Ce,Bo,wu,Pi,Ga,Bn,Kc,_i,dt,hg;let Jt=(hg=class extends At{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Bo);g(this,Pi);g(this,Bn);h(this,"waitlisted");h(this,"joined");h(this,"active");h(this,"videoSubscribed");h(this,"audioSubscribed");h(this,"pinned");h(this,"all");g(this,Ce,void 0);g(this,_i,void 0);g(this,dt,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"viewMode");h(this,"currentPage");h(this,"lastActiveSpeaker");h(this,"selectedPeers",Cf);f(this,Ce,t),f(this,_i,e),f(this,dt,r),this.waitlisted=new Ha(i),this.joined=new Ha(i),this.videoSubscribed=new Ha(i),this.audioSubscribed=new Ha(i),this.active=this.videoSubscribed,this.pinned=new Ha(i),this.all=new I0(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ce).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ce).getValue("telemetry")}setupEvents(){a(this,Ce).getValue("peerSessionStore").on(w.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ce).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=a(this,Ce).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,Ce))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new R("0 <= Max active participants count limit <= 24","1203");a(this,Ce).setValue("maxPreferredStreams",t),a(this,Bn,Kc)&&a(this,Ce).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(!a(this,Pi,Ga))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 a(this,dt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,dt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,Pi,Ga))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;a(this,dt).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=>V0.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,a(this,Ce).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ce).getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ce).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 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)))}),a(this,Ce).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 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)))}),a(this,Ce).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)),n=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(n,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,a(this,Ce).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}}}),!a(this,Bn,Kc))throw new R("Can`t disable all audio without joining room","1205");if(a(this,_i).permissions.canAllowParticipantAudio)return a(this,Bo,wu).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"),!a(this,Bn,Kc))throw new R("Can`t disable all video without joining room","1205");if(a(this,_i).permissions.canAllowParticipantVideo)return a(this,Bo,wu).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new R("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Ce).getValue("viewType")!=="LIVESTREAM"&&!a(this,Pi,Ga))throw new R("Can`t kick all without joining room","1205");if(!a(this,_i).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;a(this,dt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,Pi,Ga))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 a(this,dt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,dt).broadcastToPeers(t,i,e)}else await a(this,dt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,dt).getRoomPeers(t,e,r)).peers.map(cr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new R("Cannot update permissions, no valid userIDs found","1204");a(this,dt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,dt).getRoomPeersNonPaginated()}},Ce=new WeakMap,Bo=new WeakSet,wu=function(){return a(this,Ce).getValue("roomNodeClient")},Pi=new WeakSet,Ga=function(){var t;return((t=a(this,Ce).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Bn=new WeakSet,Kc=function(){var t;return((t=a(this,Ce).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},_i=new WeakMap,dt=new WeakMap,hg);Rs([y.trace("Participants.setViewMode")],Jt.prototype,"setViewMode",1);Rs([y.trace("Participants.setPage")],Jt.prototype,"setPage",1);Rs([y.trace("Participants.disableAllAudio")],Jt.prototype,"disableAllAudio",1);Rs([y.trace("Participants.disableAllVideo")],Jt.prototype,"disableAllVideo",1);Rs([y.trace("Participants.kickAll")],Jt.prototype,"kickAll",1);Rs([y.trace("Participants.broadcastMessage"),It(va,"rateLimitConfig")],Jt.prototype,"broadcastMessage",1);Rs([y.trace("Participants.getAllJoinedPeers"),It({maxInvocations:10,period:60})],Jt.prototype,"getAllJoinedPeers",1);Rs([y.trace("Participant.updatePermissions"),It({maxInvocations:1e3,period:60})],Jt.prototype,"updatePermissions",1);Rs([y.trace("Participants.getParticipantsInMeetingPreJoin")],Jt.prototype,"getParticipantsInMeetingPreJoin",1);Jt=Rs([et("1200")],Jt);var x0=Object.defineProperty,U0=Object.getOwnPropertyDescriptor,Qi=(s,t,e,r)=>{for(var i=r>1?void 0:r?U0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&x0(t,e,i),i},Bt,ts,Hn,pg;const wf=(pg=class{constructor(s,t,e){h(this,"participants");h(this,"self");h(this,"selectedPeers",Cf);h(this,"maxSpatialLayerUpdates",new Map);h(this,"consumerPeerMap");h(this,"events");h(this,"roomSocketHandler");h(this,"context");h(this,"videoPeerConsumerMap",new Map);g(this,Bt,{mode:"ACTIVE_GRID",page:0});g(this,ts,!1);g(this,Hn,!1);h(this,"updateConsumerSpatialLayers",ah(()=>{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: ${a(this,ts)}`);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 Jt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=os,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(x.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(w.SOCKET_PEERS,s=>{const t=this.participants.joined.size>0;this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.joined.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",t&&this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))})}),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:n,producerStates:o})=>this.onParticipantMediaJoined(n,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: ${a(this,ts)}, 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 n=i.producers.find(o=>o.producerId===t);n&&(n.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: ${a(this,ts)}, 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 sr(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)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,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),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,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&&a(this,Bt).mode!==s&&(a(this,Bt).mode=s),e&&a(this,Bt).page!==e&&(a(this,Bt).page=e);const{mode:r,page:i}=a(this,Bt);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),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=a(this,Bt))==null?void 0:e.mode)==="PAGINATED"&&!a(this,ts)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,Bt))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,ts)}, Delay: ${t}, Page: ${(i=a(this,Bt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var c,d,l,u,p;if(((l=(d=(c=this.context.getValue("connectionHandler"))==null?void 0:c.mediaState)==null?void 0:d.recv)==null?void 0:l.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,ts)){f(this,Hn,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,ts,!0),f(this,Hn,!1);let s=[];this.participants.videoSubscribed.forEach(m=>{var P,k;const T=this.participants.joined.get(m.id),E=(k=(P=m.producers)==null?void 0:P.filter(C=>C.kind==="video"))!=null?k:[];T&&(E!=null&&E.length)&&E.forEach(C=>{var L,B,$,z;const I=((B=(L=T.manualProducerConfig)==null?void 0:L.video)!=null?B:!0)&&C.kind==="video"&&!C.screenShare,V=((z=($=T.manualProducerConfig)==null?void 0:$.screenshareVideo)!=null?z:!0)&&C.kind==="video"&&C.screenShare;(I||V)&&(C.pause||s.push(C))})}),this.participants.audioSubscribed.forEach(m=>{var P,k;const T=this.participants.joined.get(m.id),E=(k=(P=m.producers)==null?void 0:P.filter(C=>C.kind==="audio"))!=null?k:[];T&&(E!=null&&E.length)&&E.forEach(C=>{var L,B,$,z;const I=((B=(L=T.manualProducerConfig)==null?void 0:L.audio)!=null?B:!0)&&C.kind==="audio"&&!C.screenShare,V=((z=($=T.manualProducerConfig)==null?void 0:$.screenshareAudio)!=null?z:!0)&&C.kind==="audio"&&C.screenShare;(I||V)&&s.push(C)})}),s=pC(s,m=>m.producerId);const t=new Map;s.forEach(m=>{t.set(m.producerId,m)});const e=(u=this.roomNodeClient)==null?void 0:u.getConsumers(),r=s.filter(m=>!(e!=null&&e.has(m.producerId)));s.filter(m=>!m.consumer&&(e==null?void 0:e.has(m.producerId))).forEach(m=>{const T=e.get(m.producerId);T&&(this.logger.info(`syncConsumers: remapping existing consumer ${T.id} to producer ${m.producerId}`),this.context.getValue("peerSessionStore").emit(w.NEW_CONSUMER,{id:T.id,appData:T.appData,peerId:T.peerId}))});const n=[];let o=Array.from((p=e==null?void 0:e.values())!=null?p:[]).map(m=>m.peerId);o=hC(o),o==null||o.forEach(m=>{var E;const T=this.participants.joined.get(m);if(!T){this.logger.warn(`Peer with ${m} doesn't exist in joined list but producers of it are being consumed.`);return}(E=T.producers)!=null&&E.length&&T.producers.forEach(P=>{const k=P.consumer&&e.has(P.consumer.id);!t.has(P.producerId)&&(e.has(P.producerId)||k)&&n.push(P)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(m=>m.producerId).join(", ")}], RemoveProducers: ${n.length} [${n.map(m=>m.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||n.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${n.length}.`),await this.updateConsumers(r,n),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(m){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:m})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,ts,!1)}a(this,Hn)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=wf.formatSocketPeerMessage(s);return new sr(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===Zs.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Zs.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===Zs.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),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.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(x.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(x.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.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),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 n=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:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,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: ${a(this,Bt).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:n,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:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n}=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:n}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===n);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,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 m;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,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:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(m=this.context)==null||m.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,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:n,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:n,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:n,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:n,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:n,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:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),n.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:n,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&&n.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=uh(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:(n=s.flags)==null?void 0:n.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})}},Bt=new WeakMap,ts=new WeakMap,Hn=new WeakMap,pg);let cr=wf;Qi([y.trace("ParticipantController.setupEvents")],cr.prototype,"setupEvents",1);Qi([y.trace("ParticipantController.setupEvents")],cr.prototype,"setupEventsGlobal",1);Qi([y.trace("ParticipantController.processMedia")],cr.prototype,"processMedia",1);Qi([y.trace("ParticipantController.processConsumerClosed")],cr.prototype,"processConsumerClosed",1);Qi([y.trace("ParticipantController.processConsumerResumed")],cr.prototype,"processConsumerResumed",1);Qi([y.trace("ParticipantController.processConsumerPaused")],cr.prototype,"processConsumerPaused",1);Qi([y.trace("ParticipantController.processNewConsumer")],cr.prototype,"processNewConsumer",1);const ye=Es(oh().permissions);var J,Fn,qn,kd,it,St;const Md=class extends At{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);g(this,it);g(this,J,void 0);g(this,Fn,void 0);g(this,qn,void 0);g(this,kd,e=>{var l,u,p;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&lr(a(this,J).chat.private,r.private),r.public&&lr(a(this,J).chat.public,r.public),this.emit("chatUpdate")),i&&lr(a(this,J).connectedMeetings,i),c){const m=E=>{switch(E){case Ur.NONE:return q.Allowed;case Ur.ALLOWED:return q.Allowed;case Ur.NOT_ALLOWED:return q.NotAllowed;case Ur.CAN_REQUEST:return q.CanRequest;default:return}},T={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(T.audio={canProduce:m(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(T.video={canProduce:m(c.video.canProduce)}),(p=c.screenshare)!=null&&p.canProduce&&(T.screenshare={canProduce:m(c.screenshare.canProduce)}),lr(a(this,J).media,T)}n&&(lr(a(this,J).plugins,n),this.emit("pluginsUpdate")),o&&(lr(a(this,J).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&lr(a(this,J),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new R("Could not load preset permissions.","0904");f(this,qn,e),f(this,Fn,i),f(this,J,r),n&&this.setupEvents()}setupEvents(){a(this,qn).getValue("peerSessionStore").on(w.UPDATE_PERMISSIONS,a(this,kd))}static init(e,r,i){let n;return i?n=new Md(e,i,r,!0):n=new Md(e,ye,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,J))==null?void 0:e.stageEnabled)||a(this,Fn)===Xs.Webinar||a(this,Fn)===Xs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,J))==null?void 0:e.acceptStageRequests)||((r=a(this,J))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,J))==null?void 0:e.stageAccess)===q.NotAllowed?q.NotAllowed:((r=a(this,J))==null?void 0:r.stageAccess)===q.CanRequest?q.CanRequest:((i=a(this,J))==null?void 0:i.stageAccess)===q.Allowed||a(this,J).media.audio.canProduce===q.Allowed||a(this,J).media.video.canProduce===q.Allowed||a(this,J).media.screenshare.canProduce===q.Allowed?q.Allowed:a(this,J).media.audio.canProduce===q.CanRequest||a(this,J).media.video.canProduce===q.CanRequest||a(this,J).media.screenshare.canProduce===q.CanRequest?q.CanRequest:q.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,J))==null?void 0:e.acceptWaitingRequests)!=null?r:ye.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,J))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,J))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,J))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===q.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,J))==null?void 0:e.disableParticipantAudio)!=null?r:ye.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,J))==null?void 0:e.canAcceptProductionRequests)!=null?r:ye.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,J))==null?void 0:e.disableParticipantVideo)!=null?r:ye.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,J))==null?void 0:e.kickParticipant)!=null?r:ye.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,J))==null?void 0:e.pinParticipant)!=null?r:ye.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,J))==null?void 0:e.canRecord)!=null?r:ye.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,J))==null?void 0:e.waitingRoomType)!=null?r:ye.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,J))==null?void 0:e.plugins)!=null?r:ye.plugins}get polls(){var e,r;return(r=(e=a(this,J))==null?void 0:e.polls)!=null?r:ye.polls}get canProduceVideo(){var r;const e=(r=a(this,J).media.video.canProduce)!=null?r:ye.media.video.canProduce;return this.stageEnabled&&(a(this,it,St)==="ACCEPTED_TO_JOIN_STAGE"||a(this,it,St)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,it,St)==="OFF_STAGE"||a(this,it,St)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,J).media.screenshare.canProduce)!=null?r:ye.media.screenshare.canProduce;return this.stageEnabled&&(a(this,it,St)==="ACCEPTED_TO_JOIN_STAGE"||a(this,it,St)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,it,St)==="OFF_STAGE"||a(this,it,St)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,J).media.audio.canProduce)!=null?r:ye.media.audio.canProduce;return this.stageEnabled&&(a(this,it,St)==="ACCEPTED_TO_JOIN_STAGE"||a(this,it,St)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,it,St)==="OFF_STAGE"||a(this,it,St)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,J))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:ye.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,J))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:ye.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,J))==null?void 0:e.connectedMeetings)!=null?r:ye==null?void 0:ye.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,J))==null?void 0:e.hiddenParticipant)!=null?r:ye.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,J).showParticipantList)!=null?e:ye.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,J))==null?void 0:e.canChangeParticipantPermissions)!=null?r:ye.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,J).canEditDisplayName)!=null?e:!1}get isRecorder(){return a(this,J).isRecorder}get canSpotlight(){return a(this,J).canSpotlight}get canLivestream(){return a(this,J).canLivestream}get transcriptionEnabled(){return a(this,J).transcriptionEnabled}};let Ru=Md;J=new WeakMap,Fn=new WeakMap,qn=new WeakMap,kd=new WeakMap,it=new WeakSet,St=function(){return a(this,qn).getValue("stageStatus")};var _t;class Rf extends At{constructor(e,r){super(r);h(this,"localMediaHandler");g(this,_t,void 0);f(this,_t,e)}async updatePermission(){var d,l;const e=(u,p)=>{this.mediaPermissions[u]=p;const m={message:this.mediaPermissions[u],kind:u};p==="DENIED"?a(this,_t).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_ERROR,m):a(this,_t).getValue("peerSessionStore").emit(w.MEDIA_PERMISSION_UPDATE,m)};if(ge.getName()==="firefox")return;const r="microphone",i="camera",n=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()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,_t))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,_t))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,_t))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,_t))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,_t))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,p;if(ge.init(),i&&f(this,_t,i),!this.localMediaHandler)try{let m=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)m=!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 ft(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:P,constraints:k}=T;this.populateMediaPermissionsInCallstats({message:P,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:P},constraints:k,mediaPermissionsErrors:{kind:E,message:P}}),this.emit("mediaPermissionError",T),this.emit("mediaPermissionUpdate",{message:P,kind:E})}),m){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(m){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:m.name,message:m.message}})}}set context(e){f(this,_t,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})}}_t=new WeakMap;var $0=Object.defineProperty,B0=Object.getOwnPropertyDescriptor,ct=(s,t,e,r)=>{for(var i=r>1?void 0:r?B0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$0(t,e,i),i},jn,nt,Gn,xe,$s,Qr,Ue,ze,Wn,zc,Ae,Oe,Jn,Kn,Ho,bu,gg;let Ge=(gg=class extends Rf{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);g(this,$s);g(this,Ue);g(this,Wn);g(this,Ae);g(this,Ho);h(this,"name");h(this,"picture");h(this,"customParticipantId");h(this,"waitlistStatus");g(this,jn,void 0);g(this,nt,void 0);g(this,Gn,void 0);h(this,"role");h(this,"userId");h(this,"organizationId");h(this,"supportsRemoteControl",!1);h(this,"device");g(this,xe,void 0);h(this,"hidden",!1);h(this,"presetName");h(this,"roomState","init");g(this,Jn,new Set);g(this,Kn,new Set);f(this,xe,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",f(this,nt,r),f(this,jn,i),this.hidden=!1,f(this,Gn,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ge.isElectron(),this.device=ge.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),O(this,Ho,bu).call(this)}get telemetry(){return a(this,xe).getValue("telemetry")}get stageStatus(){return a(this,xe).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Ue,ze).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,xe).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var m,T,E,P,k,C;let c=(T=(m=t.getValue("defaults"))==null?void 0:m.audio)!=null?T:!0,d=(P=(E=t.getValue("defaults"))==null?void 0:E.video)!=null?P:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Ge(t,e,r,i,n),u=YI(i.mediaConstraints);lr(u,(k=t.getValue("defaults"))==null?void 0:k.mediaConfiguration);const p=(C=t.getValue("defaults"))==null?void 0:C.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"),a(this,nt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",O(this,Ho,bu));const t=a(this,Wn,zc);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)}),a(this,Ae,Oe)&&this.audioEnabled)try{await a(this,Ue,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)}),a(this,Ae,Oe)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,Ae,Oe))try{await a(this,Ue,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=a(this,Wn,zc))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,Ae,Oe)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,Ue,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=a(this,xe))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,Ae,Oe)&&await a(this,Ue,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,xe))==null||e.getValue("callstats").videoOff()}),a(this,nt).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,nt).canProduceAudio!==q.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&&a(this,nt).canProduceVideo!==q.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,nt).canProduceScreenshare!==q.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,nt)}get config(){return a(this,jn)}get roomJoined(){var t;return a(this,jn).viewType===Xs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,Ae,Oe)}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!==q.NotAllowed&&!(a(this,nt).canProduceAudio===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,xe))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,Ae,Oe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,Ue,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(a(this,nt).canProduceVideo!==q.NotAllowed&&!(a(this,nt).canProduceVideo===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,xe))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,Ae,Oe)&&this.stageStatus==="ON_STAGE")try{await a(this,Ue,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 R("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,Ae,Oe))throw new R("Can`t enable screenshare without joining room","1105");if(a(this,nt).canProduceScreenshare!==q.NotAllowed&&!(a(this,nt).canProduceScreenshare===q.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 a(this,Ue,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(),a(this,Ae,Oe)&&a(this,Ue,ze).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,xe))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,Ae,Oe)&&await a(this,Ue,ze).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,xe))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,Ae,Oe)&&await a(this,Ue,ze).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,Gn,t);const r=t?"pinned":"unpinned";(i=a(this,$s,Qr))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Gn)}async pin(){if(!a(this,Ae,Oe))throw new R("Can`t pin participants without joining room","1105");return this.show(),a(this,Ue,ze).pinPeer(this.id)}async unpin(){if(!a(this,Ae,Oe))throw new R("Can`t unpin participants without joining room","1105");return a(this,Ue,ze).pinPeer(null)}async hide(){if(!a(this,Ae,Oe))throw new R("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,Ae,Oe))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,n;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||((n=e==null?void 0:e.speaker)==null?void 0:n.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){a(this,Ae,Oe)&&await a(this,Ue,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){a(this,Ae,Oe)&&await a(this,Ue,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=a(this,Wn,zc))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Jn).add(t):a(this,Kn).add(t),this.updateVideo(t),e||(i=a(this,$s,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){a(this,$s,Qr).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Jn).delete(t):(a(this,Kn).delete(t),a(this,$s,Qr).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;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=a(this,$s,Qr))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,$s,Qr))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},jn=new WeakMap,nt=new WeakMap,Gn=new WeakMap,xe=new WeakMap,$s=new WeakSet,Qr=function(){return a(this,xe).getValue("pip")},Ue=new WeakSet,ze=function(){return a(this,xe).getValue("roomNodeClient")},Wn=new WeakSet,zc=function(){return a(this,xe).getValue("audioPlayback")},Ae=new WeakSet,Oe=function(){var t;return((t=a(this,xe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Jn=new WeakMap,Kn=new WeakMap,Ho=new WeakSet,bu=function(){Array.from(a(this,Kn)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Jn)).forEach(t=>this.updateVideo(t,!0))},gg);ct([y.trace("Self.cleanupEvents")],Ge.prototype,"cleanupEvents",1);ct([y.trace("Self.setupEvents")],Ge.prototype,"setupEvents",1);ct([y.trace("Self.setupTracks")],Ge.prototype,"setupTracks",1);ct([y.trace("Self.destructMediaHandler")],Ge.prototype,"destructMediaHandler",1);ct([y.trace("Self.removeDocumentEventListeners")],Ge.prototype,"removeDocumentEventListeners",1);ct([or.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.enableAudio")],Ge.prototype,"enableAudio",1);ct([or.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.enableVideo")],Ge.prototype,"enableVideo",1);ct([y.trace("Self.updateVideoConstraints")],Ge.prototype,"updateVideoConstraints",1);ct([y.trace("Self.enableScreenShare"),or.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Ge.prototype,"enableScreenShare",1);ct([y.trace("Self.updateScreenshareConstraints")],Ge.prototype,"updateScreenshareConstraints",1);ct([or.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),y.trace("Self.disableAudio")],Ge.prototype,"disableAudio",1);ct([or.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),y.trace("Self.disableVideo")],Ge.prototype,"disableVideo",1);ct([or.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),y.trace("Self.disableScreenShare")],Ge.prototype,"disableScreenShare",1);ct([y.trace("Self.setDevice")],Ge.prototype,"setDevice",1);Ge=ct([et("1100")],Ge);class Sh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Sh)}}class vh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,vh)}}var Fo;class ku{constructor(t,e=!1){h(this,"pendingTasks",new Map);h(this,"nextTaskId",0);h(this,"stopping",!1);g(this,Fo,void 0);this.log=e,f(this,Fo,{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,n)=>{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),n(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 Sh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new vh)}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();a(this,Fo).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)}}}Fo=new WeakMap;function H0(s,t){const e=new Error(t);return e.name=s,e}class po extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,po):this.stack=new Error(t).stack}}class mt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,mt):this.stack=new Error(t).stack}}class fr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,mt):this.stack=new Error(t).stack}}const Fp=s=>new Promise(t=>setTimeout(t,s));async function bf(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=p=>{l=!0,r(p)};for(;c<n;){try{const p=await s(c,u);return e(p)}catch(p){if(d=p,l)break;if(c<n)i==="linear"?await Fp(o*(c+1)):i==="exponential"&&await Fp(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function F0(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function q0(s){return s.map(t=>({uri:t.uri}))}function Uc(s){return{codecs:F0(s.codecs),headerExtensions:q0(s.headerExtensions?s.headerExtensions:[])}}function j0(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 n={audio:Uc(t),video:Uc(e)};return{sender:{audio:Uc(r),video:Uc(i)},receiver:n}}var $e;class G0{constructor(t){g(this,$e,void 0);h(this,"events");f(this,$e,t),this.events=os}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,$e).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:Ew.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,$e).sendMessagePromise(this.events.createWebRTCTransport,zC.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=xm.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,$e).sendMessagePromise(this.events.produce,Vw.toBinary(t))).payload,r=SR.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,$e).sendMessagePromise(this.events.consume,Aw.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=fR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,$e).sendMessagePromise(this.events.closeProducer,qw.toBinary(t))).payload,{description:r}=wR.fromBinary(e);return r}async closeConsumer(t){return(await a(this,$e).sendMessagePromise(this.events.closeConsumer,Gw.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,$e).sendMessagePromise(this.events.updateConsumersSimulcastConfig,Nw.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,$e).sendMessagePromise(this.events.hostControlPeer,Qw.toBinary(r))).payload;if(!i)return!1;const{status:n}=DR.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,$e).sendMessagePromise(this.events.hostControlAllPeers,Zw.toBinary(e))).payload;if(!r)return!1;const{status:i}=NR.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,$e).sendMessagePromise(x.kickAll,Hm.toBinary(t))}async kickPeer(t){a(this,$e).sendMessagePromise(x.kick,Wm.toBinary(t))}async changeDisplayName(t){const e=(await a(this,$e).sendMessagePromise(this.events.changeDisplayName,zw.toBinary(t))).payload;if(!e)return!1;const{status:r}=VR.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,$e).sendMessagePromise(this.events.selfJoinComplete,_w.toBinary(t))).payload;return nu.fromBinary(e)}async audioActivity(t){a(this,$e).sendMessage(this.events.audioActivity,QC.toBinary(t))}}$e=new WeakMap;var ys=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(ys||{}),qo;class Rl extends Ze.EventEmitter{constructor(e){super();g(this,qo,void 0);f(this,qo,e),this.setMaxListeners(1/0)}get logger(){return a(this,qo).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),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((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}qo=new WeakMap;class yh extends Rl{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:n,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",...n},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 n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}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 n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}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 Eh extends yh{static createFactory(t){return()=>new Eh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=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 m;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=((m=p.sdpFmtpLine)==null?void 0:m.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)}`),n.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(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.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 ud extends yh{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new ud(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?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,m)=>{var V;const T=Yt.parse(p),E=T.media[T.media.length-1],P=E.rtp.filter(L=>m.some(B=>B.name===L.codec)),k=E.fmtp.filter(L=>P.some(B=>B.payload===L.payload)),C=(V=E.rtcpFb)==null?void 0:V.filter(L=>P.some(B=>B.payload===L.payload)),I=P.map(L=>L.payload);return T.media[T.media.length-1].rtp=P,T.media[T.media.length-1].fmtp=k,T.media[T.media.length-1].rtcpFb=C,T.media[T.media.length-1].payloads=I.join(" "),Yt.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:m}=this,T=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${m?"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 n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Ph extends yh{static createFactory(t){return()=>new Ph(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 n=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 m;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=((m=p.sdpFmtpLine)==null?void 0:m.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)}`),n.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,m=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=${m}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.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 W0(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var jo,Ci,gs,Ad,ms,hr,Go,Mu,Id,kf,Dd,Mf;class J0 extends Rl{constructor(e,r){var i;super(e);g(this,ms);g(this,Go);g(this,Id);g(this,Dd);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,jo,void 0);g(this,Ci,void 0);g(this,gs,void 0);g(this,Ad,void 0);this.id=r.id,this.localId=r.localId,f(this,jo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,gs,!1),this.producerId=r.producerId,this.track=r.track,f(this,Ci,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,O(this,Id,kf).call(this),f(this,Ad,e)}get closed(){return a(this,gs)}get kind(){return this.track.kind}get paused(){return a(this,Ci)}close(e,r){a(this,gs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,ms,hr)),f(this,gs,!0),r&&(O(this,Dd,Mf).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,gs))throw new mt("closed");return a(this,jo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,ms,hr)),a(this,gs)){this.logger.error("consumer::pause() | Consumer closed",a(this,ms,hr));return}f(this,Ci,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,ms,hr)),a(this,gs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,ms,hr));return}f(this,Ci,!1),this.track.enabled=!0,this.safeEmit("resume")}}jo=new WeakMap,Ci=new WeakMap,gs=new WeakMap,Ad=new WeakMap,ms=new WeakSet,hr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Go=new WeakSet,Mu=function(){this.logger.debug('Consumer::track "ended" event',a(this,ms,hr)),this.safeEmit("trackended")},Id=new WeakSet,kf=function(){this.track.addEventListener("ended",O(this,Go,Mu).bind(this))},Dd=new WeakSet,Mf=function(){try{this.track.removeEventListener("ended",O(this,Go,Mu)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,ms,hr),error:e})}};var ss,zn,Yn,wi,Ht,Ke,Mr,Qn,Od,Ct,zt;class K0 extends Rl{constructor(e,r){var i,n;super(e);g(this,Ct);h(this,"id");h(this,"localId");g(this,ss,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");g(this,zn,void 0);g(this,Yn,void 0);g(this,wi,void 0);g(this,Ht,!1);g(this,Ke,void 0);g(this,Mr,void 0);g(this,Qn,void 0);g(this,Od,void 0);this.id=r.id,this.localId=r.localId,f(this,Ke,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,Mr,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Qn,void 0),f(this,zn,r.stopTracks),f(this,Yn,r.disableTrackOnPause),f(this,wi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,ss,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Od,e)}get closed(){return a(this,Ht)}get track(){return a(this,Ke)}get paused(){return a(this,Mr)}get maxSpatialLayer(){return a(this,Qn)}async close(e){if(a(this,Ht))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Ct,zt)),f(this,Ht,!0),this._destroyTrack(),e===go){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,ss).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,Ht))throw new mt("closed");return a(this,ss).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Ct,zt)),a(this,Ht)&&this.logger.error("Producer::pause() | Producer closed",a(this,Ct,zt)),f(this,Mr,!0),a(this,Ke)&&a(this,Yn)&&(a(this,Ke).enabled=!1),a(this,wi)&&a(this,ss).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Ct,zt)),a(this,Ht)){this.logger.error("Producer::resume() | Producer closed",a(this,Ct,zt));return}f(this,Mr,!1),a(this,Ke)&&a(this,Yn)&&(a(this,Ke).enabled=!0),a(this,wi)&&a(this,ss).replaceTrack(this.localId,a(this,Ke)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Ct,zt)),a(this,Ht)){if(e&&a(this,zn))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Ct,zt),error:r})}throw new mt("closed")}else if(e&&e.readyState==="ended")throw new mt("track ended");if(e===a(this,Ke)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Ct,zt));return}(!a(this,wi)||!a(this,Mr))&&await a(this,ss).replaceTrack(this.localId,e),this._destroyTrack(),f(this,Ke,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,Ht))throw new mt("closed");if(this.kind!=="video")throw new po("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,ss).setMaxSpatialLayer(this.localId,e),f(this,Qn,e)}async setRtpEncodingParameters(e){if(a(this,Ht))throw new mt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,ss).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Ct,zt)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,Ke)&&a(this,Ke).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,Ke))try{a(this,Ke).removeEventListener("ended",this._onTrackEnded),a(this,zn)&&a(this,Ke).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Ct,zt),error:r})}}}ss=new WeakMap,zn=new WeakMap,Yn=new WeakMap,wi=new WeakMap,Ht=new WeakMap,Ke=new WeakMap,Mr=new WeakMap,Qn=new WeakMap,Od=new WeakMap,Ct=new WeakSet,zt=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Af(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Kl(s){return Math.random().toString(36).substring(2,2+s)}const $c=1;function qp(s){const t=s;return delete t.payload._bolt,t}function z0(s){return s.payload&&Af(s.payload)}function Y0(s){var t,e;return z0(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var Ar,Nd,Ri;const dn=class extends Ze.EventEmitter{constructor(e,r,i,n){super();h(this,"channel");h(this,"queue");h(this,"serverProtocolVersion");g(this,Ar,new Map);g(this,Nd,void 0);g(this,Ri,void 0);h(this,"respond",(e,r,i=!1)=>{let n;i?n=dn.createErrorResponse(e,r):n=dn.createResponse(e,r),this.channel.send(JSON.stringify(n))});h(this,"notify",e=>{const r=dn.createNotification(e);this.channel.send(JSON.stringify(r))});h(this,"request",async e=>{const r=dn.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(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 n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,p=(l+1)*n;c.push(r.slice(u,p))}const d=qr.v4();for(let l=0;l<o;l+=1){const u=c[l],m=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,Ri).debug(`Sending message chunk over dc: ${m}`),this.channel.send(m)}}else a(this,Ri).debug(`Sending message over dc: ${r}`),this.channel.send(r)});h(this,"processMessage",e=>{var i;a(this,Ar).has(e.id)||a(this,Ar).set(e.id,[]);const r=a(this,Ar).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,Ar).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,Ar).delete(e.id);const c=JSON.parse(o);if(!c.payload||!Af(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?(a(this,Ri).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(qp(e)):i.resolve(qp(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:Kl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Nd,e),f(this,Ri,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Xr=dn;Ar=new WeakMap,Nd=new WeakMap,Ri=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:Kl(8),type:"REQUEST",version:$c}}}}),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:$c}}}}),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:Kl(8),type:"NOTIFY",version:$c}}}}),h(Xr,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:$c}}}));const go="transport closed";var bi;const ln=class extends Rl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:p}){var P,k,C;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,bi,void 0);f(this,bi,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const T=W0(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 ku(m,!0),this.handler=n(),this.handler.enableHighBitrate=(P=p==null?void 0:p.enableHighBitrate)!=null?P:!1,this.handler.enableStereo=(k=p==null?void 0:p.enableStereo)!=null?k:!1,this.handler.enableDtx=(C=p==null?void 0:p.enableDtx)!=null?C:!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(I=>{const V=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),I(!1)},E);this.once("connected",()=>{clearTimeout(V),I(!0)}),this.once("disconnect",()=>{clearTimeout(V),I(!1)}),this.once("close",()=>{clearTimeout(V),I(!1)})}),this.eventsDCReadyPromise=new Promise(I=>{this.eventsDCReadyPromiseResolver=I}),this.handler.on("@connectionstatechange",I=>{I!==this.connectionState&&(this.logger.debug(`connection state changed to ${I}`),this.connectionState=I,I==="connected"&&(this.connected=!0,this.emit("connected")),I==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(I==="failed"||I==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",I))}),this.handler.on("@icecandidate",({candidate:I})=>{this.closed||this.safeEmit("icecandidate",I)}),this.handler.on("dc_open",I=>{let V=this.datachannels.get(I.label);V||(V||(V=new Xr(a(this,bi),I,I.label,this.serverId),this.datachannels.set(I.label,V)),this.eventsDCFailureTimer=setTimeout(()=>{I.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",I.label))},5e3))}),this.handler.on("datachannel",(I,V)=>{I.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(I.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:I.label,message:V}});return}try{const B=JSON.parse(V);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:B.id,count:B.count,chunkIndex:B.chunkIndex,chunk:B.chunk,transprtId:this.serverId}});const $=L.processMessage(B);if(!$)return;this.logger.debug(`datachannel message with id:${B.id} on transport:${this.serverId}complete - ${JSON.stringify($)}`),this.emit(`datachannel:${I.label}`,L.label,$)}catch(B){this.logger.error("error parsing message",{error:B})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",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(go).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(go)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new mt("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:n,answer:o}=await e(r);this.setServerId(n),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 mt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new po("not a sending Transport");if(r.readyState==="ended")throw new mt("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 fr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:m,localId:T,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:P,callback:k,sender:C,mid:I}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:V,producerId:L}=await r({offer:P,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...p||{},mid:I},codecOptions:c,producingTransportId:this.serverId}),B=await k(V);return{producerId:L,localId:B,rtpSender:C}},"Transport.produce");return this.createProducerObject({id:m,localId:T,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:p,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new K0(a(this,bi),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 mt("closed");if(this.direction!=="recv")throw new po("not a receiving transport");if(!await this.transportConnectionPromise)throw new fr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,p)=>{n[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(n).map(([u,p])=>p.then(m=>l.push(m)).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=Yt.parse(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=Yt.parse(e.sdp);return n.media=n.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:Yt.write(n)}}static parseHeaderExtensionMappings(e){const r=Yt.parse(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Yt.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Yt.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=ln.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=ln.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=ln.setCodecAndFmtpMappings(c,i,n),c=ln.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=Yt.parse(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},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 n}),r.sdp=Yt.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 n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:p,mimeType:m}=e,T=`${c}:${p}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(P,k)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${T} producingPeerId: ${n}`),this.consumerTrackEvents.delete(T),E.isTimedout=!0,k(E)},5e3),I=(L,B)=>{try{if(L.readyState==="ended")clearTimeout(C),k(E);else{const $=L;$.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const z=new J0(a(this,bi),{id:r,localId:B.mid,transceiver:B,track:$,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:B.receiver,mimeType:m});this.consumers.set(r,z),z.once("close",()=>{this.consumers.delete(z.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:p,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",z),clearTimeout(C),P(z)}}catch($){this.logger.warn("error while creating consumer:",$),clearTimeout(C),k(E)}},V=this.unknownTracksMap.get(T);V?(this.logger.info(`track event already received [trackId: ${V.track.id}] [mid: ${V.transceiver.mid}]`),this.unknownTracksMap.delete(T),I(V.track,V.transceiver)):(this.logger.info(`Registering onTrack handler for key ${T} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(T,I))})}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 H0("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Au=ln;bi=new WeakMap;function Q0(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=vg.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 Bs,ki;class X0{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");g(this,Bs,void 0);g(this,ki,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,Bs,t),f(this,ki,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,ki).debug(`Device::constructor() | handler given: ${e}`);else if(e=Q0(a(this,ki)),e)a(this,ki).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Eh.createFactory(a(this,Bs));break;case"Safari12":this.handlerFactory=Ph.createFactory(a(this,Bs));break;case"Firefox60":this.handlerFactory=ud.createFactory(a(this,Bs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=ud.createFactory(a(this,Bs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=qr.v4();return new Au(a(this,Bs),{id:e,...t,handlerFactory:this.handlerFactory})}}Bs=new WeakMap,ki=new WeakMap;const Z0=2e3;var Xn,Be,He,Wo,Jo,Mi,Zn,Ko,ea,Ai,fs,ta,Yc,zo,Iu,Ld,If,Yo,Du,Vd,Df,xd,Of,Ud,Nf,$d,Lf,Bd,Vf,Qo,Ou,Ir,rn;class eD extends Ze.EventEmitter{constructor(e,r){super();g(this,ta);g(this,zo);g(this,Ld);g(this,Yo);g(this,Vd);g(this,xd);g(this,Ud);g(this,$d);g(this,Bd);g(this,Qo);g(this,Ir);h(this,"context");g(this,Xn,void 0);g(this,Be,void 0);g(this,He,void 0);g(this,Wo,void 0);g(this,Jo,void 0);g(this,Mi,void 0);g(this,Zn,void 0);g(this,Ko,void 0);g(this,ea,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Ai,void 0);g(this,fs,"all");this.context=e,f(this,Mi,r),f(this,Xn,new X0(e)),f(this,Zn,new G0(r)),f(this,Ko,os),a(this,ta,Yc).mediaState={send:{state:ys.NEW},recv:{state:ys.NEW}},Ta(this.context,"forceRelay")&&f(this,fs,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,fs)}`),O(this,zo,Iu).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Mi)}get socketHandler(){return a(this,Zn)}get sendTransport(){return a(this,Be)}get recvTransport(){return a(this,He)}get events(){return a(this,Ko)}set sendTransportConnectedCallback(e){f(this,Wo,e)}set recvTransportConnectedCallback(e){f(this,Jo,e)}async setupTransports(e){await O(this,Ld,If).call(this,e);let r,i;e.send&&(r=O(this,Yo,Du).call(this,a(this,Be)).then(n=>{try{a(this,Wo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=O(this,Yo,Du).call(this,a(this,He)).then(n=>{try{a(this,Jo).call(this,n)}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:n,serverId:o,direction:c}=a(this,Be);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,Be).close(),a(this,Be).removeAllListeners(),f(this,Be,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,He);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,He))==null||r.close(),(i=a(this,He))==null||i.removeAllListeners(),f(this,He,void 0)}O(this,zo,Iu).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Xn=new WeakMap,Be=new WeakMap,He=new WeakMap,Wo=new WeakMap,Jo=new WeakMap,Mi=new WeakMap,Zn=new WeakMap,Ko=new WeakMap,ea=new WeakMap,Ai=new WeakMap,fs=new WeakMap,ta=new WeakSet,Yc=function(){return this.context.getValue("connectionHandler")},zo=new WeakSet,Iu=function(){f(this,Ai,{send:void 0,recv:void 0})},Ld=new WeakSet,If=async function(e){var o,c,d,l,u,p,m,T;Ta(this.context,"forceRelay")&&f(this,fs,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,fs)}`);const n=await gt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&O(this,xd,Of).call(this,{iceServers:n,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:(m=(p=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:p.enableStereo)!=null?m:!1,enableDtx:!1},iceTransportPolicy:a(this,fs)}),e.recv&&O(this,Ud,Nf).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(T=this.context.getValue("modules").e2ee)==null?void 0:T.enabled},iceTransportPolicy:a(this,fs)})},Yo=new WeakSet,Du=async function(e){const{id:r,serverId:i,direction:n}=e;O(this,$d,Lf).call(this,e);try{return await bf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new fr("Cannot reconnect closed transport");await O(this,Vd,Df).call(this,e)}catch(l){if(l instanceof fr){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:n}}),e.close(),e.removeAllListeners(),o}},Vd=new WeakSet,Df=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Mi).isConnected)throw new fr("Socket is not connected");if(e.connectionState==="closed")throw new fr("Transport is closed");try{await e.connect(n=>O(this,Bd,Vf).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,ea).transportFailureCount[i]+=1,n.message==="ice connection failed"?new fr(n.message):n}},xd=new WeakSet,Of=function(e){var r,i;if(a(this,Be)&&a(this,Be).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,Be))==null?void 0:r.id,serverId:(i=a(this,Be))==null?void 0:i.serverId,type:"send"}});return}f(this,Be,a(this,Xn).createTransport({...e,direction:"send"})),O(this,Ir,rn).call(this,{state:ys.NEW,direction:"send",sfuSessionId:a(this,Be).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,Be))},Ud=new WeakSet,Nf=function(e){var r,i;if(a(this,He)&&a(this,He).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,He))==null?void 0:r.id,serverId:(i=a(this,He))==null?void 0:i.serverId,type:"recv"}});return}f(this,He,a(this,Xn).createTransport({...e,direction:"recv"})),O(this,Ir,rn).call(this,{state:ys.NEW,direction:"recv",sfuSessionId:a(this,He).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,He))},$d=new WeakSet,Lf=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{O(this,Ir,rn).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{O(this,Ir,rn).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,Ai)[r];c!==void 0&&(clearTimeout(c),a(this,Ai)[r]=void 0)};switch(n){case"connected":o(),a(this,ea).lastConnectionTime=performance.now();break;case"disconnected":a(this,Ai)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await O(this,Qo,Ou).call(this,e.direction)},Z0);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 O(this,Qo,Ou).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,Y0(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 ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Bd=new WeakSet,Vf=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?tr.SUBSCRIBER:tr.PUBLISHER},producers:[]};return a(this,Zn).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},Qo=new WeakSet,Ou=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Mi).isConnected&&a(this,ea).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,fs,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,Be)}),this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,He)}),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,Be):a(this,He);O(this,Ir,rn).call(this,{state:ys.CONNECTED,direction:e,sfuSessionId:r.serverId})},Ir=new WeakSet,rn=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,ta,Yc).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(w.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,ta,Yc).mediaState[i]})};var Hd,Ft;class tD{constructor(t,e,r,i,n){g(this,Hd,void 0);g(this,Ft,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Hd,t),f(this,Ft,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,m={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:p,...m})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,Ft).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(m){}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{a(this,Ft).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,Ft).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:tr.SUBSCRIBER}};return a(this,Ft).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,ew.toBinary(r)),a(this,Ft).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,Ft).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,Ft).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:tr.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=bR.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(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,Ft).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Hd=new WeakMap,Ft=new WeakMap;class _h{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Yt.parse(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var p,m;const c=_h.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:tr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(m=n[0])==null?void 0:m.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function sD(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}var Dr,Or,sa,Xo,Ts,Fd,Hs,ra,Zo,Nu,qd,xf,jd,Uf,Gd,$f,Wd,Bf;class rD extends eD{constructor(e,r){super(e,r);g(this,Zo);g(this,qd);g(this,jd);g(this,Gd);g(this,Wd);g(this,Dr,void 0);g(this,Or,void 0);g(this,sa,void 0);g(this,Xo,void 0);g(this,Ts,void 0);g(this,Fd,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Hs,[]);g(this,ra,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,Xo,new _h(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,sa).clear(),f(this,Ts,new tD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,Dr)}get consumers(){return a(this,Or)}get producerIdToConsumerIdMap(){return a(this,sa)}get logger(){return this.context.getValue("logger")}reset(){f(this,Dr,new Map),f(this,Or,new Map),f(this,sa,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,O(this,qd,xf).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,o),O(this,jd,Uf).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,Fd).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;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),(n=this.context.getValue("modules").e2ee)!=null&&n.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(a(this,Dr).entries()).map(([,e])=>e.close()))}async closeAllProducersLocally(){var r;const e=(r=this.sendTransport)==null?void 0:r.handler;await Promise.all(Array.from(a(this,Dr).values()).map(async i=>{try{if(e){const n=e.midTransceiverMap.get(i.localId);n&&(await n.sender.replaceTrack(null),n.direction="inactive")}}catch(n){this.logger.warn("closeAllProducersLocally: failed to deactivate transceiver",{producer:{id:i.id,kind:i.kind,appData:i.appData},error:n})}await i.close(go)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,ra)||clearTimeout(a(this,ra)),f(this,Hs,a(this,Hs).concat(e)),await O(this,Zo,Nu).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Ts))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,Ts).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Or).keys()))}async switchConsumersToLayer(e,r){a(this,Ts).switchConsumersToLayer(e,r)}}Dr=new WeakMap,Or=new WeakMap,sa=new WeakMap,Xo=new WeakMap,Ts=new WeakMap,Fd=new WeakMap,Hs=new WeakMap,ra=new WeakMap,Zo=new WeakSet,Nu=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Hs).splice(0,a(this,Hs).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,O(this,Gd,$f).bind(this),a(this,Ts).negotiate.bind(a(this,Ts)));if(o.forEach(O(this,Wd,Bf).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);f(this,Hs,a(this,Hs).concat(d)),f(this,ra,setTimeout(O(this,Zo,Nu).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=sD(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},qd=new WeakSet,xf=function(e){return a(this,Xo).create(e)},jd=new WeakSet,Uf=function(e,r){e.on("close",async(i,n)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==go){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:tr.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"}}),n({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"}})}),a(this,Dr).set(e.id,e)},Gd=new WeakSet,$f=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Ts).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Wd=new WeakSet,Bf=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,Or).delete(e.id),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:e.id})}),a(this,Or).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 ec,tc,sc,ia,na,aa,rc,ic,oa,lt,rs,is,Ii,Di,Fs,nc,Jd,Hf,Kd,Ff,zd,qf,Yd,jf;const Qd=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,Jd);g(this,Kd);g(this,ec,void 0);g(this,tc,void 0);g(this,sc,void 0);g(this,ia,void 0);g(this,na,void 0);g(this,aa,void 0);g(this,rc,void 0);g(this,ic,void 0);g(this,oa,void 0);g(this,lt,void 0);g(this,rs,void 0);g(this,is,!1);g(this,Ii,0);g(this,Di,0);g(this,Fs,[]);g(this,nc,void 0);f(this,ia,t),f(this,lt,t),f(this,ec,e),f(this,tc,r),f(this,sc,i),f(this,na,n),f(this,aa,o),f(this,rc,c),f(this,ic,d),f(this,oa,l),f(this,nc,u),f(this,rs,t/2)}get voiceDetected(){return a(this,is)}processAudioChunk(t){var o,c;const e=O(o=Qd,zd,qf).call(o,t),r=O(c=Qd,Yd,jf).call(c,t);return O(this,Jd,Hf).call(this,e),e/a(this,rs)>a(this,oa)&&e>a(this,lt)&&r>a(this,ec)?(f(this,Ii,a(this,Ii)+1),f(this,Di,a(this,sc)),a(this,Ii)>=a(this,tc)&&f(this,is,!0)):(f(this,Ii,0),a(this,Di)>0?f(this,Di,a(this,Di)-1):a(this,is)&&f(this,is,!1),a(this,is)||O(this,Kd,Ff).call(this,e)),{energy:e,isVoice:a(this,is)}}reset(){f(this,is,!1),f(this,Ii,0),f(this,Di,0),f(this,lt,a(this,ia)),f(this,rs,a(this,ia)/2),f(this,Fs,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,lt),backgroundNoiseEnergy:a(this,rs),energyRatioThreshold:a(this,oa)}}};let Wa=Qd;ec=new WeakMap,tc=new WeakMap,sc=new WeakMap,ia=new WeakMap,na=new WeakMap,aa=new WeakMap,rc=new WeakMap,ic=new WeakMap,oa=new WeakMap,lt=new WeakMap,rs=new WeakMap,is=new WeakMap,Ii=new WeakMap,Di=new WeakMap,Fs=new WeakMap,nc=new WeakMap,Jd=new WeakSet,Hf=function(t){a(this,is)?f(this,lt,a(this,aa)*a(this,lt)+(1-a(this,aa))*t):f(this,lt,a(this,na)*a(this,lt)+(1-a(this,na))*a(this,rs)),f(this,lt,Math.max(a(this,rc),Math.min(a(this,ic),a(this,lt))))},Kd=new WeakSet,Ff=function(t){if(t<a(this,lt)*1.2)if(a(this,Fs).push(t),a(this,Fs).length>a(this,nc)&&a(this,Fs).shift(),a(this,Fs).length>=10){const e=[...a(this,Fs)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,rs,e[r])}else f(this,rs,.95*a(this,rs)+.05*t)},zd=new WeakSet,qf=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Yd=new WeakSet,jf=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(Wa,zd),g(Wa,Yd);var ac;class jp{constructor(t){h(this,"RNAudioSampleHandler");g(this,ac,void 0);f(this,ac,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 a(this,ac).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()}}ac=new WeakMap;var oc;class Gp{constructor(t){h(this,"audioContext");h(this,"analyser");g(this,oc,void 0);f(this,oc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,oc).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)}}oc=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 qs,js,Gs,cc,ca,da,Nr,Oi,la,Ni,Ws,Ss,Xd,Gf,dc,Lu,Zd,Wf,el,Jf;const no=class{constructor(t,e){g(this,Xd);g(this,Zd);g(this,qs,void 0);g(this,js,void 0);g(this,Gs,void 0);g(this,cc,void 0);g(this,ca,void 0);g(this,da,void 0);g(this,Nr,void 0);g(this,Oi,void 0);g(this,la,void 0);g(this,Ni,void 0);g(this,Ws,void 0);g(this,Ss,void 0);this.reportRequest=e,f(this,Ni,t),f(this,da,new Wa);const{isReactNative:r}=navigator;f(this,Ws,r?new jp(a(this,Ni)):new Gp(a(this,Ni))),f(this,Ss,r?iD:Bc)}get logger(){return a(this,Ni).getValue("logger")}set producerId(t){f(this,Gs,t)}set audioTrack(t){f(this,cc,t),a(this,Ws)instanceof Gp&&(a(this,Ws).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Gs)}`),a(this,qs)&&a(this,Ss).clearInterval(a(this,qs)),f(this,qs,a(this,Ss).setInterval(async()=>{var i;if(!a(this,cc)||!a(this,Gs))return;const{energy:t}=O(this,Xd,Gf).call(this),e=O(i=no,dc,Lu).call(i,t);let r=.9;a(this,la)!==e&&a(this,la)?r=.9:e?r=.3:r=.5,f(this,ca,(a(this,ca)||0)*(1-r)+t*r)},nD)),a(this,js)&&a(this,Ss).clearInterval(a(this,js)),f(this,js,a(this,Ss).setInterval(O(this,Zd,Wf).bind(this),aD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Gs)}`),a(this,qs)&&(a(this,Ss).clearInterval(a(this,qs)),f(this,qs,void 0)),a(this,js)&&(a(this,Ss).clearInterval(a(this,js)),f(this,js,void 0))}catch(t){}a(this,da).reset(),a(this,Ws)instanceof jp&&a(this,Ws).stop()}};let Ja=no;qs=new WeakMap,js=new WeakMap,Gs=new WeakMap,cc=new WeakMap,ca=new WeakMap,da=new WeakMap,Nr=new WeakMap,Oi=new WeakMap,la=new WeakMap,Ni=new WeakMap,Ws=new WeakMap,Ss=new WeakMap,Xd=new WeakSet,Gf=function(){var o;const{samples:t}=a(this,Ws),{energy:e,isVoice:r}=a(this,da).processAudioChunk(t),i=O(o=no,el,Jf).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Nr)||i<a(this,Nr))&&f(this,Nr,i),(!a(this,Oi)||i>a(this,Oi))&&f(this,Oi,i),{energy:(i-a(this,Nr))/(a(this,Oi)-a(this,Nr))*10||0,isVoice:r})},dc=new WeakSet,Lu=function(t){return t<5},Zd=new WeakSet,Wf=function(t=a(this,ca)){var r;if(!a(this,Gs)||!t)return;const e={producerId:a(this,Gs),energy:Math.round(t),silent:O(r=no,dc,Lu).call(r,t)};f(this,la,e.silent),this.reportRequest(e)},el=new WeakSet,Jf=function(t){const e=Math.log10(t);return Math.round(e)},g(Ja,dc),g(Ja,el);var oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,oe=(s,t,e,r)=>{for(var i=r>1?void 0:r?cD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oD(t,e,i),i},lc,uc,Qe,H,tl,at,Li,Vi,xi,hc,wt,vs,Xe,ut,Js,Zr,sl,Kf,rl,zf,il,Yf,pc,Vu,nl,Qf,al,Xf,ot,vt,Ui,Ka,ol,Zf,cl,eT,dl,tT;class se{constructor(t,e){g(this,Js);g(this,sl);g(this,rl);g(this,il);g(this,pc);g(this,nl);g(this,al);g(this,ot);g(this,Ui);g(this,ol);g(this,cl);g(this,dl);h(this,"context");h(this,"authToken");h(this,"e2ee");g(this,lc,void 0);g(this,uc,void 0);g(this,Qe,void 0);g(this,H,void 0);g(this,tl,void 0);g(this,at,void 0);g(this,Li,void 0);g(this,Vi,void 0);g(this,xi,void 0);g(this,hc,void 0);g(this,wt,null);g(this,vs,void 0);g(this,Xe,void 0);g(this,ut,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,Qe,r),f(this,Li,!1),f(this,H,new rD(t,r)),f(this,at,a(this,H).events),f(this,vs,new Set),f(this,Xe,new Map),f(this,Vi,!1),f(this,xi,new ku(t.getValue("logger"))),f(this,ut,new Ja(this.context,a(this,H).socketHandler.audioActivity.bind(a(this,H).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,hc,ah(async()=>{if(!a(this,Js,Zr).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,uc),a(this,lc),!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 a(this,Js,Zr).mediaJoined}set mediaJoined(t){a(this,Js,Zr).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,H).closeAllProducers(),a(this,H).closeAllConsumers(),a(this,Xe).clear(),a(this,vs).clear(),f(this,wt,null),t&&a(this,xi).stop(),a(this,H).stopAllTransports(),a(this,H).reset(),t&&f(this,xi,new ku)}async joinRoom(t,e,r=!1,i={}){a(this,Js,Zr).mediaJoinAttempted=!0,f(this,Li,!0);try{return await a(this,xi).push(()=>O(this,sl,Kf).call(this,t,e,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(t,e,r=!1,i={}){return a(this,wt)?a(this,wt):(f(this,wt,(async()=>{try{await O(this,pc,Vu).call(this,t,e,r,i)}catch(n){throw f(this,wt,null),n}})()),a(this,wt))}getConsumers(){return a(this,H).consumers}getProducers(){return a(this,H).producers}async leaveRoom(){a(this,H).stopAllTransports(),f(this,Vi,!1),a(this,Js,Zr).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,Qe).sendMessagePromise(a(this,at).leaveRoom,ww.toBinary(t)).then(r=>{var i;(i=pR.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(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,H).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,H).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,H).closeConsumers(e)}async _shareWebcam(t){var u,p,m,T;const e=Ee.WEBCAM,r=O(this,ot,vt).call(this,e);if(r){const E=await r;if(a(this,H).producers.has(E)){const P=a(this,H).producers.get(E);if(!P.closed)return await P.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=O(this,dl,tT).call(this,t),n=Ta(this.context,"disableSimulcast"),o=(p=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:p.simulcastConfig;n||o&&o.disable||!((T=(m=this.context)==null?void 0:m.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=KI(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Xe).delete(e)},l=a(this,H).createProducer(i,d);return O(this,Ui,Ka).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},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Xe).delete(Ee.SCREENSHARE_VIDEO),a(this,Xe).delete(Ee.SCREENSHARE_AUDIO)},o=a(this,H).createProducer(i,n);O(this,Ui,Ka).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=a(this,H).createProducer(d,l),O(this,Ui,Ka).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 mt("track undefined");const e=O(this,ot,vt).call(this,Ee.MIC);if(e){const o=await e;if(a(this,H).producers.has(o)){const c=a(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,ut)&&(a(this,ut).audioTrack=t,a(this,ut).producerId=o,a(this,ut).start());return}await a(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=O(this,cl,eT).call(this,t),i=()=>{a(this,Xe).delete(Ee.MIC)},n=a(this,H).createProducer(r,i);O(this,Ui,Ka).call(this,Ee.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,ut)&&(a(this,ut).audioTrack=o.track,a(this,ut).producerId=o.id,a(this,ut).start())})}catch(e){throw new R(e)}}async pauseMic(){var i;const t=await O(this,ot,vt).call(this,Ee.MIC),e=a(this,H).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=a(this,ut))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,Qe).sendMessage(a(this,at).toggleProducer,Oc.toBinary(r))}async pauseWebcam(){const t=await O(this,ot,vt).call(this,Ee.WEBCAM),e=a(this,H).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,Qe).sendMessage(a(this,at).toggleProducer,Oc.toBinary(r))}async resumeMic(){const t=await O(this,ot,vt).call(this,Ee.MIC),e=a(this,H).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};a(this,Qe).sendMessage(a(this,at).toggleProducer,Oc.toBinary(r))}async resumeWebcam(t=Ee.WEBCAM){const e=await O(this,ot,vt).call(this,t),r=a(this,H).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};a(this,Qe).sendMessage(a(this,at).toggleProducer,Oc.toBinary(i))}async disableWebcam(){const t=Ee.WEBCAM,e=await O(this,ot,vt).call(this,t);O(this,ol,Zf).call(this,t),e&&await a(this,H).closeProducer(e)}async disableMic(){var e;const t=await O(this,ot,vt).call(this,Ee.MIC);t&&await a(this,H).closeProducer(t),(e=a(this,ut))==null||e.stop(),a(this,Xe).delete(Ee.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await O(this,ot,vt).call(this,Ee.SCREENSHARE_VIDEO),e=await O(this,ot,vt).call(this,Ee.SCREENSHARE_AUDIO);t&&await a(this,H).closeProducer(t),e&&await a(this,H).closeProducer(e),a(this,vs).clear(),a(this,Xe).delete(Ee.SCREENSHARE_VIDEO),a(this,Xe).delete(Ee.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await O(this,ot,vt).call(this,Ee.WEBCAM);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await O(this,ot,vt).call(this,Ee.SCREENSHARE_VIDEO);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,H).socketHandler.kickPeer(e)}kickAll(){a(this,H).socketHandler.kickAll()}async muteAll(t){if(!await a(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,H).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 a(this,Qe).sendMessagePromise(a(this,at).globalPinPeer,$w.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,H).producers.get(t.producerId)&&a(this,vs).add(t.consumerPeerId),a(this,vs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,Qe).on(a(this,at).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=qR.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===Zs.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===Zs.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,Qe).on(a(this,at).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=Pp.fromBinary(t);if(c)return;const d=i===Zs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Pp.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&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:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(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})}}),a(this,Qe).on(a(this,at).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=au.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,vs).delete(e),a(this,H).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})}}),a(this,Qe).on(a(this,at).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=WR.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=a(this,H).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,H).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,H).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,Qe).on(a(this,at).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Li)&&!a(this,Vi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),a(this,hc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,H).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(a(this,H).producers.values()).find(n=>n.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})})})}}lc=new WeakMap,uc=new WeakMap,Qe=new WeakMap,H=new WeakMap,tl=new WeakMap,at=new WeakMap,Li=new WeakMap,Vi=new WeakMap,xi=new WeakMap,hc=new WeakMap,wt=new WeakMap,vs=new WeakMap,Xe=new WeakMap,ut=new WeakMap,Js=new WeakSet,Zr=function(){return this.context.getValue("connectionHandler")},sl=new WeakSet,Kf=async function(t,e,r,i){var o;f(this,uc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,Js,Zr).mediaState)!=null?o:{};(d==null?void 0:d.state)===ys.CONNECTED&&(c==null?void 0:c.state)===ys.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,H).closeAllProducersLocally(),a(this,Xe).clear(),a(this,vs).clear(),f(this,wt,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,wt)?await a(this,wt):await O(this,pc,Vu).call(this,t,e,r,i,n),O(this,il,Yf).call(this,e);const{joined:c,error:d}=await O(this,rl,zf).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{f(this,wt,null)}},rl=new WeakSet,zf=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,H).socketHandler.notifySelfJoinComplete();return f(this,lc,t.roomUuid),f(this,Vi,!0),f(this,Li,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},il=new WeakSet,Yf=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)},pc=new WeakSet,Vu=async function(t,e,r,i,n=!1){try{const o=O(this,nl,Qf).call(this);await O(this,al,Xf).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},nl=new WeakSet,Qf=function(){const t=j0("video/VP8");return f(this,tl,t),t},al=new WeakSet,Xf=async function(t,e,r,i){await bf(async(n,o)=>{if(!a(this,Qe).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,H).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})},ot=new WeakSet,vt=function(t){return a(this,Xe).get(t)},Ui=new WeakSet,Ka=function(t,e){return a(this,Xe).set(t,e)},ol=new WeakSet,Zf=function(t){return a(this,Xe).delete(t)},cl=new WeakSet,eT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},dl=new WeakSet,tT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};oe([y.trace("MediaNodeClient.reset")],se.prototype,"reset",1);oe([y.trace("MediaNodeClient.joinRoom")],se.prototype,"joinRoom",1);oe([y.trace("MediaNodeClient.leaveRoom")],se.prototype,"leaveRoom",1);oe([y.trace("MediaNodeClient.activatePeers")],se.prototype,"activatePeers",1);oe([y.trace("MediaNodeClient.createConsumers")],se.prototype,"createConsumers",1);oe([y.trace("MediaNodeClient.closeConsumers")],se.prototype,"closeConsumers",1);oe([y.trace("MediaNodeClient._shareWebcam")],se.prototype,"_shareWebcam",1);oe([y.trace("MediaNodeClient.shareWebcam")],se.prototype,"shareWebcam",1);oe([y.trace("MediaNodeClient.shareScreen")],se.prototype,"shareScreen",1);oe([y.trace("MediaNodeClient.shareMic")],se.prototype,"shareMic",1);oe([y.trace("MediaNodeClient.pauseMic")],se.prototype,"pauseMic",1);oe([y.trace("MediaNodeClient.pauseWebcam")],se.prototype,"pauseWebcam",1);oe([y.trace("MediaNodeClient.resumeMic")],se.prototype,"resumeMic",1);oe([y.trace("MediaNodeClient.resumeWebcam")],se.prototype,"resumeWebcam",1);oe([y.trace("MediaNodeClient.disableWebcam")],se.prototype,"disableWebcam",1);oe([y.trace("MediaNodeClient.disableMic")],se.prototype,"disableMic",1);oe([y.trace("MediaNodeClient.disableScreenShare")],se.prototype,"disableScreenShare",1);oe([y.trace("MediaNodeClient.muteSelf")],se.prototype,"muteSelf",1);oe([y.trace("MediaNodeClient.resetVideoProducers")],se.prototype,"resetVideoProducers",1);oe([y.trace("MediaNodeClient.changeDisplayName")],se.prototype,"changeDisplayName",1);oe([y.trace("MediaNodeClient.kickPeer")],se.prototype,"kick",1);oe([y.trace("MediaNodeClient.kickAllPeers")],se.prototype,"kickAll",1);oe([y.trace("MediaNodeClient.muteAll")],se.prototype,"muteAll",1);oe([y.trace("MediaNodeClient.muteAllVideo")],se.prototype,"muteAllVideo",1);oe([y.trace("MediaNodeClient.disableAudio")],se.prototype,"disableAudio",1);oe([y.trace("MediaNodeClient.disableVideo")],se.prototype,"disableVideo",1);oe([y.trace("MediaNodeClient.pinPeer")],se.prototype,"pinPeer",1);oe([y.trace("MediaNodeClient.validateScreenShare")],se.prototype,"validateScreenShare",1);function sT(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 dD(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,Xi=(s,t,e,r)=>{for(var i=r>1?void 0:r?uD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lD(t,e,i),i},ua,ns,Q,ht,Ot,mg;const rT=(mg=class{constructor(s,t,e,r){g(this,ht);h(this,"self");h(this,"authToken");g(this,ua,void 0);h(this,"viewType");g(this,ns,void 0);g(this,Q,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,Q,s),this.viewType=r,this.authToken=n,f(this,ua,i),f(this,ns,e),this.setupEvents()}get peerId(){return a(this,Q).getValue("peerId")}get telemetry(){return a(this,Q).getValue("telemetry")}get logger(){return a(this,Q).getValue("logger")}get mediaJoined(){return a(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=gt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ge.__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(m=>m.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(m=>m.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(m=>m.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 n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:TC(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(m){l.error("Callstats:: initialization failed",{error:m})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new rT(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===q.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,ht,Ot).shareMic(s),this.self.audioEnabled||a(this,ht,Ot).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===q.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,ht,Ot).shareWebcam(t),this.self.videoEnabled||a(this,ht,Ot).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===q.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,ht,Ot))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),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){a(this,Q).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,ht,Ot).reset({resetTransportQueue:!0}))}setupEvents(){a(this,Q).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Q).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,ua).updateURL(t),a(this,Q).getValue("telemetry").resetPeerId(t),gt().setHeader("tracing-id",t),Hr.remapContext(t,a(this,Q)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Q).getValue("peerSessionStore").on(w.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ns).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ns).on(jc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Q).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),a(this,ns).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ns).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ns).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Q).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Q).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,Q).getValue("callstats").audioOff())}),a(this,Q).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,Q).getValue("callstats").videoOff())}),a(this,Q).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Q).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await a(this,ns).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,ns).socket.flush();const e=uh(t.stageType);if(a(this,Q).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new R("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),a(this,Q).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof fr&&t.message==="ice connection failed"?new R("A firewall or network restriction may be blocking the connection.","0014"):new R("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,Q).setValue("roomNodeClient",void 0),a(this,Q).notify("stageStatus"),(t=a(this,Q).getValue("roomSocketHandler"))==null||t.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,Q).getAllValues();try{if(e===Xs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}sT(a(this,Q),{socket:a(this,ua),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:p}=(o=await((n=a(this,ht,Ot))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw p!=null?p:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),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=a(this,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Xs.Webinar)&&a(this,ht,Ot)&&(a(this,ht,Ot).mediaJoined&&s!=="disconnected"&&await a(this,ht,Ot).leaveRoom(),!(s==="stageLeft"&&t===Xs.Livestream)&&(a(this,ht,Ot).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()}},ua=new WeakMap,ns=new WeakMap,Q=new WeakMap,ht=new WeakSet,Ot=function(){return a(this,Q).getValue("roomNodeClient")},mg);let Kr=rT;Xi([y.trace("SelfController.resetSelf")],Kr.prototype,"resetSelf",1);Xi([y.trace("SelfController.setupEvents")],Kr.prototype,"setupEvents",1);Xi([y.trace("SelfController.joinRoom")],Kr.prototype,"joinRoom",1);Xi([y.trace("SelfController.leaveRoom")],Kr.prototype,"leaveRoom",1);Xi([y.trace("SelfController.joinMediaRoom")],Kr.prototype,"joinMediaRoom",1);Xi([y.trace("SelfController.leaveMediaRoom")],Kr.prototype,"leaveMediaRoom",1);Xi([y.trace("SelfController.init")],Kr,"init",1);var gc;class hD{constructor(t){g(this,gc,void 0);f(this,gc,t)}on(t,e){let r;t===x.roomPeerCount?r=wp.fromBinary.bind(wp):r=Op.fromBinary.bind(Op),a(this,gc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const n=r(i);e(n)})}}gc=new WeakMap;var mc,fc;class pD{constructor(t,e){g(this,mc,void 0);g(this,fc,void 0);f(this,mc,e),f(this,fc,t)}get logger(){return a(this,fc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=$l.fromBinary.bind($l),i=$l.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,mc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}mc=new WeakMap,fc=new WeakMap;var gD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,Ch=(s,t,e,r)=>{for(var i=r>1?void 0:r?mD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gD(t,e,i),i},Ks,ha;class bl{constructor(t,e){g(this,Ks,void 0);g(this,ha,void 0);f(this,Ks,e),f(this,ha,t)}get logger(){return a(this,ha).getValue("logger")}get telemetry(){return a(this,ha).getValue("telemetry")}getPolls(){return a(this,Ks).sendMessagePromise(Ms.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Ks).sendMessage(Ms.createPoll,EA.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Ks).sendMessage(Ms.votePoll,_A.toBinary(r))}on(t,e){let r,i;switch(t){case Ms.updatePoll:case Ms.createPoll:case Ms.votePoll:{r=Gl.fromBinary.bind(Gl),i=Gl.create();break}}a(this,Ks).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Ks).removeListeners(t)}}Ks=new WeakMap,ha=new WeakMap;Ch([y.trace("PollSocketHandler.getPolls")],bl.prototype,"getPolls",1);Ch([y.trace("PollSocketHandler.createPoll")],bl.prototype,"createPoll",1);Ch([y.trace("PollSocketHandler.votePoll")],bl.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,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fD(t,e,i),i},Rt;class iT{constructor(t,e){h(this,"socket");g(this,Rt,void 0);f(this,Rt,t),this.socket=e,this.handleSocketEvents(),a(this,Rt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Rt).getValue("telemetry")}get logger(){return a(this,Rt).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(x.joinRoom,Eb.toBinary(e));try{const{peer:n}=en.fromBinary((await r).payload);a(this,Rt).getValue("connectionHandler").socketJoined=!0,a(this,Rt).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Rt).getValue("peerSessionStore").emit(w.ROOM_STATE,d),a(this,Rt).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return nk.fromBinary((await this.socket.sendMessagePromise(x.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(x.getRoomPeersInfo,ub.toBinary(n));i=Bl.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=Bl.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(x.getRoomPeersInfo);t=Bl.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(x.getPeerInfo,jm.toBinary({peerId:t}));e=en.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Rp.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=Rp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Ap.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=Ap.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(x.broadcastMessage,$a.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(x.broadcastToEntity,$a.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(x.broadcastToEntity,$a.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(x.leaveRoom,_b.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,Wm.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,Hm.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,uk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,pk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(jc.updateUserPreset,Fk.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=$a.fromBinary(t);a(this,Rt).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(x.broadcastToEntity,({payload:t})=>{try{const e=$a.fromBinary(t);a(this,Rt).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 x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=en.fromBinary.bind(en),i=en.create();break}case x.getWaitingRoomRequests:{r=(n,o)=>n?Mp.fromBinary(n,o):{requests:[]},i=Mp.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=Vp.fromBinary.bind(Vp);break}case jc.updateUserPreset:{r=Ip.fromBinary.bind(Ip);break}case os.peerJoinedBroadcast:case mr.peerJoinedBroadcast:{r=yp.fromBinary.bind(yp);break}case os.selfJoinComplete:case mr.selfJoinComplete:{r=nu.fromBinary.bind(nu);break}case os.globalPeerPinBroadcast:case mr.globalPeerPinBroadcast:{r=_p.fromBinary.bind(_p);break}case os.selectedPeer:case mr.selectedPeer:{r=iu.fromBinary.bind(iu);break}case os.selectedPeerDiff:case mr.selectedPeerDiff:{r=vp.fromBinary.bind(vp);break}case os.leaveRoom:case mr.leaveRoom:{r=au.fromBinary.bind(au);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}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(jc.getUserPresets,Lk.toBinary(e)),i=$k.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).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}}}Rt=new WeakMap;SD([y.trace("RoomSocketHandler.joinRoom")],iT.prototype,"joinRoom",1);var pt;class vD{constructor(t){g(this,pt,void 0);f(this,pt,t)}async getStageRequests(){const{payload:t}=await a(this,pt).sendMessagePromise(x.getStageRequests);return t?jl.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,pt).sendMessage(x.requestStageAccess)}cancelRequestAccess(){a(this,pt).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,pt).sendMessage(x.grantStageAccess,uA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,pt).sendMessage(x.denyStageAccess,pA.toBinary(e))}joinStage(){return a(this,pt).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,pt).sendMessagePromise(x.leaveStage,Lp.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,pt).sendMessagePromise(x.leaveStage,Lp.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=Np.fromBinary.bind(Np);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=jl.fromBinary.bind(jl);break}case x.peerStageStatusUpdate:{r=Cp.fromBinary.bind(Cp);break}}a(this,pt).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,pt).sendMessagePromise(x.getPeerInfo,jm.toBinary({peerId:t}));return en.fromBinary(e.payload)}}pt=new WeakMap;var Lr,pa;class yD{constructor(t,e){g(this,Lr,void 0);g(this,pa,void 0);f(this,Lr,e),f(this,pa,t)}get logger(){return a(this,pa).getValue("logger")}get peerId(){return a(this,pa).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,Lr).sendMessage(ks.storeInsertKeys,GM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Lr).sendMessage(ks.storeGetKeys,JM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Lr).sendMessage(ks.storeDeleteKeys,zM.toBinary(n),i)}on(t,e){const r=Dp.fromBinary.bind(Dp);a(this,Lr).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Lr=new WeakMap,pa=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,_D=(s,t,e)=>(PD(s,typeof t!="symbol"?t+"":t,e),e),wh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>(wh(s,t,"read from private field"),e?e.call(s):t.get(s)),re=(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)},Z=(s,t,e,r)=>(wh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ee=(s,t,e)=>(wh(s,t,"access private method"),e),hd={},CD={get exports(){return hd},set exports(s){hd=s}},gn=typeof Reflect=="object"?Reflect:null,Wp=gn&&typeof gn.apply=="function"?gn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Qc;gn&&typeof gn.ownKeys=="function"?Qc=gn.ownKeys:Object.getOwnPropertySymbols?Qc=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Qc=function(s){return Object.getOwnPropertyNames(s)};function wD(s){console&&console.warn&&console.warn(s)}var nT=Number.isNaN||function(s){return s!==s};function ae(){ae.init.call(this)}CD.exports=ae;hd.once=MD;ae.EventEmitter=ae;ae.prototype._events=void 0;ae.prototype._eventsCount=0;ae.prototype._maxListeners=void 0;var Jp=10;function kl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ae,"defaultMaxListeners",{enumerable:!0,get:function(){return Jp},set:function(s){if(typeof s!="number"||s<0||nT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Jp=s}});ae.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};ae.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||nT(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 aT(s){return s._maxListeners===void 0?ae.defaultMaxListeners:s._maxListeners}ae.prototype.getMaxListeners=function(){return aT(this)};ae.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 n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")Wp(c,this,t);else for(var d=c.length,l=uT(c,d),e=0;e<d;++e)Wp(l[e],this,t);return!0};function oT(s,t,e,r){var i,n,o;if(kl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=aT(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}ae.prototype.addListener=function(s,t){return oT(this,s,t,!1)};ae.prototype.on=ae.prototype.addListener;ae.prototype.prependListener=function(s,t){return oT(this,s,t,!0)};function RD(){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 cT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=RD.bind(r);return i.listener=e,r.wrapFn=i,i}ae.prototype.once=function(s,t){return kl(t),this.on(s,cT(this,s,t)),this};ae.prototype.prependOnceListener=function(s,t){return kl(t),this.prependListener(s,cT(this,s,t)),this};ae.prototype.removeListener=function(s,t){var e,r,i,n,o;if(kl(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,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():bD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ae.prototype.off=ae.prototype.removeListener;ae.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),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);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 dT(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):uT(i,i.length)}ae.prototype.listeners=function(s){return dT(this,s,!0)};ae.prototype.rawListeners=function(s){return dT(this,s,!1)};ae.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):lT.call(s,t)};ae.prototype.listenerCount=lT;function lT(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}ae.prototype.eventNames=function(){return this._eventsCount>0?Qc(this._events):[]};function uT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function bD(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,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}hT(s,t,n,{once:!0}),t!=="error"&&AD(s,i,{once:!0})})}function AD(s,t,e){typeof s.on=="function"&&hT(s,"error",t,e)}function hT(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(n){r.once&&s.removeEventListener(t,i),e(n)});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 Kp=new ID;class pT{static encode(t){return Kp.toBinary(t)}static decode(t){return Kp.fromBinary(new Uint8Array(t))}}function DD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var pr;class OD{constructor(t={}){_D(this,"opts"),re(this,pr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},Z(this,pr,0)}async wait(){Z(this,pr,A(this,pr)+1);const t=DD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,pr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,pr)}reset(){Z(this,pr,0)}}pr=new WeakMap;const dr={debug:0,info:1,warn:2,error:3};var ei,ti;class ND{constructor(t){re(this,ei,void 0),re(this,ti,void 0),Z(this,ei,console),Z(this,ti,t)}debug(...t){dr[A(this,ti)]>dr.debug||A(this,ei).debug("[Sockrates]:",...t)}info(...t){dr[A(this,ti)]>dr.info||A(this,ei).info("[Sockrates]:",...t)}warn(...t){dr[A(this,ti)]>dr.warn||A(this,ei).warn("[Sockrates]:",...t)}error(...t){dr[A(this,ti)]>dr.error||A(this,ei).error("[Sockrates]:",...t)}}ei=new WeakMap,ti=new WeakMap;var gT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(gT||{});const zp="2",Yp="3";var we,nn,ie,Se,gr,je,Ys,$r,as,an,on,bs,xu,mT,za,Xc,Uu,fT,Zc,zl,pd,$u,Bu,TT,eo,ed,mn,to,gd,Hu,fn,so,Fu,ST,ro,td,io,md;class LD{constructor(t,e){var E,P,k,C,I,V,L,B,$,z,De,Tt;re(this,xu),re(this,za),re(this,Uu),re(this,Zc),re(this,pd),re(this,Bu),re(this,eo),re(this,mn),re(this,gd),re(this,fn),re(this,Fu),re(this,ro),re(this,io),re(this,we,void 0),re(this,nn,void 0),re(this,ie,void 0),re(this,Se,void 0),re(this,gr,void 0),re(this,je,void 0),re(this,Ys,void 0),re(this,$r,void 0),re(this,as,void 0),re(this,an,void 0),re(this,on,void 0),re(this,bs,void 0);var r,i,n,o,c,d,l,u,p,m,T;Z(this,nn,t),Z(this,gr,[]),Z(this,je,new hd),Z(this,Ys,!0),Z(this,as,!1),Z(this,ie,e!=null?e:{}),(E=(r=A(this,ie)).autoReconnect)!=null||(r.autoReconnect=!0),(P=(i=A(this,ie)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(k=(n=A(this,ie)).pingTimeout)!=null||(n.pingTimeout=3e4),(C=(o=A(this,ie)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(I=(c=A(this,ie)).debug)!=null||(c.debug=!0),(V=(d=A(this,ie)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(L=(l=A(this,ie)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=A(this,ie)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),($=(p=A(this,ie)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),(z=(m=A(this,ie)).clientInitiatedPings)!=null||(m.clientInitiatedPings=!1),(De=(T=A(this,ie)).clientInitiatedPingInterval)!=null||(T.clientInitiatedPingInterval=3e4),Z(this,$r,{code:void 0,reason:void 0}),Z(this,Se,(Tt=A(this,ie).logger)!=null?Tt:new ND(A(this,ie).debug?"debug":"info")),Z(this,bs,new OD)}get readyState(){var t;return(t=A(this,we))==null?void 0:t.readyState}get url(){return A(this,nn)}updateURL(t){Z(this,nn,t),ee(this,Bu,TT).call(this)}get config(){return A(this,ie)}get sendQueue(){return A(this,gr)}flush(){if(!A(this,ie).queueOnDisconnect)return!1;const t=[];return A(this,gr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),Z(this,gr,t),A(this,gr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,Se).debug("Websocket was already connecting or connected.");return}if(A(this,Ys)!==!1)return new Promise((e,r)=>{ee(this,fn,so).call(this),ee(this,io,md).call(this);try{Z(this,we,new WebSocket(ee(this,xu,mT).call(this,A(this,nn)))),A(this,we).binaryType="arraybuffer",A(this,Se).debug("Connecting");const i=setTimeout(()=>{A(this,Se).debug("Connection timeout. Closing socket"),Z(this,Ys,!0),ee(this,io,md).call(this),A(this,we).close(3001,"Connection Timeout"),A(this,ie).autoReconnect&&!A(this,as)&&(A(this,je).emit("reconnecting"),ee(this,eo,ed).call(this)),r(new Error("Connection timed out!"))},A(this,ie).connectionTimeout);A(this,we).onopen=()=>{A(this,Se).debug(`Ready State: ${gT[A(this,we).readyState]}`),i&&clearTimeout(i),ee(this,gd,Hu).call(this),ee(this,Fu,ST).call(this),Z(this,$r,{code:void 0,reason:void 0}),A(this,je).emit("connected"),A(this,ie).flushOnReconnect&&this.flush(),e()},A(this,we).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),A(this,Se).debug("Socket closed. Close event:",{event:n}),A(this,Se).debug(`Connection closed code: ${o}`),A(this,Se).debug(`Connection closed reason: ${c}`),A(this,as)||ee(this,pd,$u).call(this,o,c)}catch(o){ee(this,za,Xc).call(this,o)}},A(this,we).onerror=n=>{ee(this,za,Xc).call(this,n)},A(this,we).onmessage=n=>ee(this,Uu,fT).call(this,n)}catch(i){ee(this,za,Xc).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(A(this,ie).queueOnDisconnect&&(!A(this,we)||A(this,we).readyState!==1))return A(this,Se).debug("Queuing message since socket is not connected!",n),A(this,gr).push(n),!1;const o=pT.encode(n);return ee(this,mn,to).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ee(this,mn,to).call(this,t)}receive(t,e){return A(this,je).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")){A(this,je).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,je).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,je).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,je).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){Z(this,Ys,!1),ee(this,fn,so).call(this),ee(this,ro,td).call(this),this.removeAllListeners(),Z(this,$r,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,we).close(1e3,"Sockrates disconnect method called.")}}we=new WeakMap,nn=new WeakMap,ie=new WeakMap,Se=new WeakMap,gr=new WeakMap,je=new WeakMap,Ys=new WeakMap,$r=new WeakMap,as=new WeakMap,an=new WeakMap,on=new WeakMap,bs=new WeakMap,xu=new WeakSet,mT=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,Xc=function(s,t){A(this,Se).error("Error:",{error:s}),A(this,je).emit("errored",{error:s}),t==null||t(s)},Uu=new WeakSet,fT=function(s){if(ee(this,gd,Hu).call(this),s.data===zp){A(this,Se).debug("Received ping from server"),ee(this,mn,to).call(this,Yp);return}if(s.data===Yp){A(this,Se).debug("Received pong from server");return}const t=pT.decode(s.data),{id:e,payload:r}=t;A(this,Se).debug("Received message",{event:t.event,messageID:e}),A(this,je).emit(t.event.toString(),{id:e,payload:r})},Zc=new WeakSet,zl=function(){return A(this,we).readyState===1},pd=new WeakSet,$u=function(s,t){Z(this,$r,{reason:t,code:s}),A(this,je).emit("disconnected",{code:s,reason:t})},Bu=new WeakSet,TT=function(){const{reason:s,code:t}=A(this,$r);t&&t!==1e3&&A(this,Ys)&&A(this,ie).autoReconnect&&!A(this,as)&&(A(this,Se).debug(`Triggering reconnection due to ${s}.`),A(this,je).emit("reconnecting"),ee(this,eo,ed).call(this))},eo=new WeakSet,ed=async function(s=!0){if(s&&A(this,as)){A(this,Se).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,as)||A(this,bs).reset(),A(this,ie).maxReconnectionAttempts!==null&&A(this,bs).getAttempts()>=A(this,ie).maxReconnectionAttempts){A(this,je).emit("failed"),Z(this,as,!1);return}Z(this,as,!0),ee(this,io,md).call(this),ee(this,fn,so).call(this);try{if(await A(this,bs).wait(),A(this,Ys)===!1)return;if(A(this,Se).debug(`Reconnection attempt ${A(this,bs).getAttempts()}`),A(this,je).emit("reconnectAttempt",{attempt:A(this,bs).getAttempts()}),await this.connect(),!ee(this,Zc,zl).call(this))throw Error("Reconnect Failed");Z(this,as,!1),Z(this,$r,{code:void 0,reason:void 0}),A(this,je).emit("reconnected")}catch(t){A(this,Se).debug("Failed to reconnect."),A(this,je).emit("reconnectFailure",{attempt:A(this,bs).getAttempts()}),ee(this,eo,ed).call(this,!1)}},mn=new WeakSet,to=function(s){try{return A(this,we).send(s),!0}catch(t){return A(this,Se).error(t.message),!1}},gd=new WeakSet,Hu=function(){this.config.disconnectOnPingTimeout&&(A(this,Se).debug("Resetting ping timeout"),ee(this,fn,so).call(this),Z(this,an,setTimeout(()=>{var s;A(this,Se).debug("Disconnecting the socket due to ping timeout"),Z(this,Ys,!0);const t=3002,e="Ping timeout";(s=A(this,we))==null||s.close(t,e),ee(this,pd,$u).call(this,t,e)},A(this,ie).pingTimeout)))},fn=new WeakSet,so=function(){A(this,an)&&(clearTimeout(A(this,an)),Z(this,an,void 0))},Fu=new WeakSet,ST=function(){ee(this,ro,td).call(this),A(this,ie).clientInitiatedPings&&Z(this,on,setInterval(()=>{ee(this,Zc,zl).call(this)&&(A(this,Se).debug("Sending client-initiated ping"),ee(this,mn,to).call(this,zp))},A(this,ie).clientInitiatedPingInterval))},ro=new WeakSet,td=function(){A(this,on)&&(clearInterval(A(this,on)),Z(this,on,void 0))},io=new WeakSet,md=function(){ee(this,ro,td).call(this),A(this,we)&&(A(this,we).onopen=void 0,A(this,we).onerror=void 0,A(this,we).onmessage=void 0,A(this,we).onclose=void 0)};var VD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,Ml=(s,t,e,r)=>{for(var i=r>1?void 0:r?xD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&VD(t,e,i),i};const Qp=65535,UD=3e3;var Vr,fe,Te,be,qt,Fe,Tc,qu,Sc,ju,fg;const vT=(fg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Te);g(this,Tc);g(this,Sc);g(this,Vr,void 0);g(this,fe,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");g(this,qt,void 0);g(this,Fe,void 0);if(!t||!e||!r)throw new R("peerId, meetingId, or authToken can not be empty","0404");f(this,qt,void 0),f(this,Fe,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Vr,O(this,Tc,qu).call(this,t));const n=i.includes("PING");f(this,fe,new LD(a(this,Vr),{autoReconnect:!0,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,maxReconnectionAttempts:50,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Te,be).socketJoinAttempted}set joinAttempted(s){a(this,Te,be).socketJoinAttempted=s}get telemetry(){return a(this,Fe).getValue("telemetry")}get logger(){return a(this,Fe).getValue("logger")}get peerId(){return a(this,Fe).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,Vr,O(this,Tc,qu).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,fe).updateURL(a(this,Vr))}static getSocketEdgeDomain(s){return pn({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,Vr)}async connect(){a(this,Te,be).socketJoinAttempted=!0,await a(this,fe).connect(),a(this,Te,be).socketJoinAttempted=!0,a(this,Te,be).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Te,be).socketJoinAttempted=!1,a(this,fe).disconnect(),a(this,Te,be).socketJoinAttempted=!0,a(this,Te,be).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,fe).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,Fe).getValue("telemetry").injectContext(r),a(this,fe).send(s,e!=null?e:O(this,Sc,ju).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 n=i!=null?i:s;return new Promise((o,c)=>{const d=(E,P)=>{a(this,fe).removeListener(n,E),a(this,fe).removeListener(Qp,P),a(this,fe).removeListener(mr.errorResponse,P),a(this,fe).removeListener(os.errorResponse,P)},l=r!=null?r:O(this,Sc,ju).call(this),u={};a(this,Fe).getValue("telemetry").injectContext(u);const m=({id:E,payload:P})=>{if(l===E){let k;try{const C=rR.fromBinary(P);k=new Error(C.errorMessage)}catch(C){k=new Error("failed to parse error message",{cause:C});try{const I=ib.fromBinary(P);k=new Error(I.message)}catch(I){k=new Error("failed to parse error message",{cause:I})}}c(k),d(T,m)}},T=({id:E,payload:P})=>{l===E&&(o({id:E,payload:P}),d(T,m))};a(this,fe).on(n,T),a(this,fe).on(Qp,m),a(this,fe).on(mr.errorResponse,m),a(this,fe).on(os.errorResponse,m),setTimeout(()=>{d(T,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,fe).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,fe).on(s,t)}onStateEvent(s,t){a(this,fe).on(s,t)}removeListener(s,t){a(this,fe).removeListener(s,t)}removeListeners(s){a(this,fe).removeListeners(s)}flush(){return a(this,fe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,qt)&&(clearTimeout(a(this,qt)),f(this,qt,void 0)),a(this,Te,be).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=a(this,Te,be).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==ys.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==ys.CONNECTED?a(this,Fe).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Te,be).joinAttempted}):f(this,qt,setTimeout(()=>{a(this,Fe).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Te,be).joinAttempted}),f(this,qt,void 0)},UD)),a(this,Te,be).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Te,be).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Te,be).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Te,be).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Te,be).mediaJoinAttempted}}),a(this,qt)&&(clearTimeout(a(this,qt)),f(this,qt,void 0)),a(this,Fe).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Te,be).mediaJoinAttempted}),a(this,Te,be).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,Fe).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED),a(this,Te,be).updateSocketConnectionState("failed")})}},Vr=new WeakMap,fe=new WeakMap,Te=new WeakSet,be=function(){return a(this,Fe).getValue("connectionHandler")},qt=new WeakMap,Fe=new WeakMap,Tc=new WeakSet,qu=function(s){const t=a(this,Fe).getValue("socketBaseURI")||a(this,Fe).getValue("baseURI");let e=vT.getSocketEdgeDomain(t);typeof Ta(a(this,Fe),"socket_server_base")=="string"&&(e=Ta(a(this,Fe),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>cd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Sc=new WeakSet,ju=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},fg);let Mc=vT;Ml([y.trace("SocketService.connect")],Mc.prototype,"connect",1);Ml([y.trace("SocketService.disconnect")],Mc.prototype,"disconnect",1);Ml([y.trace("SocketService.sendMessagePromise")],Mc.prototype,"sendMessagePromise",1);Ml([y.trace("SocketService.sendMessagePromiseWithTimeout")],Mc.prototype,"sendMessagePromiseWithTimeout",1);class $D{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=Ib.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:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=rk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Gm.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return kp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Jb.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,Lb.toBinary({payloads:t}));return kp.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(x.deleteConnectedRooms,Gb.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,Zb.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 BD=Object.defineProperty,HD=Object.getOwnPropertyDescriptor,FD=(s,t,e,r)=>{for(var i=r>1?void 0:r?HD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BD(t,e,i),i},bt;class yT extends At{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);g(this,bt,void 0);f(this,bt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,bt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,bt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,bt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,bt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,bt).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.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,bt).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.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.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 a(this,bt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,bt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.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}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,bt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.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}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.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=>n.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})}}bt=new WeakMap;FD([It({maxInvocations:60,period:60})],yT.prototype,"getConnectedMeetings",1);var qD=Object.defineProperty,jD=Object.getOwnPropertyDescriptor,Rh=(s,t,e,r)=>{for(var i=r>1?void 0:r?jD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&qD(t,e,i),i},le,Tg;const ET=(Tg=class{constructor(s){h(this,"connectedMeetings");g(this,le,void 0);f(this,le,s),this.connectedMeetings=new yT(s)}get telemetry(){return a(this,le).getValue("telemetry")}get logger(){return a(this,le).getValue("logger")}static init(s){const t=new ET(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,le).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,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,le).getValue("self").videoEnabled,audio:a(this,le).getValue("self").audioEnabled};try{a(this,le).getValue("self").cleanupEvents(),await a(this,le).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,le).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await _T.init({...a(this,le).getValue("options"),cachedUserDetails:null,defaults:{...a(this,le).getValue("options").defaults,...e,mediaHandler:a(this,le).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}=a(this,le).getValue("self");r.self.setName(a(this,le).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=a(this,le).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 a(this,le).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,le).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=a(this,le).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})}},le=new WeakMap,Tg);let Al=ET;Rh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Al.prototype,"getConnectedMeetings",1);Rh([y.trace("ConnectedMeetingsController.setupEvents")],Al.prototype,"setupEvents",1);Rh([y.trace("ConnectedMeetingsController.switchMeeting")],Al.prototype,"switchMeeting",1);var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,bh=(s,t,e,r)=>{for(var i=r>1?void 0:r?WD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GD(t,e,i),i};const Ya=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 V,L,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(dD(s),ge.isSupported()===!1)throw new R("Browser not supported","0010",c,!0);const d=XA(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new NI(s);s.setValue("connectionHandler",l);let u="",p="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=((V=m.meeting)==null?void 0:V.title)||"",p=((L=m.socket)==null?void 0:L.baseUri)||s.getValue("baseURI"),s.setValue("presetName",m.preset.name),s.setValue("socketBaseURI",p),c.info(`Socket Base URI ${p} is being used`)}catch($){throw c.error("Failed to get user details",{error:$}),$ instanceof uu?$.status===401?new R("Unauthorized. The auth token may be invalid or expired. (401)","0004"):$.status===403?new R("Access denied. Insufficient permissions to join the meeting. (403)","0004"):$.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new R("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")):$.status>=500?new R(`The server encountered an error. Try again. (${$.status})`,"0001"):$.isHttpError?new R(`Request rejected by the server. (${$.status})`,"0001"):$.isTimeout?new R("Connection timed out. Check the network and try again.","0001"):new R("Unable to connect to the server. Check the internet connection.","0001"):new R(($==null?void 0:$.message)||"Failed to initialize.","0001")}const T=Ya.createSocketService(s),E=T.connect();try{await E}catch($){c.error("[Controller]: Failed to connect to socket server:",{error:$})}const P=Pu.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",P);const k=Ru.init(s,P.viewType,m.preset.permissions),C=Ya.setupControllers(T,s,m,u,P,k);PI(P)&&((B=Ya.createRoomNodeClient(s,T).initializeConnection(m.participant.name,i,!1,k))==null||B.catch(z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:z})}));const{controllers:I}=await C;return UC(),new Ya(e,I,s)}static async setupControllers(s,t,e,r,i,n){var ve,N,b;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:p}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(ve=p.enableHighBitrate)!=null?ve:!1,enableStereo:(N=p.enableStereo)!=null?N:!1}},...d}),t.setValue("maxPreferredStreams",ge.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let m,T,E,P,k,C,I,V,L;const B=new pD(t,s),$=new $D(s);t.setValue("connectedMeetingsSocketHandler",$);const z=new bl(t,s),De=new nr(t,s),Tt=new vD(s),Kt=new iT(t,s),zr=new yD(t,s),M=new hD(s),v=await Kr.init(t,Kt,c,n,i);t.setValue("selfController",v);const _=await of.init(t,v.self,Kt,B,r);o.participant&&(V=new cr(t,v.self,Kt)),(b=o.e2ee)!=null&&b.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(T=await Za.init(t,De,v.self,V.participants)),o.internals&&(k=await gh.init(t)),o.livestream&&i.viewType===Xs.Livestream&&(I=new Sf(t,v.self,M)),o.poll&&(m=await sf.init(t,v.self,z)),o.recording&&(C=new pf(t,v.self,Kt)),o.stage&&(E=new cf(t,Tt,Kt,v.self,V.participants));const U=new R0(t,zr);if(o.plugin){if(!V)throw new R("The plugin module cannot be initialized without the `participant` module","0102");const Re=d.plugins||[];P=await hf.init(t,Re,v.self,U)}if(o.connectedMeetings&&(L=await Al.init(t)),o.pip){const Re=await ru._init(t,v.self);t.setValue("pip",Re)}return{theme:i,permissions:n,controllers:{storesManager:U,pollController:m,selfController:v,metaController:_,chatController:T,stageController:E,pluginController:P,recordingController:C,internalsController:k,livestreamController:I,participantController:V,connectedMeetingsController:L}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return sT(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 Mc(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Il=Ya;bh([y.trace("Controller.init")],Il,"init",1);bh([y.trace("Controller.createRoomNodeClient")],Il,"createRoomNodeClient",1);bh([y.trace("Controller.createSocketService")],Il,"createSocketService",1);class JD{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 Xp=new JD;function KD(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 n=ri.baseURI.prod;t&&(n=t);const o=`https://${pn({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new R("Invalid auth token","0004")}}var xr,$i,Bi,vc,ll,PT;class zD{constructor(){g(this,ll);g(this,xr,new Audio);g(this,$i,new MediaStream);g(this,Bi,new Map);g(this,vc,void 0);a(this,xr).srcObject=a(this,$i),a(this,xr).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Bi).has(e.id)||(a(this,$i).addTrack(e),a(this,Bi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,xr).setSinkId(t)}removeTrack(t){const e=a(this,Bi).get(t);e&&(a(this,$i).removeTrack(e),a(this,Bi).delete(t))}async play(){return a(this,xr).srcObject=a(this,$i),a(this,xr).play().catch(t=>{O(this,ll,PT).call(this,t)})}onError(t){f(this,vc,t)}}xr=new WeakMap,$i=new WeakMap,Bi=new WeakMap,vc=new WeakMap,ll=new WeakSet,PT=function(t){var e;(e=a(this,vc))==null||e.call(this,t)};var Hi;class YD extends zD{constructor(){super();g(this,Hi,void 0);f(this,Hi,new Map)}addParticipantTrack(e,r){a(this,Hi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,Hi).get(e);r&&this.removeTrack(r),a(this,Hi).delete(e)}}Hi=new WeakMap;var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,Dl=(s,t,e,r)=>{for(var i=r>1?void 0:r?XD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QD(t,e,i),i},Ie,Fi,Sg;let jr=(Sg=class{constructor(t,e){g(this,Ie,void 0);g(this,Fi,void 0);f(this,Fi,t),f(this,Ie,e)}get peerId(){return a(this,Fi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:qr.v4(),n=Hr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Rf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,T,E,P,k,C,I,V,L;ge.init();const e=(T=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?T:qr.v4(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=KD(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new R("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=jr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");AT(l),Xp.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(k=(P=t.modules)==null?void 0:P.tracing)!=null?k:!0,(I=(C=t==null?void 0:t.modules)==null?void 0:C.devTools)==null?void 0:I.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(V=t.authToken)==null?void 0:V.slice(0,10)}...
10
- ${(L=t.authToken)==null?void 0:L.slice(-10)}`}});const u=await Il.init(c),p=new jr(c,u);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const n=Hr.createContext(t,e),o={...mC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",fC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Es(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.2-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new YD),n}async join(){const{selfController:t}=a(this,Ie);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Xp.cleanup(),a(this,Fi).getValue("peerSessionStore").reset(),(r=a(this,Ie).pluginController)==null||r.cleanup();const{selfController:e}=a(this,Ie);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Ie).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Ie).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Ie).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Ie).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Ie).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Ie).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Ie).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Ie).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Ie).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Ie).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Ie).stageController)==null?void 0:t.stage}get stores(){return a(this,Ie).storesManager}get audio(){return a(this,Fi).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Ie).internalsController)==null?void 0:t.internals}},Ie=new WeakMap,Fi=new WeakMap,Sg);Dl([et("0002"),or.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],jr.prototype,"join",1);Dl([et("0003")],jr.prototype,"leave",1);Dl([et("0001"),or.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],jr,"init",1);jr=Dl([et("0000")],jr);const _T=jr;module.exports=_T;
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(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class zg extends et{constructor(e){super();h(this,"call");h(this,"timeOut");this.call=new er(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 tS=8,sS=1/1e3;class rS extends zg{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(er.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(n){}}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)*tS/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const n=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(n*sS)})}}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 Wu extends zg{constructor(e,r=er.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 iS extends Wu{constructor(t){super(t,er.isHost)}}class nS extends Wu{constructor(t){super(t,er.isRelay)}}class aS extends Wu{constructor(t){super(t,er.isReflexive)}}class oS{constructor(){h(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,n,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,(n=this.ipInformation)!=null&&n.ip&&(this.ipInformation.ip=Br(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=Br(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 Yg=new oS,Oh=[{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 Nh(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Qg{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 Xg extends et{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 et}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 n=((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&&n.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&&n.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 n=((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&&n.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&&n.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 n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.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&&n.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 n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.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&&n.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 n=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=n,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(),n=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 n}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=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 n}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 n=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return n&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var P,R,k,I,O,x,B,$,z,he,Oe,Kt,zr;const c=e,d=new Qg,l=r.length?new Set(r):void 0,u=[],p=[],f=[],S=new Map,y=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:_}=M,U=M,fe={nominated:v!=null?v:_,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(fe),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=fe);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 _={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=_,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,_)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,_)}}break}case"remote-inbound-rtp":{const v=M,_={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,_);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(M.id))break;const v=M,_=n||this.outboundProducerMap.get(M.id),U=this.pausedProducerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const fe=this.overallProducersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const ye=this.callStatsInstance.producers.get(_);if(((P=ye==null?void 0:ye.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(_)||d.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const L={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 b=v,be={frameHeight:b.frameHeight,frameWidth:b.frameWidth,framesEncoded:b.framesEncoded,framesDropped:b.framesDropped,framesPerSecond:b.framesPerSecond,framesSent:b.framesSent,keyFramesEncoded:b.keyFramesEncoded,firCount:b.firCount,encoderImplementation:b.encoderImplementation,hugeFramesSent:b.hugeFramesSent,pliCount:b.pliCount,qpSum:b.qpSum,qualityLimitationDurations:b.qualityLimitationDurations,qualityLimitationReason:b.qualityLimitationReason,qualityLimitationResolutionChanges:b.qualityLimitationResolutionChanges,totalEncodeTime:b.targetBitrate,totalPacketSendDelay:b.totalPacketSendDelay,retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,scalabilityMode:b.scalabilityMode,powerEfficientEncoder:b.powerEfficientEncoder,...L};d.outboundVideoRtp.set(M.id,be),d.producerStreamMap.get(_).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(_,fe,be)}else if(v.mediaType==="audio"||v.kind==="audio"){const b=v,be={retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,...L};d.outboundAudioRtp.set(M.id,be),d.producerStreamMap.get(_).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(_,fe,be)}}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,_=n||this.inboundConsumerMap.get(M.id),U=this.pausedConsumerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const fe=this.overallConsumersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(_)||d.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const ye={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 L=v,b={frameHeight:L.frameHeight,frameWidth:L.frameWidth,framesDecoded:L.framesDecoded,framesDropped:L.framesDropped,framesPerSecond:L.framesPerSecond,framesReceived:L.framesReceived,keyFramesDecoded:L.keyFramesDecoded,firCount:L.firCount,decoderImplementation:L.decoderImplementation,pliCount:L.pliCount,totalProcessingDelay:L.totalProcessingDelay,qpSum:L.qpSum||0,totalAssemblyTime:L.totalAssemblyTime||0,totalDecodeTime:L.totalDecodeTime||0,totalFreezesDuration:L.totalFreezesDuration||0,totalInterFrameDelay:L.totalInterFrameDelay||0,totalPausesDuration:L.totalPausesDuration||0,totalSquaredInterFrameDelay:L.totalSquaredInterFrameDelay||0,freezeCount:L.freezeCount||0,pauseCount:L.pauseCount||0,powerEfficientDecoder:L.powerEfficientDecoder,...ye};b.score=Kg({frameWidth:b.frameWidth||0,framesDecoded:(b.framesDecoded||0)-(((R=this.videoConsumerToStatsMap.get(_))==null?void 0:R.framesDecoded)||0),framesPerSecond:b.framesPerSecond||0,packetsLost:(b.packetsLost||0)-(((k=this.videoConsumerToStatsMap.get(_))==null?void 0:k.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((I=this.videoConsumerToStatsMap.get(_))==null?void 0:I.packetsReceived)||0),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),y.set(_,{score:+(b.score*10).toFixed(),frameWidth:b.frameWidth||0,frameHeight:b.frameHeight||0,framesPerSecond:b.framesPerSecond||0,packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((O=this.videoConsumerToStatsMap.get(_))==null?void 0:O.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(_))==null?void 0:x.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(_))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,b),d.inboundVideoRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(_,fe,b)}else if(v.mediaType==="audio"||v.kind==="audio"){const L=v,b={audioLevel:L.audioLevel,concealedSamples:L.concealedSamples,concealmentEvents:L.concealmentEvents,totalAudioEnergy:L.totalAudioEnergy,totalSamplesDuration:L.totalSamplesDuration,totalSamplesReceived:L.totalSamplesReceived,fecPacketsDiscarded:L.fecPacketsDiscarded||0,fecPacketsReceived:L.fecPacketsReceived||0,insertedSamplesForDeceleration:L.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:L.removedSamplesForAcceleration||0,silentConcealedSamples:L.silentConcealedSamples||0,playoutId:L.playoutId,...ye};b.score=Jg({concealmentEvents:(b.concealmentEvents||0)-((($=this.audioConsumerToStatsMap.get(_))==null?void 0:$.concealmentEvents)||0),packetsLost:(b.packetsLost||0)-(((z=this.audioConsumerToStatsMap.get(_))==null?void 0:z.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((he=this.audioConsumerToStatsMap.get(_))==null?void 0:he.packetsReceived)||0),jitter:b.jitter||0}),y.set(_,{score:+(b.score*10).toFixed(),packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((Oe=this.audioConsumerToStatsMap.get(_))==null?void 0:Oe.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((Kt=this.audioConsumerToStatsMap.get(_))==null?void 0:Kt.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((zr=this.audioConsumerToStatsMap.get(_))==null?void 0:zr.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,b),d.inboundAudioRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(_,fe,b)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((M,v)=>{var _,U,fe,ye,L,b,be,Pa,_a,Ca,wa,Ra,ba,ka,Ma,Aa,Ia,Da,Oa,Na,La,Va,xa;if(M.outboundVideoRtpId.length>0){const ce=[];M.outboundVideoRtpId.forEach(Nl=>{ce.push(d.outboundVideoRtp.get(Nl))});const Y=this.getWorkingSimulcastVideoStats(ce);Y.score=Gg({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((_=Y.remoteData)==null?void 0:_.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsSent:(Y.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(v))==null?void 0:U.packetsSent)||0),packetsLost:(((fe=Y.remoteData)==null?void 0:fe.packetsLost)||0)-(((L=(ye=this.videoProducerToStatsMap.get(v))==null?void 0:ye.remoteData)==null?void 0:L.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((b=this.videoProducerToStatsMap.get(v))==null?void 0:b.framesEncoded)||0)}),S.set(v,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((be=Y.remoteData)==null?void 0:be.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:rd({packetsSent:(Y.packetsSent||0)-(((Pa=this.videoProducerToStatsMap.get(v))==null?void 0:Pa.packetsSent)||0),packetsLost:(((_a=Y.remoteData)==null?void 0:_a.packetsLost)||0)-(((wa=(Ca=this.videoProducerToStatsMap.get(v))==null?void 0:Ca.remoteData)==null?void 0:wa.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Y)}else if(M.outboundAudioRtpId.length>0){const ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);ce.score=jg({packetsSent:(ce.packetsSent||0)-(((ba=this.audioProducerToStatsMap.get(v))==null?void 0:ba.packetsSent)||0),packetsLost:(((ka=ce.remoteData)==null?void 0:ka.packetsLost)||0)-(((Aa=(Ma=this.audioProducerToStatsMap.get(v))==null?void 0:Ma.remoteData)==null?void 0:Aa.packetsLost)||0),jitter:((Ia=ce.remoteData)==null?void 0:Ia.jitter)||0}),S.set(v,{score:+(ce.score*10).toFixed(),bitrate:((ce.bytesSent||0)-(((Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.bytesSent)||0))*8/7,packetsLostPercentage:rd({packetsSent:(ce.packetsSent||0)-(((Oa=this.audioProducerToStatsMap.get(v))==null?void 0:Oa.packetsSent)||0),packetsLost:(((Na=ce.remoteData)==null?void 0:Na.packetsLost)||0)-(((Va=(La=this.audioProducerToStatsMap.get(v))==null?void 0:La.remoteData)==null?void 0:Va.packetsLost)||0)}),jitter:((xa=ce.remoteData)==null?void 0:xa.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ce)}}),f.forEach(M=>{const v=u.find(U=>U.id===M.localCandidateId?(M.localCandidateId=U.id,U):null),_=p.find(U=>U.id===M.remoteCandidateId?(M.remoteCandidateId=U.id,U):null);v&&(M.localCandidateType=v.type,M.localCandidateAddress=Br(v.address),M.localCandidatePort=v.port,M.localCandidateProtocol=v.protocol,M.localCandidateUrl=v.url,M.localCandidateNetworkType=v.networkType,M.localCandidateRelatedAddress=Br(v.relatedAddress),M.localCandidateRelatedPort=v.relatedPort),_&&(M.remoteCandidateType=_.type,M.remoteCandidateAddress=Br(_.address),M.remoteCandidatePort=_.port,M.remoteCandidateProtocol=_.protocol,M.remoteCandidateUrl=_.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((_,U)=>{_.roundTripTime&&_.roundTripTime>M&&(M=_.roundTripTime,v=_.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=v}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(M){}if(S.size>0)try{this.observer.emit("producer_score",S)}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 n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,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,n)=>{var o,c;r.push({producerId:n,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(n))==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,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,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||Oh},i=new Promise((u,p)=>{try{const f=new iS(r);f.addListener("done",u),f.addListener("failed",()=>{u({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),n=new Promise((u,p)=>{try{const f=new nS(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 aS(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,n,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((n,o)=>{try{const c={iceServers:e||Oh},d=new rS(c);d.addListener("done",n),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 Yg.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?Nh(l==null?void 0:l.loc):void 0}}const[i,n,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?Nh(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}}}class cS extends Xg{}class Zg extends Xg{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(),n=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...n.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(n,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,n=void 0,o=void 0){var P,R,k,I,O,x,B,$,z,he,Oe,Kt,zr;const c=e,d=new Qg,l=r.length?new Set(r):void 0,u=[],p=[],f=[],S=new Map,y=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:_}=M,U=M,fe={nominated:v!=null?v:_,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(fe),(M.nominated===!0||M.selected===!0)&&(d.candidatePair=fe);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 _={bytesReceived:v.bytesReceived,bytesSent:v.bytesSent,packetsSent:v.packetsSent,packetsReceived:v.packetsReceived,dtlsCipher:v.dtlsCipher,dtlsState:v.dtlsState,iceRole:v.iceRole};if(d.transport=_,o){if(o.producing){const U=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,U,_)}if(o.consuming){const U=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,U,_)}}break}case"remote-inbound-rtp":{const v=M,_={jitter:v.jitter,fractionLost:v.fractionLost,roundTripTime:v.roundTripTime,roundTripTimeMeasurements:v.roundTripTimeMeasurements,totalRoundTripTime:v.totalRoundTripTime,packetsLost:v.packetsLost};d.remoteInboundRtp.set(v.localId,_);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(M.id))break;const v=M,_=n||this.outboundProducerMap.get(M.id),U=this.pausedProducerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const fe=this.overallProducersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.outboundProducerMap.has(M.id)){d.staleProducerStreamMap=!0;break}const ye=this.callStatsInstance.producers.get(_);if(((P=ye==null?void 0:ye.track)==null?void 0:P.readyState)==="ended")break;d.producerStreamMap.has(_)||d.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const L={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 b=v,be={frameHeight:b.frameHeight,frameWidth:b.frameWidth,framesEncoded:b.framesEncoded,framesDropped:b.framesDropped?b.framesDropped:b.droppedFrames,framesPerSecond:b.framesPerSecond?b.framesPerSecond:b.framerateMean,framesSent:b.framesSent,keyFramesEncoded:b.keyFramesEncoded,firCount:b.firCount,encoderImplementation:b.encoderImplementation,hugeFramesSent:b.hugeFramesSent,pliCount:b.pliCount,qpSum:b.qpSum,qualityLimitationReason:b.qualityLimitationReason,qualityLimitationDurations:b.qualityLimitationDurations,qualityLimitationResolutionChanges:b.qualityLimitationResolutionChanges,totalEncodeTime:b.totalEncodeTime,totalPacketSendDelay:b.totalEncodeTime,retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,scalabilityMode:b.scalabilityMode,powerEfficientEncoder:b.powerEfficientEncoder,...L};d.outboundVideoRtp.set(M.id,be),d.producerStreamMap.get(_).outboundVideoRtpId.push(M.id),this.processOutboundProducerVideoStats(_,fe,be)}else if(v.mediaType==="audio"||v.kind==="audio"){const b=v,be={retransmittedBytesSent:b.retransmittedBytesSent,retransmittedPacketsSent:b.retransmittedPacketsSent,...L};d.outboundAudioRtp.set(M.id,be),d.producerStreamMap.get(_).outboundAudioRtpId.push(M.id),this.processOutboundProducerAudioStats(_,fe,be)}}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,_=n||this.inboundConsumerMap.get(M.id),U=this.pausedConsumerMap.get(_);if(U){if(U.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(v.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const fe=this.overallConsumersStatsMap[_];if(["video","audio"].includes(v.mediaType)||["video","audio"].includes(v.kind)){if(!this.inboundConsumerMap.has(M.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(_)||d.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const ye={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 L=v,b={frameHeight:L.frameHeight,frameWidth:L.frameWidth,framesDecoded:L.framesDecoded,framesDropped:L.framesDropped?L.framesDropped:L.droppedFrames,framesPerSecond:L.framesPerSecond?L.framesPerSecond:L.framerateMean,framesReceived:L.framesReceived,keyFramesDecoded:L.keyFramesDecoded,firCount:L.firCount,decoderImplementation:L.decoderImplementation,pliCount:L.pliCount,totalProcessingDelay:L.totalProcessingDelay,qpSum:L.qpSum||0,totalAssemblyTime:L.totalAssemblyTime||0,totalDecodeTime:L.totalDecodeTime||0,totalFreezesDuration:L.totalFreezesDuration||0,totalInterFrameDelay:L.totalInterFrameDelay||0,totalPausesDuration:L.totalPausesDuration||0,totalSquaredInterFrameDelay:L.totalSquaredInterFrameDelay||0,freezeCount:L.freezeCount||0,pauseCount:L.pauseCount||0,powerEfficientDecoder:L.powerEfficientDecoder,...ye};b.score=Kg({frameWidth:b.frameWidth||0,framesDecoded:(b.framesDecoded||0)-(((R=this.videoConsumerToStatsMap.get(_))==null?void 0:R.framesDecoded)||0),framesPerSecond:b.framesPerSecond||0,packetsLost:(b.packetsLost||0)-(((k=this.videoConsumerToStatsMap.get(_))==null?void 0:k.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((I=this.videoConsumerToStatsMap.get(_))==null?void 0:I.packetsReceived)||0),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),y.set(_,{score:+(b.score*10).toFixed(),frameWidth:b.frameWidth||0,frameHeight:b.frameHeight||0,framesPerSecond:b.framesPerSecond||0,packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((O=this.videoConsumerToStatsMap.get(_))==null?void 0:O.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(_))==null?void 0:x.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((B=this.videoConsumerToStatsMap.get(_))==null?void 0:B.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,b),d.inboundVideoRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundVideoRtpId.push(M.id),this.processInboundConsumerVideoStats(_,fe,b)}else if(v.mediaType==="audio"||v.kind==="audio"){const L=v,b={audioLevel:L.audioLevel,concealedSamples:L.concealedSamples,concealmentEvents:L.concealmentEvents,totalAudioEnergy:L.totalAudioEnergy,totalSamplesDuration:L.totalSamplesDuration,totalSamplesReceived:L.totalSamplesReceived,fecPacketsDiscarded:L.fecPacketsDiscarded||0,fecPacketsReceived:L.fecPacketsReceived||0,insertedSamplesForDeceleration:L.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:L.removedSamplesForAcceleration||0,silentConcealedSamples:L.silentConcealedSamples||0,playoutId:L.playoutId,...ye};b.score=Jg({concealmentEvents:(b.concealmentEvents||0)-((($=this.audioConsumerToStatsMap.get(_))==null?void 0:$.concealmentEvents)||0),packetsLost:(b.packetsLost||0)-(((z=this.audioConsumerToStatsMap.get(_))==null?void 0:z.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((he=this.audioConsumerToStatsMap.get(_))==null?void 0:he.packetsReceived)||0),jitter:b.jitter||0}),y.set(_,{score:+(b.score*10).toFixed(),packetsLostPercentage:id({packetsLost:(b.packetsLost||0)-(((Oe=this.audioConsumerToStatsMap.get(_))==null?void 0:Oe.packetsLost)||0),packetsReceived:(b.packetsReceived||0)-(((Kt=this.audioConsumerToStatsMap.get(_))==null?void 0:Kt.packetsReceived)||0)}),jitter:b.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((b.bytesReceived||0)-(((zr=this.audioConsumerToStatsMap.get(_))==null?void 0:zr.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,b),d.inboundAudioRtp.set(M.id,b),d.consumerStreamMap.get(_).inboundAudioRtpId.push(M.id),this.processInboundConsumerAudioStats(_,fe,b)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${v.mediaType} kind: ${v.kind}`);break}}}if(d.producerStreamMap.forEach((M,v)=>{var _,U,fe,ye,L,b,be,Pa,_a,Ca,wa,Ra,ba,ka,Ma,Aa,Ia,Da,Oa,Na,La,Va,xa;if(M.outboundVideoRtpId.length>0){const ce=[];M.outboundVideoRtpId.forEach(Nl=>{ce.push(d.outboundVideoRtp.get(Nl))});const Y=this.getWorkingSimulcastVideoStats(ce);Y.score=Gg({frameWidth:Y.frameWidth||0,framesPerSecond:Y.framesPerSecond||0,jitter:((_=Y.remoteData)==null?void 0:_.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsSent:(Y.packetsSent||0)-(((U=this.videoProducerToStatsMap.get(v))==null?void 0:U.packetsSent)||0),packetsLost:(((fe=Y.remoteData)==null?void 0:fe.packetsLost)||0)-(((L=(ye=this.videoProducerToStatsMap.get(v))==null?void 0:ye.remoteData)==null?void 0:L.packetsLost)||0),framesEncoded:(Y.framesEncoded||0)-(((b=this.videoProducerToStatsMap.get(v))==null?void 0:b.framesEncoded)||0)}),S.set(v,{score:+(Y.score*10).toFixed(),frameWidth:Y.frameWidth||0,frameHeight:Y.frameHeight||0,framesPerSecond:Y.framesPerSecond||0,jitter:((be=Y.remoteData)==null?void 0:be.jitter)||0,isScreenShare:this.screenShareProducers.has(v),packetsLostPercentage:rd({packetsSent:(Y.packetsSent||0)-(((Pa=this.videoProducerToStatsMap.get(v))==null?void 0:Pa.packetsSent)||0),packetsLost:(((_a=Y.remoteData)==null?void 0:_a.packetsLost)||0)-(((wa=(Ca=this.videoProducerToStatsMap.get(v))==null?void 0:Ca.remoteData)==null?void 0:wa.packetsLost)||0)}),bitrate:((Y.bytesSent||0)-(((Ra=this.videoProducerToStatsMap.get(v))==null?void 0:Ra.bytesSent)||0))*8/7,cpuLimitations:Y.qualityLimitationReason==="cpu",bandwidthLimitations:Y.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(v,Y)}else if(M.outboundAudioRtpId.length>0){const ce=d.outboundAudioRtp.get(M.outboundAudioRtpId[0]);ce.score=jg({packetsSent:(ce.packetsSent||0)-(((ba=this.audioProducerToStatsMap.get(v))==null?void 0:ba.packetsSent)||0),packetsLost:(((ka=ce.remoteData)==null?void 0:ka.packetsLost)||0)-(((Aa=(Ma=this.audioProducerToStatsMap.get(v))==null?void 0:Ma.remoteData)==null?void 0:Aa.packetsLost)||0),jitter:((Ia=ce.remoteData)==null?void 0:Ia.jitter)||0}),S.set(v,{score:+(ce.score*10).toFixed(),bitrate:((ce.bytesSent||0)-(((Da=this.audioProducerToStatsMap.get(v))==null?void 0:Da.bytesSent)||0))*8/7,packetsLostPercentage:rd({packetsSent:(ce.packetsSent||0)-(((Oa=this.audioProducerToStatsMap.get(v))==null?void 0:Oa.packetsSent)||0),packetsLost:(((Na=ce.remoteData)==null?void 0:Na.packetsLost)||0)-(((Va=(La=this.audioProducerToStatsMap.get(v))==null?void 0:La.remoteData)==null?void 0:Va.packetsLost)||0)}),jitter:((xa=ce.remoteData)==null?void 0:xa.jitter)||0,isScreenShare:this.screenShareProducers.has(v)}),this.audioProducerToStatsMap.set(v,ce)}}),f.forEach(M=>{const v=u.find(U=>U.id===M.localCandidateId?(M.localCandidateId=U.id,U):null),_=p.find(U=>U.id===M.remoteCandidateId?(M.remoteCandidateId=U.id,U):null);v&&(M.localCandidateType=v.type,M.localCandidateAddress=Br(v.address),M.localCandidatePort=v.port,M.localCandidateProtocol=v.protocol,M.localCandidateUrl=v.url,M.localCandidateNetworkType=v.networkType,M.localCandidateRelatedAddress=Br(v.relatedAddress),M.localCandidateRelatedPort=v.relatedPort),_&&(M.remoteCandidateType=_.type,M.remoteCandidateAddress=Br(_.address),M.remoteCandidatePort=_.port,M.remoteCandidateProtocol=_.protocol,M.remoteCandidateUrl=_.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((_,U)=>{_.roundTripTime&&_.roundTripTime>M&&(M=_.roundTripTime,v=_.totalRoundTripTime)}),d.transport.roundTripTime=M,d.transport.totalRoundTripTime=v}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(M){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(M){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),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:n,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 n;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(),S=e.inboundVideoRtp.get(u);return S.frameHeight||(S.frameHeight=f.height,S.frameWidth=f.width,S.framesPerSecond=f.frameRate),S});n={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 n}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,n))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class dS extends Zg{}function nd(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 Lh(s,t,e){const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{nd(this,t,e,o)}):n}catch(n){nd(this,t,e,n)}return null},s}const K=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{nd(this,s,t,d)}):c}catch(c){nd(this,s,t,c)}return null},i},lS=(s,t)=>(e,r,i)=>{if(i)return Lh(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);o.value instanceof Function&&Object.defineProperty(e.prototype,n,Lh(o,s,t))}};var G=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(n=(i<3?o(n):i>3?o(t,e,n):o(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n};const W=console;let F=class extends et{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=xg.PROD,n,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 KT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new cS;break;case"Gecko":this.measurements=new Zg;break;case"WebKit":this.measurements=new dS;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 et,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(n=>{this.registerProducer(n)}),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(n=>{this.registerConsumer(n)}),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===Nt.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===Nt.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===Nt.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Nt.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===Nt.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===Nt.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===Nt.AUDIO&&D.AUDIO_PLAY_FAILED||e===Nt.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Nt.AUDIO&&D.AUDIO_TRACK_MUTED||e===Nt.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(n,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)}n({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(n=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}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,n;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&&(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!((d=n.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()]);n&&l?n.consumerReport=l:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.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:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.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}})}};G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerIceServers",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendConsumerSharedMediaStateEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"registerConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterConsumer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"deRegisterProducer",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectConsumingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"disconnectProducingTransport",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPreCallTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendScreenShareRequestedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendActiveSpeakerEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"devices",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"selectedDevice",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPermission",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaPlaybackFailed",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"mediaTrackMuted",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"tabChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserBackgrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"browserForegrounded",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"legacySwitch",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"getPreCallTestResults",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendCallJoinBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendNetworkQualityTestBeginEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendWebSocketConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendTransportConnectedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendAudioToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendVideoToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendParticipantRoleToggleEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"startPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"stopPingStats",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPingStatsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRebufferEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAudioBlockEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerInitializedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerWorkerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerRecoverableErrorEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerAnalyticsEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendIVSPlayerQualityChanged",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendPlayerLiveLatency",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendDisconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"sendReconnectEvent",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedVideoResolution",null);G([K(TypeError,(s,t)=>W.error(t,s))],F.prototype,"expectedScreenshareResolution",null);F=G([lS(TypeError,(s,t)=>W.error(t,s))],F);const uS=F;class em extends et{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=xg.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:p}){var f,S,y;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 Yg.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new uS(o,r,i,c,d,e,l,p),this.iceServers=n,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(y=(S=this.backend)==null?void 0:S.eventHandler)==null||y.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(P){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.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(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(n=this.backend)==null||n.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 n;(n=this.backend)==null||n.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.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 n,o,c,d,l,u,p,f,S,y,P;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.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":(S=this.backend)==null||S.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(y=this.backend)==null||y.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(P=this.backend)==null||P.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 n;(n=this.backend)==null||n.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedScreenshareResolution(e,r,i)})}}const hS=new em;hS.setMaxListeners(30);var mo;class pS{constructor(){g(this,mo,void 0)}get telemetry(){var t;return(t=a(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 As,Is;class gS extends et.EventEmitter{constructor(e){super();g(this,As,void 0);g(this,Is,void 0);h(this,"asyncPromiseTimeout");h(this,"logger");this.logger=e,m(this,As,new Map),m(this,Is,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,As).set(e,[]);const i=a(this,Is).get(e).map(()=>new Promise(n=>{a(this,As).get(e).push(n)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((n,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),a(this,As).delete(e)}onAsync(e,r){const i=a(this,As),n=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 a(this,Is).get(e)||a(this,Is).set(e,[]),a(this,Is).get(e).push(n),super.on(e,n)}reset(){m(this,As,new Map),m(this,Is,new Map),super.removeAllListeners()}}As=new WeakMap,Is=new WeakMap;var mS=typeof global=="object"&&global&&global.Object===Object&&global;const tm=mS;var fS=typeof self=="object"&&self&&self.Object===Object&&self,TS=tm||fS||Function("return this")();const ds=TS;var SS=ds.Symbol;const Ps=SS;var sm=Object.prototype,vS=sm.hasOwnProperty,yS=sm.toString,Ua=Ps?Ps.toStringTag:void 0;function ES(s){var t=vS.call(s,Ua),e=s[Ua];try{s[Ua]=void 0;var r=!0}catch(n){}var i=yS.call(s);return r&&(t?s[Ua]=e:delete s[Ua]),i}var PS=Object.prototype,_S=PS.toString;function CS(s){return _S.call(s)}var wS="[object Null]",RS="[object Undefined]",Vh=Ps?Ps.toStringTag:void 0;function Ji(s){return s==null?s===void 0?RS:wS:Vh&&Vh in Object(s)?ES(s):CS(s)}function _s(s){return s!=null&&typeof s=="object"}var bS="[object Symbol]";function fl(s){return typeof s=="symbol"||_s(s)&&Ji(s)==bS}function kS(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 MS=Array.isArray;const kt=MS;var AS=1/0,xh=Ps?Ps.prototype:void 0,Uh=xh?xh.toString:void 0;function rm(s){if(typeof s=="string")return s;if(kt(s))return kS(s,rm)+"";if(fl(s))return Uh?Uh.call(s):"";var t=s+"";return t=="0"&&1/s==-AS?"-0":t}var IS=/\s/;function DS(s){for(var t=s.length;t--&&IS.test(s.charAt(t)););return t}var OS=/^\s+/;function NS(s){return s&&s.slice(0,DS(s)+1).replace(OS,"")}function Gt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var $h=0/0,LS=/^[-+]0x[0-9a-f]+$/i,VS=/^0b[01]+$/i,xS=/^0o[0-7]+$/i,US=parseInt;function Bh(s){if(typeof s=="number")return s;if(fl(s))return $h;if(Gt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Gt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=NS(s);var e=VS.test(s);return e||xS.test(s)?US(s.slice(2),e?2:8):LS.test(s)?$h:+s}function Ju(s){return s}var $S="[object AsyncFunction]",BS="[object Function]",HS="[object GeneratorFunction]",FS="[object Proxy]";function Ku(s){if(!Gt(s))return!1;var t=Ji(s);return t==BS||t==HS||t==$S||t==FS}var qS=ds["__core-js_shared__"];const Vl=qS;var Hh=function(){var s=/[^.]+$/.exec(Vl&&Vl.keys&&Vl.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function jS(s){return!!Hh&&Hh in s}var GS=Function.prototype,WS=GS.toString;function Ki(s){if(s!=null){try{return WS.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var JS=/[\\^$.*+?()[\]{}|]/g,KS=/^\[object .+?Constructor\]$/,zS=Function.prototype,YS=Object.prototype,QS=zS.toString,XS=YS.hasOwnProperty,ZS=RegExp("^"+QS.call(XS).replace(JS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ev(s){if(!Gt(s)||jS(s))return!1;var t=Ku(s)?ZS:KS;return t.test(Ki(s))}function tv(s,t){return s==null?void 0:s[t]}function zi(s,t){var e=tv(s,t);return ev(e)?e:void 0}var sv=zi(ds,"WeakMap");const Ql=sv;var Fh=Object.create,rv=function(){function s(){}return function(t){if(!Gt(t))return{};if(Fh)return Fh(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const iv=rv;function nv(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 av(){}function im(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var ov=800,cv=16,dv=Date.now;function lv(s){var t=0,e=0;return function(){var r=dv(),i=cv-(r-e);if(e=r,i>0){if(++t>=ov)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function uv(s){return function(){return s}}var hv=function(){try{var s=zi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const ad=hv;var pv=ad?function(s,t){return ad(s,"toString",{configurable:!0,enumerable:!1,value:uv(t),writable:!0})}:Ju;const gv=pv;var mv=lv(gv);const fv=mv;function Tv(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function Sv(s,t,e,r){for(var i=s.length,n=e+(r?1:-1);r?n--:++n<i;)if(t(s[n],n,s))return n;return-1}function vv(s){return s!==s}function yv(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function Ev(s,t,e){return t===t?yv(s,t,e):Sv(s,vv,e)}function Pv(s,t){var e=s==null?0:s.length;return!!e&&Ev(s,t,0)>-1}var _v=9007199254740991,Cv=/^(?:0|[1-9]\d*)$/;function zu(s,t){var e=typeof s;return t=t==null?_v:t,!!t&&(e=="number"||e!="symbol"&&Cv.test(s))&&s>-1&&s%1==0&&s<t}function Yu(s,t,e){t=="__proto__"&&ad?ad(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function yc(s,t){return s===t||s!==s&&t!==t}var wv=Object.prototype,Rv=wv.hasOwnProperty;function nm(s,t,e){var r=s[t];(!(Rv.call(s,t)&&yc(r,e))||e===void 0&&!(t in s))&&Yu(s,t,e)}function Ec(s,t,e,r){var i=!e;e||(e={});for(var n=-1,o=t.length;++n<o;){var c=t[n],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?Yu(e,c,d):nm(e,c,d)}return e}var qh=Math.max;function bv(s,t,e){return t=qh(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=qh(r.length-t,0),o=Array(n);++i<n;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),nv(s,this,c)}}function kv(s,t){return fv(bv(s,t,Ju),s+"")}var Mv=9007199254740991;function Qu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=Mv}function Pc(s){return s!=null&&Qu(s.length)&&!Ku(s)}function Av(s,t,e){if(!Gt(e))return!1;var r=typeof t;return(r=="number"?Pc(e)&&zu(t,e.length):r=="string"&&t in e)?yc(e[t],s):!1}function Iv(s){return kv(function(t,e){var r=-1,i=e.length,n=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(n=s.length>3&&typeof n=="function"?(i--,n):void 0,o&&Av(e[0],e[1],o)&&(n=i<3?void 0:n,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,n)}return t})}var Dv=Object.prototype;function Tl(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Dv;return s===e}function Ov(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var Nv="[object Arguments]";function jh(s){return _s(s)&&Ji(s)==Nv}var am=Object.prototype,Lv=am.hasOwnProperty,Vv=am.propertyIsEnumerable,xv=jh(function(){return arguments}())?jh:function(s){return _s(s)&&Lv.call(s,"callee")&&!Vv.call(s,"callee")};const oo=xv;function Uv(){return!1}var om=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gh=om&&typeof module=="object"&&module&&!module.nodeType&&module,$v=Gh&&Gh.exports===om,Wh=$v?ds.Buffer:void 0,Bv=Wh?Wh.isBuffer:void 0,Hv=Bv||Uv;const ga=Hv;var Fv="[object Arguments]",qv="[object Array]",jv="[object Boolean]",Gv="[object Date]",Wv="[object Error]",Jv="[object Function]",Kv="[object Map]",zv="[object Number]",Yv="[object Object]",Qv="[object RegExp]",Xv="[object Set]",Zv="[object String]",ey="[object WeakMap]",ty="[object ArrayBuffer]",sy="[object DataView]",ry="[object Float32Array]",iy="[object Float64Array]",ny="[object Int8Array]",ay="[object Int16Array]",oy="[object Int32Array]",cy="[object Uint8Array]",dy="[object Uint8ClampedArray]",ly="[object Uint16Array]",uy="[object Uint32Array]",ge={};ge[ry]=ge[iy]=ge[ny]=ge[ay]=ge[oy]=ge[cy]=ge[dy]=ge[ly]=ge[uy]=!0;ge[Fv]=ge[qv]=ge[ty]=ge[jv]=ge[sy]=ge[Gv]=ge[Wv]=ge[Jv]=ge[Kv]=ge[zv]=ge[Yv]=ge[Qv]=ge[Xv]=ge[Zv]=ge[ey]=!1;function hy(s){return _s(s)&&Qu(s.length)&&!!ge[Ji(s)]}function Xu(s){return function(t){return s(t)}}var cm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Qa=cm&&typeof module=="object"&&module&&!module.nodeType&&module,py=Qa&&Qa.exports===cm,xl=py&&tm.process,gy=function(){try{var s=Qa&&Qa.require&&Qa.require("util").types;return s||xl&&xl.binding&&xl.binding("util")}catch(t){}}();const ma=gy;var Jh=ma&&ma.isTypedArray,my=Jh?Xu(Jh):hy;const Sl=my;var fy=Object.prototype,Ty=fy.hasOwnProperty;function dm(s,t){var e=kt(s),r=!e&&oo(s),i=!e&&!r&&ga(s),n=!e&&!r&&!i&&Sl(s),o=e||r||i||n,c=o?Ov(s.length,String):[],d=c.length;for(var l in s)(t||Ty.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||zu(l,d)))&&c.push(l);return c}function lm(s,t){return function(e){return s(t(e))}}var Sy=lm(Object.keys,Object);const vy=Sy;var yy=Object.prototype,Ey=yy.hasOwnProperty;function um(s){if(!Tl(s))return vy(s);var t=[];for(var e in Object(s))Ey.call(s,e)&&e!="constructor"&&t.push(e);return t}function vl(s){return Pc(s)?dm(s):um(s)}function Py(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var _y=Object.prototype,Cy=_y.hasOwnProperty;function wy(s){if(!Gt(s))return Py(s);var t=Tl(s),e=[];for(var r in s)r=="constructor"&&(t||!Cy.call(s,r))||e.push(r);return e}function _c(s){return Pc(s)?dm(s,!0):wy(s)}var Ry=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,by=/^\w*$/;function Zu(s,t){if(kt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||fl(s)?!0:by.test(s)||!Ry.test(s)||t!=null&&s in Object(t)}var ky=zi(Object,"create");const co=ky;function My(){this.__data__=co?co(null):{},this.size=0}function Ay(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Iy="__lodash_hash_undefined__",Dy=Object.prototype,Oy=Dy.hasOwnProperty;function Ny(s){var t=this.__data__;if(co){var e=t[s];return e===Iy?void 0:e}return Oy.call(t,s)?t[s]:void 0}var Ly=Object.prototype,Vy=Ly.hasOwnProperty;function xy(s){var t=this.__data__;return co?t[s]!==void 0:Vy.call(t,s)}var Uy="__lodash_hash_undefined__";function $y(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=co&&t===void 0?Uy:t,this}function Gi(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])}}Gi.prototype.clear=My;Gi.prototype.delete=Ay;Gi.prototype.get=Ny;Gi.prototype.has=xy;Gi.prototype.set=$y;function By(){this.__data__=[],this.size=0}function yl(s,t){for(var e=s.length;e--;)if(yc(s[e][0],t))return e;return-1}var Hy=Array.prototype,Fy=Hy.splice;function qy(s){var t=this.__data__,e=yl(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():Fy.call(t,e,1),--this.size,!0}function jy(s){var t=this.__data__,e=yl(t,s);return e<0?void 0:t[e][1]}function Gy(s){return yl(this.__data__,s)>-1}function Wy(s,t){var e=this.__data__,r=yl(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function rr(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])}}rr.prototype.clear=By;rr.prototype.delete=qy;rr.prototype.get=jy;rr.prototype.has=Gy;rr.prototype.set=Wy;var Jy=zi(ds,"Map");const lo=Jy;function Ky(){this.size=0,this.__data__={hash:new Gi,map:new(lo||rr),string:new Gi}}function zy(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function El(s,t){var e=s.__data__;return zy(t)?e[typeof t=="string"?"string":"hash"]:e.map}function Yy(s){var t=El(this,s).delete(s);return this.size-=t?1:0,t}function Qy(s){return El(this,s).get(s)}function Xy(s){return El(this,s).has(s)}function Zy(s,t){var e=El(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function ir(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])}}ir.prototype.clear=Ky;ir.prototype.delete=Yy;ir.prototype.get=Qy;ir.prototype.has=Xy;ir.prototype.set=Zy;var eE="Expected a function";function eh(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(eE);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],n=e.cache;if(n.has(i))return n.get(i);var o=s.apply(this,r);return e.cache=n.set(i,o)||n,o};return e.cache=new(eh.Cache||ir),e}eh.Cache=ir;var tE=500;function sE(s){var t=eh(s,function(r){return e.size===tE&&e.clear(),r}),e=t.cache;return t}var rE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,iE=/\\(\\)?/g,nE=sE(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(rE,function(e,r,i,n){t.push(i?n.replace(iE,"$1"):r||e)}),t});const aE=nE;function oE(s){return s==null?"":rm(s)}function hm(s,t){return kt(s)?s:Zu(s,t)?[s]:aE(oE(s))}var cE=1/0;function Pl(s){if(typeof s=="string"||fl(s))return s;var t=s+"";return t=="0"&&1/s==-cE?"-0":t}function pm(s,t){t=hm(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[Pl(t[e++])];return e&&e==r?s:void 0}function dE(s,t,e){var r=s==null?void 0:pm(s,t);return r===void 0?e:r}function gm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var lE=lm(Object.getPrototypeOf,Object);const th=lE;var uE="[object Object]",hE=Function.prototype,pE=Object.prototype,mm=hE.toString,gE=pE.hasOwnProperty,mE=mm.call(Object);function fE(s){if(!_s(s)||Ji(s)!=uE)return!1;var t=th(s);if(t===null)return!0;var e=gE.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&mm.call(e)==mE}function TE(){this.__data__=new rr,this.size=0}function SE(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function vE(s){return this.__data__.get(s)}function yE(s){return this.__data__.has(s)}var EE=200;function PE(s,t){var e=this.__data__;if(e instanceof rr){var r=e.__data__;if(!lo||r.length<EE-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new ir(r)}return e.set(s,t),this.size=e.size,this}function cs(s){var t=this.__data__=new rr(s);this.size=t.size}cs.prototype.clear=TE;cs.prototype.delete=SE;cs.prototype.get=vE;cs.prototype.has=yE;cs.prototype.set=PE;function _E(s,t){return s&&Ec(t,vl(t),s)}function CE(s,t){return s&&Ec(t,_c(t),s)}var fm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Kh=fm&&typeof module=="object"&&module&&!module.nodeType&&module,wE=Kh&&Kh.exports===fm,zh=wE?ds.Buffer:void 0,Yh=zh?zh.allocUnsafe:void 0;function Tm(s,t){if(t)return s.slice();var e=s.length,r=Yh?Yh(e):new s.constructor(e);return s.copy(r),r}function RE(s,t){for(var e=-1,r=s==null?0:s.length,i=0,n=[];++e<r;){var o=s[e];t(o,e,s)&&(n[i++]=o)}return n}function Sm(){return[]}var bE=Object.prototype,kE=bE.propertyIsEnumerable,Qh=Object.getOwnPropertySymbols,ME=Qh?function(s){return s==null?[]:(s=Object(s),RE(Qh(s),function(t){return kE.call(s,t)}))}:Sm;const sh=ME;function AE(s,t){return Ec(s,sh(s),t)}var IE=Object.getOwnPropertySymbols,DE=IE?function(s){for(var t=[];s;)gm(t,sh(s)),s=th(s);return t}:Sm;const vm=DE;function OE(s,t){return Ec(s,vm(s),t)}function ym(s,t,e){var r=t(s);return kt(s)?r:gm(r,e(s))}function Xl(s){return ym(s,vl,sh)}function NE(s){return ym(s,_c,vm)}var LE=zi(ds,"DataView");const Zl=LE;var VE=zi(ds,"Promise");const eu=VE;var xE=zi(ds,"Set");const hn=xE;var Xh="[object Map]",UE="[object Object]",Zh="[object Promise]",ep="[object Set]",tp="[object WeakMap]",sp="[object DataView]",$E=Ki(Zl),BE=Ki(lo),HE=Ki(eu),FE=Ki(hn),qE=Ki(Ql),Yr=Ji;(Zl&&Yr(new Zl(new ArrayBuffer(1)))!=sp||lo&&Yr(new lo)!=Xh||eu&&Yr(eu.resolve())!=Zh||hn&&Yr(new hn)!=ep||Ql&&Yr(new Ql)!=tp)&&(Yr=function(s){var t=Ji(s),e=t==UE?s.constructor:void 0,r=e?Ki(e):"";if(r)switch(r){case $E:return sp;case BE:return Xh;case HE:return Zh;case FE:return ep;case qE:return tp}return t});const fa=Yr;var jE=Object.prototype,GE=jE.hasOwnProperty;function WE(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&GE.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var JE=ds.Uint8Array;const od=JE;function rh(s){var t=new s.constructor(s.byteLength);return new od(t).set(new od(s)),t}function KE(s,t){var e=t?rh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var zE=/\w*$/;function YE(s){var t=new s.constructor(s.source,zE.exec(s));return t.lastIndex=s.lastIndex,t}var rp=Ps?Ps.prototype:void 0,ip=rp?rp.valueOf:void 0;function QE(s){return ip?Object(ip.call(s)):{}}function Em(s,t){var e=t?rh(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var XE="[object Boolean]",ZE="[object Date]",eP="[object Map]",tP="[object Number]",sP="[object RegExp]",rP="[object Set]",iP="[object String]",nP="[object Symbol]",aP="[object ArrayBuffer]",oP="[object DataView]",cP="[object Float32Array]",dP="[object Float64Array]",lP="[object Int8Array]",uP="[object Int16Array]",hP="[object Int32Array]",pP="[object Uint8Array]",gP="[object Uint8ClampedArray]",mP="[object Uint16Array]",fP="[object Uint32Array]";function TP(s,t,e){var r=s.constructor;switch(t){case aP:return rh(s);case XE:case ZE:return new r(+s);case oP:return KE(s,e);case cP:case dP:case lP:case uP:case hP:case pP:case gP:case mP:case fP:return Em(s,e);case eP:return new r;case tP:case iP:return new r(s);case sP:return YE(s);case rP:return new r;case nP:return QE(s)}}function Pm(s){return typeof s.constructor=="function"&&!Tl(s)?iv(th(s)):{}}var SP="[object Map]";function vP(s){return _s(s)&&fa(s)==SP}var np=ma&&ma.isMap,yP=np?Xu(np):vP;const EP=yP;var PP="[object Set]";function _P(s){return _s(s)&&fa(s)==PP}var ap=ma&&ma.isSet,CP=ap?Xu(ap):_P;const wP=CP;var RP=1,bP=2,kP=4,_m="[object Arguments]",MP="[object Array]",AP="[object Boolean]",IP="[object Date]",DP="[object Error]",Cm="[object Function]",OP="[object GeneratorFunction]",NP="[object Map]",LP="[object Number]",wm="[object Object]",VP="[object RegExp]",xP="[object Set]",UP="[object String]",$P="[object Symbol]",BP="[object WeakMap]",HP="[object ArrayBuffer]",FP="[object DataView]",qP="[object Float32Array]",jP="[object Float64Array]",GP="[object Int8Array]",WP="[object Int16Array]",JP="[object Int32Array]",KP="[object Uint8Array]",zP="[object Uint8ClampedArray]",YP="[object Uint16Array]",QP="[object Uint32Array]",ue={};ue[_m]=ue[MP]=ue[HP]=ue[FP]=ue[AP]=ue[IP]=ue[qP]=ue[jP]=ue[GP]=ue[WP]=ue[JP]=ue[NP]=ue[LP]=ue[wm]=ue[VP]=ue[xP]=ue[UP]=ue[$P]=ue[KP]=ue[zP]=ue[YP]=ue[QP]=!0;ue[DP]=ue[Cm]=ue[BP]=!1;function Xa(s,t,e,r,i,n){var o,c=t&RP,d=t&bP,l=t&kP;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!Gt(s))return s;var u=kt(s);if(u){if(o=WE(s),!c)return im(s,o)}else{var p=fa(s),f=p==Cm||p==OP;if(ga(s))return Tm(s,c);if(p==wm||p==_m||f&&!i){if(o=d||f?{}:Pm(s),!c)return d?OE(s,CE(o,s)):AE(s,_E(o,s))}else{if(!ue[p])return i?s:{};o=TP(s,p,c)}}n||(n=new cs);var S=n.get(s);if(S)return S;n.set(s,o),wP(s)?s.forEach(function(R){o.add(Xa(R,t,e,R,s,n))}):EP(s)&&s.forEach(function(R,k){o.set(k,Xa(R,t,e,k,s,n))});var y=l?d?NE:Xl:d?_c:vl,P=u?void 0:y(s);return Tv(P||s,function(R,k){P&&(k=R,R=s[k]),nm(o,k,Xa(R,t,e,k,s,n))}),o}var XP=4;function ZP(s){return Xa(s,XP)}var e_=1,t_=4;function ih(s){return Xa(s,e_|t_)}var s_="__lodash_hash_undefined__";function r_(s){return this.__data__.set(s,s_),this}function i_(s){return this.__data__.has(s)}function uo(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new ir;++t<e;)this.add(s[t])}uo.prototype.add=uo.prototype.push=r_;uo.prototype.has=i_;function n_(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 Rm(s,t){return s.has(t)}var a_=1,o_=2;function bm(s,t,e,r,i,n){var o=e&a_,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var p=-1,f=!0,S=e&o_?new uo:void 0;for(n.set(s,t),n.set(t,s);++p<c;){var y=s[p],P=t[p];if(r)var R=o?r(P,y,p,t,s,n):r(y,P,p,s,t,n);if(R!==void 0){if(R)continue;f=!1;break}if(S){if(!n_(t,function(k,I){if(!Rm(S,I)&&(y===k||i(y,k,e,r,n)))return S.push(I)})){f=!1;break}}else if(!(y===P||i(y,P,e,r,n))){f=!1;break}}return n.delete(s),n.delete(t),f}function c_(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function nh(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var d_=1,l_=2,u_="[object Boolean]",h_="[object Date]",p_="[object Error]",g_="[object Map]",m_="[object Number]",f_="[object RegExp]",T_="[object Set]",S_="[object String]",v_="[object Symbol]",y_="[object ArrayBuffer]",E_="[object DataView]",op=Ps?Ps.prototype:void 0,Ul=op?op.valueOf:void 0;function P_(s,t,e,r,i,n,o){switch(e){case E_:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case y_:return!(s.byteLength!=t.byteLength||!n(new od(s),new od(t)));case u_:case h_:case m_:return yc(+s,+t);case p_:return s.name==t.name&&s.message==t.message;case f_:case S_:return s==t+"";case g_:var c=c_;case T_:var d=r&d_;if(c||(c=nh),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=l_,o.set(s,t);var u=bm(c(s),c(t),r,i,n,o);return o.delete(s),u;case v_:if(Ul)return Ul.call(s)==Ul.call(t)}return!1}var __=1,C_=Object.prototype,w_=C_.hasOwnProperty;function R_(s,t,e,r,i,n){var o=e&__,c=Xl(s),d=c.length,l=Xl(t),u=l.length;if(d!=u&&!o)return!1;for(var p=d;p--;){var f=c[p];if(!(o?f in t:w_.call(t,f)))return!1}var S=n.get(s),y=n.get(t);if(S&&y)return S==t&&y==s;var P=!0;n.set(s,t),n.set(t,s);for(var R=o;++p<d;){f=c[p];var k=s[f],I=t[f];if(r)var O=o?r(I,k,f,t,s,n):r(k,I,f,s,t,n);if(!(O===void 0?k===I||i(k,I,e,r,n):O)){P=!1;break}R||(R=f=="constructor")}if(P&&!R){var x=s.constructor,B=t.constructor;x!=B&&"constructor"in s&&"constructor"in t&&!(typeof x=="function"&&x instanceof x&&typeof B=="function"&&B instanceof B)&&(P=!1)}return n.delete(s),n.delete(t),P}var b_=1,cp="[object Arguments]",dp="[object Array]",Ac="[object Object]",k_=Object.prototype,lp=k_.hasOwnProperty;function M_(s,t,e,r,i,n){var o=kt(s),c=kt(t),d=o?dp:fa(s),l=c?dp:fa(t);d=d==cp?Ac:d,l=l==cp?Ac:l;var u=d==Ac,p=l==Ac,f=d==l;if(f&&ga(s)){if(!ga(t))return!1;o=!0,u=!1}if(f&&!u)return n||(n=new cs),o||Sl(s)?bm(s,t,e,r,i,n):P_(s,t,d,e,r,i,n);if(!(e&b_)){var S=u&&lp.call(s,"__wrapped__"),y=p&&lp.call(t,"__wrapped__");if(S||y){var P=S?s.value():s,R=y?t.value():t;return n||(n=new cs),i(P,R,e,r,n)}}return f?(n||(n=new cs),R_(s,t,e,r,i,n)):!1}function _l(s,t,e,r,i){return s===t?!0:s==null||t==null||!_s(s)&&!_s(t)?s!==s&&t!==t:M_(s,t,e,r,_l,i)}var A_=1,I_=2;function D_(s,t,e,r){var i=e.length,n=i,o=!r;if(s==null)return!n;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<n;){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 cs;if(r)var f=r(l,u,d,s,t,p);if(!(f===void 0?_l(u,l,A_|I_,r,p):f))return!1}}return!0}function km(s){return s===s&&!Gt(s)}function O_(s){for(var t=vl(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,km(i)]}return t}function Mm(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function N_(s){var t=O_(s);return t.length==1&&t[0][2]?Mm(t[0][0],t[0][1]):function(e){return e===s||D_(e,s,t)}}function L_(s,t){return s!=null&&t in Object(s)}function V_(s,t,e){t=hm(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=Pl(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&Qu(i)&&zu(o,i)&&(kt(s)||oo(s)))}function x_(s,t){return s!=null&&V_(s,t,L_)}var U_=1,$_=2;function B_(s,t){return Zu(s)&&km(t)?Mm(Pl(s),t):function(e){var r=dE(e,s);return r===void 0&&r===t?x_(e,s):_l(t,r,U_|$_)}}function H_(s){return function(t){return t==null?void 0:t[s]}}function F_(s){return function(t){return pm(t,s)}}function q_(s){return Zu(s)?H_(Pl(s)):F_(s)}function j_(s){return typeof s=="function"?s:s==null?Ju:typeof s=="object"?kt(s)?B_(s[0],s[1]):N_(s):q_(s)}function G_(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var W_=G_();const J_=W_;var K_=function(){return ds.Date.now()};const $l=K_;var z_="Expected a function",Y_=Math.max,Q_=Math.min;function ah(s,t,e){var r,i,n,o,c,d,l=0,u=!1,p=!1,f=!0;if(typeof s!="function")throw new TypeError(z_);t=Bh(t)||0,Gt(e)&&(u=!!e.leading,p="maxWait"in e,n=p?Y_(Bh(e.maxWait)||0,t):n,f="trailing"in e?!!e.trailing:f);function S($){var z=r,he=i;return r=i=void 0,l=$,o=s.apply(he,z),o}function y($){return l=$,c=setTimeout(k,t),u?S($):o}function P($){var z=$-d,he=$-l,Oe=t-z;return p?Q_(Oe,n-he):Oe}function R($){var z=$-d,he=$-l;return d===void 0||z>=t||z<0||p&&he>=n}function k(){var $=$l();if(R($))return I($);c=setTimeout(k,P($))}function I($){return c=void 0,f&&r?S($):(r=i=void 0,o)}function O(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function x(){return c===void 0?o:I($l())}function B(){var $=$l(),z=R($);if(r=arguments,i=this,d=$,z){if(c===void 0)return y(d);if(p)return clearTimeout(c),c=setTimeout(k,t),S(d)}return c===void 0&&(c=setTimeout(k,t)),o}return B.cancel=O,B.flush=x,B}function tu(s,t,e){(e!==void 0&&!yc(s[t],e)||e===void 0&&!(t in s))&&Yu(s,t,e)}function X_(s){return _s(s)&&Pc(s)}function su(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function Z_(s){return Ec(s,_c(s))}function eC(s,t,e,r,i,n,o){var c=su(s,e),d=su(t,e),l=o.get(d);if(l){tu(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,p=u===void 0;if(p){var f=kt(d),S=!f&&ga(d),y=!f&&!S&&Sl(d);u=d,f||S||y?kt(c)?u=c:X_(c)?u=im(c):S?(p=!1,u=Tm(d,!0)):y?(p=!1,u=Em(d,!0)):u=[]:fE(d)||oo(d)?(u=c,oo(c)?u=Z_(c):(!Gt(c)||Ku(c))&&(u=Pm(d))):p=!1}p&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),tu(s,e,u)}function Am(s,t,e,r,i){s!==t&&J_(t,function(n,o){if(i||(i=new cs),Gt(n))eC(s,t,o,e,Am,r,i);else{var c=r?r(su(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),tu(s,o,c)}},_c)}function tC(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 sC="[object Map]",rC="[object Set]",iC=Object.prototype,nC=iC.hasOwnProperty;function aC(s){if(s==null)return!0;if(Pc(s)&&(kt(s)||typeof s=="string"||typeof s.splice=="function"||ga(s)||Sl(s)||oo(s)))return!s.length;var t=fa(s);if(t==sC||t==rC)return!s.size;if(Tl(s))return!um(s).length;for(var e in s)if(nC.call(s,e))return!1;return!0}function oC(s,t){return _l(s,t)}var cC=Iv(function(s,t,e){Am(s,t,e)});const lr=cC;var dC=1/0,lC=hn&&1/nh(new hn([,-0]))[1]==dC?function(s){return new hn(s)}:av;const uC=lC;var hC=200;function Im(s,t,e){var r=-1,i=Pv,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=tC;else if(n>=hC){var l=t?null:uC(s);if(l)return nh(l);o=!1,i=Rm,d=new uo}else d=t?[]:c;e:for(;++r<n;){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 pC(s){return s&&s.length?Im(s):[]}function gC(s,t){return s&&s.length?Im(s,j_(t)):[]}function Fc(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 mC={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},up={STAGING:"staging",PROD:"prod"},fC={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 Ta(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function TC({baseURI:s}){return s.includes("staging.realtime")?up.STAGING:up.PROD}function pn({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function SC(s){const t=s.getValue("baseURI");return{location:pn({servicePrefix:"location",baseURI:t}),locationLegacy:pn({servicePrefix:"location-legacy",baseURI:t}),daCollector:pn({servicePrefix:"da-collector",baseURI:t})}}const vC='<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>',yC='<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>',Ic=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(n=>{n(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((n,o)=>{r.onload=()=>{n(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"}},EC=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,ru="__rtk_plugins__",PC=[ru];function Dm(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(ri.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function _C(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"],n=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(n<o)return!1}return!0}function Om(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var n;if([null,void 0,NaN].includes(s[r])||t&&(((n=t.match(/\./g))==null?void 0:n.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?Om(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function hp(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=Om(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 Dm(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(n){const o=Fc(n);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 E{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=Hr.getContext(this.meetingMetadata.peerId);return`https://${pn({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 n=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=n,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:o}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?o==null?void 0:o.getDeviceInfo():me.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,n)=>{const o=n.value;return n.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},n}}injectContext(t){var i;const e=qr.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:Fc(r.error)});const n=Hr.getContext(this.meetingMetadata.peerId);if(Dm(n)&&(aC(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!_C(n,t))try{const c=hp(n,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:Fc(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 n=Hr.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:hp(n,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:n.getValue("sdkName"),logs:t});let c;const d={Authorization:`Bearer ${n.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(n){e||(this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Fc(n)}),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 CC(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)},n=l=>{var u;(u=e.get(l))==null||u.forEach(p=>{try{p(t[l])}catch(f){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,p=!0)=>{t[l]=u,p&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class wC{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 E,i=new pS;this.contexts.set(t,CC(e)),this.contexts.get(t).setValue("peerSessionStore",new gS(i));const n=new em;return n.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",n),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 Hr=new wC,RC={"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"},qc={"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","0604":"Active plugins store is not available yet","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(qc).forEach(s=>{qc[s]=`{${RC[s.slice(0,2)]}} ${qc[s]}`});class w extends Error{constructor(e,r,i=void 0,n=!1){super(e);h(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?qc[this.code]:"";this.message=`${o}: ${c}
6
+ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=Hr.getContext(Hr.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 Dc(s,t,e,r){if(r instanceof w)throw r;if(r instanceof t){const i=new w(r.message,e);throw i.stack=r.stack,i}else throw r}function pp(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Dc(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Dc(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Dc(this,t,e,o)}):n}catch(n){Dc(this,t,e,n)}},s}function bC(s,t){return(e,r,i)=>{if(i)return pp(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,pp(o,s,t))}}}const tt=s=>bC(Error,s);var Xs=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Xs||{}),q=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(q||{}),eg;typeof process!="undefined"&&(eg=process==null?void 0:process.env)!=null&&eg.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Nm=[-2,-1,0,1,2],kC=[0,1,2,3,4];function MC(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 AC=(s,t,e)=>{let r,i,n;if(t==0)r=i=n=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),n=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(n*255)]},IC=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let n,o;const c=(r+i)/2;if(r==i)n=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:n=(t-e)/d+(t<e?6:0);break;case t:n=(e-s)/d+2;break;case e:n=(s-t)/d+4;break}n/=6}return[n,o,c]},DC=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Lm=(s,t=Nm,e=.4)=>{const r=[],[i,n,o]=MC(s),[c,d,l]=IC(i,n,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(R=>R===0);if(p===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const f=5-p,S=p+1,y=(100-u)/f,P=u/S;for(const R of t){let k;R<0?k=u+R*P*e:R>0?k=u+R*y*e:k=u;const[I,O,x]=AC(c,d,k/100);r.push(DC(I,O,x))}return r},gp={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"}},OC=s=>{const[t,e,r,i,n]=Lm(s,Nm);return{300:t,400:e,500:r,600:i,700:n}},NC=s=>{if(s==="#FFFFFF")return gp.light.background;if(s==="#000000")return gp.dark.background;const[t,e,r,i,n]=Lm(s,kC);return{1e3:t,900:e,800:r,700:i,600:n}},LC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:OC("#2160FD"),background:NC("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Vm(){return ih(LC)}var VC={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:Vm(),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 xC(){return ih(VC)}var UC={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:Vm(),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 oh(){return ih(UC)}function $C(){me.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(n=>{var o;return(o=n.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 Sa extends et.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 n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}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 At extends et.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 n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}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 BC(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 mp=1080,fp=1920,HC=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let p=d*u,f=l*u,S,y,P,R,k=1;return p<e&&(k=e/p),Math.abs(k-1)<1e-14&&f<r&&(k=r/f),p*=k,f*=k,P=d/(p/e),R=l/(f/r),S=(d-P)*o,y=(l-R)*c,S<0&&(S=0),y<0&&(y=0),P>d&&(P=d),R>l&&(R=l),[S,y,P,R,s,t,e,r]};var Lt,ii,Qe,Vt,_e,Qt,Ds,st,Me,Tn,Sn,Os,vn;const kh=class extends At{constructor(e,r,i,n){const o=e.getValue("logger");super(o);g(this,Lt,void 0);g(this,ii,void 0);g(this,Qe,void 0);g(this,Vt,void 0);g(this,_e,{height:mp,width:fp});g(this,Qt,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,Ds,void 0);g(this,st,{});g(this,Me,void 0);g(this,Tn,void 0);g(this,Sn,void 0);g(this,Os,void 0);g(this,vn,!1);h(this,"cleanupEventListeners",()=>{a(this,ii).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Me).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Me).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Me).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"&&(a(this,Me).videoEnabled?a(this,Me).disableVideo():a(this,Me).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Me).audioEnabled?a(this,Me).disableAudio():a(this,Me).enableAudio(),this.emit("micToggled")),e==="END"&&(a(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&&a(this,Os)==="active"){this.disable(!0);return}a(this,st)!==void 0&&this.paintCanvas(),a(this,Ds)!==void 0&&m(this,Ds,requestAnimationFrame(()=>this.animate()))});h(this,"disable",(e=!1)=>{m(this,Os,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,Ds)),e!==!0&&document.body.removeChild(a(this,Qe)),m(this,Ds,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});m(this,ii,e),m(this,Os,"idle"),m(this,Me,r),m(this,Qt,{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),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Ic(vC),n=await Ic(yC)}catch(o){}return new kh(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":m(this,Sn,r);break;case"pin":m(this,Tn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":m(this,Sn,await Ic(r));break;case"pin":m(this,Tn,await Ic(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){m(this,Qe,document.createElement("div")),a(this,Qe).style.width="0.1px",a(this,Qe).style.height="0.1px",a(this,Qe).style.overflow="hidden",a(this,Qe).style.position="absolute",a(this,Qe).style.bottom="0",a(this,Qe).style.right="0",a(this,Qe).style.opacity="0",a(this,Qe).appendChild(a(this,Vt))}setupEventListeners(){a(this,ii).subscribe("stageStatus",this.handlePipMediaControls),a(this,Me).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Me).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Me).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,_e).height,e.width=a(this,_e).width,m(this,Lt,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||a(this,Me).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Me).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,st)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,Lt)===void 0)return;const o=a(this,Lt).getContext("2d"),c=a(this,Lt).width,d=0,l=0,u=r-d*2,p=i-d*2,f=Math.floor(c/u),S=Math.floor(e/f),P=e%f*(u+d)+d,R=S*(p+d)+d,{displayText:k,image:I}=n!=null?n:{};o.fillStyle=k||I?a(this,Qt).videoBackground:a(this,Qt).background,o.strokeStyle=a(this,Qt).brand,o.beginPath(),o.moveTo(P+l,R),o.arcTo(P+u,R,P+u,R+l,l),o.arcTo(P+u,R+p,P+u-l,R+p,l),o.arcTo(P,R+p,P,R+p-l,l),o.arcTo(P,R,P+l,R,l),o.closePath(),o.fill(),o.stroke();const O=u/6,x=u/2+P,B=p/2+R;o.save(),(k||I)&&(o.beginPath(),o.arc(x,B,O,0,Math.PI*2),o.fillStyle=a(this,Qt).brand,o.fill(),I?(o.clip(),o.drawImage(I,x-O,B-O,O*2,O*2),o.restore()):k&&(o.fillStyle=a(this,Qt).textOnBrand,o.font=`${O/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(k,x,B)),this.drawIcons(n,P,R,Math.max(u,p)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,p=f=>{const S=a(this,Lt).getContext("2d");S.save(),S.fillStyle=a(this,Qt).background,S.beginPath(),S.moveTo(l+d,u),S.arcTo(l+o,u,l+o,u+d,d),S.arcTo(l+o,u+o,l+o-d,u+o,d),S.arcTo(l,u+o,l,u+o-d,d),S.arcTo(l,u,l+d,u,d),S.closePath(),S.fill(),typeof f=="string"?(S.font=`${o/1.5}px sans-serif`,S.fillStyle=a(this,Qt).text,S.textAlign="center",S.textBaseline="top",S.fillText(f,o/2+l,u+c)):S.drawImage(f,l+c,u+c,o-c*2,o-c*2),l+=o+c,S.restore()};e.pinned&&p(a(this,Tn)),e.handRaised&&p(a(this,Sn)),e.reaction&&p(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,Lt)===void 0)return;const n=a(this,Lt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,_e).height-5;){let p=0;for(;p<a(this,_e).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const f=o[d].element,[S,y,P,R,k,I,O,x]=HC(p,c,e,r,f.videoWidth,f.videoHeight);((u=f==null?void 0:f.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(f,S,y,P,R,-1*k,I,-1*O,x),n.restore()):n.drawImage(f,S,y,P,R,k,I,O,x),this.drawIcons(o[d],k,I,Math.max(O,x))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,p+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,_e).width,a(this,_e).height];case 2:return[Math.floor(a(this,_e).width/2),a(this,_e).height];case 3:case 4:return[Math.floor(a(this,_e).width/2),Math.floor(a(this,_e).height/2)];case 5:case 6:return[Math.floor(a(this,_e).width/3),Math.floor(a(this,_e).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,_e).width/3),Math.floor(a(this,_e).height/3)];default:return[Math.floor(a(this,_e).width/3),Math.floor(a(this,_e).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=a(this,Me).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(m(this,vn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,Qe))try{document.body.removeChild(a(this,Qe))}catch(e){}this.removeAllSources(),m(this,Lt,void 0),m(this,Vt,void 0),m(this,Ds,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(a(this,vn))return;m(this,vn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");m(this,_e,{height:e!=null?e:mp,width:r!=null?r:fp}),i.height=a(this,_e).height,i.width=a(this,_e).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,Lt).captureStream(24),m(this,Vt,i),a(this,Vt).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,Vt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,st)[e]!==void 0&&(a(this,st)[e].enabled=!0)}disableSource(e){a(this,st)[e]!==void 0&&(a(this,st)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,st)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?BC(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=a(this,st)[e];i&&(a(this,st)[e]={...i,...r})}removeSource(e){delete a(this,st)[e]}removePinnedSource(){Object.values(a(this,st)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){m(this,st,{})}enable(){m(this,Os,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Me).videoEnabled),this.updateMediaSession("MIC",a(this,Me).audioEnabled),document.body.appendChild(a(this,Qe)),m(this,Ds,requestAnimationFrame(()=>this.animate())),a(this,Vt).onloadedmetadata=()=>{a(this,Vt).requestPictureInPicture().then(()=>{m(this,Os,"active")})},a(this,Vt).readyState===4&&a(this,Vt).requestPictureInPicture().then(()=>{m(this,Os,"active")})}};let iu=kh;Lt=new WeakMap,ii=new WeakMap,Qe=new WeakMap,Vt=new WeakMap,_e=new WeakMap,Qt=new WeakMap,Ds=new WeakMap,st=new WeakMap,Me=new WeakMap,Tn=new WeakMap,Sn=new WeakMap,Os=new WeakMap,vn=new WeakMap;var tr;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(tr||(tr={}));var Zs;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Zs||(Zs={}));class FC extends T.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 xm=new FC;class qC extends T.MessageType{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const jC=new qC;class GC extends T.MessageType{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new GC;class WC extends T.MessageType{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",tr]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ls=new WC;class JC extends T.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 KC=new JC;class zC extends T.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:()=>ls},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>KC}])}}const YC=new zC;class QC extends T.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 XC=new QC;class ZC extends T.MessageType{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Um=new ZC;class ew extends T.MessageType{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls}])}}const tw=new ew;class sw extends T.MessageType{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls}])}}new sw;class rw extends T.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 iw=new rw;class nw extends T.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 aw=new nw;class ow extends T.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 ow;class cw extends T.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 cw;class dw extends T.MessageType{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Zs]},{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:()=>xm}])}}const Cc=new dw;class lw extends T.MessageType{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Cc},{no:3,name:"producer_track",kind:"message",T:()=>aw},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const uw=new lw;class hw extends T.MessageType{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>uw}}])}}const $m=new hw;class pw extends T.MessageType{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Sp},{no:2,name:"receiver",kind:"message",T:()=>Sp}])}}const Bm=new pw;class gw extends T.MessageType{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>xm},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>jC}])}}const Tp=new gw;class mw extends T.MessageType{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Tp},{no:2,name:"video",kind:"message",T:()=>Tp}])}}const Sp=new mw;class fw extends T.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 Tw=new fw;class Sw extends T.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 Hm=new Sw;class vw extends T.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 yw=new vw;class Ew extends T.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:()=>yw},{no:9,name:"capabilities",kind:"message",T:()=>Bm}])}}const Pw=new Ew;class _w extends T.MessageType{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const Cw=new _w;class ww extends T.MessageType{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const Rw=new ww;class bw extends T.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 bw;class kw extends T.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:()=>Tw},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Hm}])}}const Mw=new kw;class Aw extends T.MessageType{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Mw},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Iw=new Aw;class Dw extends T.MessageType{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Hm},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const Ow=new Dw;class Nw extends T.MessageType{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Ow},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Lw=new Nw;class Vw extends T.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:()=>ls},{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 xw=new Vw;class Uw extends T.MessageType{constructor(){super("media.edge.SelectedPeersRequest",[])}}new Uw;class $w extends T.MessageType{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Bw=new $w;class Hw extends T.MessageType{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Oc=new Hw;class Fw extends T.MessageType{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new Fw;class qw extends T.MessageType{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const jw=new qw;class Gw extends T.MessageType{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>ls},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Ww=new Gw;class Jw extends T.MessageType{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new Jw;class Kw extends T.MessageType{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Fm=new Kw;class zw extends T.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 Yw=new zw;class Qw extends T.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 Xw=new Qw;class Zw extends T.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 eR=new Zw;class tR extends T.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 sR=new tR;class rR extends T.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 iR=new rR;class nR extends T.MessageType{constructor(){super("media.edge.EmptyResponse",[])}}new nR;class aR extends T.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:()=>Cc},{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:()=>Bm}])}}const qm=new aR;class oR extends T.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 nu=new oR;class cR extends T.MessageType{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const dR=new cR;class lR extends T.MessageType{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>dR}])}}const vp=new lR;class uR extends T.MessageType{constructor(){super("media.edge.PeerJoinResponse",[])}}new uR;class hR extends T.MessageType{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>sR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>qm},{no:3,name:"selected_peers",kind:"message",T:()=>nu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const au=new hR;class pR extends T.MessageType{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const gR=new pR;class mR extends T.MessageType{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>$m}])}}new mR;class fR extends T.MessageType{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>$m},{no:3,name:"description",kind:"message",T:()=>ls}])}}const TR=new fR;class SR extends T.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:()=>ls}])}}const vR=new SR;class yR extends T.MessageType{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>iw}])}}new yR;class ER extends T.MessageType{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new ER;class PR extends T.MessageType{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new PR;class _R extends T.MessageType{constructor(){super("media.edge.ProducerToggleResponse",[])}}new _R;class CR extends T.MessageType{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new CR;class wR extends T.MessageType{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ls}])}}const RR=new wR;class bR extends T.MessageType{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ls}])}}const kR=new bR;class MR extends T.MessageType{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new MR;class AR extends T.MessageType{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new AR;class IR extends T.MessageType{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new IR;class DR extends T.MessageType{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const OR=new DR;class NR extends T.MessageType{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const LR=new NR;class VR extends T.MessageType{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const xR=new VR;class UR extends T.MessageType{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>qm}])}}const yp=new UR;class $R extends T.MessageType{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Ep=new $R;class BR extends T.MessageType{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Ep},{no:3,name:"screenshare",kind:"message",T:()=>Ep}])}}const HR=new BR;class FR extends T.MessageType{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Um},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>HR}])}}new FR;class qR extends T.MessageType{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Cc}])}}const jR=new qR;class GR extends T.MessageType{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Cc},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Pp=new GR;class WR extends T.MessageType{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Cc}])}}const JR=new WR;class KR extends T.MessageType{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ou=new KR;class zR extends T.MessageType{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const _p=new zR;class YR extends T.MessageType{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new YR;class QR extends T.MessageType{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new QR;class XR extends T.MessageType{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new XR;class ZR extends T.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 ZR;class eb extends T.MessageType{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new eb;class tb extends T.MessageType{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new tb;class sb extends T.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 Bl=new sb;class rb extends T.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 rb;class ib extends T.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 nb=new ib;var qi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(qi||(qi={}));var zs;(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"})(zs||(zs={}));var cu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(cu||(cu={}));var du;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(du||(du={}));var cd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(cd||(cd={}));class ab extends T.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 ob=new ab;class cb extends T.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",zs,"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:()=>ob}])}}const Cl=new cb;class db extends T.MessageType{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Cl}])}}const en=new db;class lb extends T.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",zs,"STAGE_TYPE_"]}])}}const Cp=new lb;class ub extends T.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 hb=new ub;class pb extends T.MessageType{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Cl}])}}const Hl=new pb;class gb extends T.MessageType{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const wp=new gb;class mb extends T.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:()=>Tb},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const jm=new mb;class fb extends T.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",qi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const Tb=new fb;class Sb extends T.MessageType{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>jm}])}}const Rp=new Sb;class vb extends T.MessageType{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Gm=new vb;class yb extends T.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 yb;class Eb extends T.MessageType{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Cl},{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",cd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const Pb=new Eb;class _b extends T.MessageType{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Cl},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const Cb=new _b;class wb extends T.MessageType{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>jm}])}}new wb;class Rb extends T.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new Rb;class bb extends T.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 ch=new bb;class kb extends T.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 Mb=new kb;class Ab extends T.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:()=>Mb}])}}const bp=new Ab;class Ib extends T.MessageType{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>bp},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>bp}])}}const Db=new Ib;class Ob extends T.MessageType{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const Nb=new Ob;class Lb extends T.MessageType{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Nb}])}}const Vb=new Lb;class xb extends T.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:()=>ch}])}}const Ub=new xb;class $b extends T.MessageType{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Ub}])}}const kp=new $b;class Bb extends T.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 Hb=new Bb;class Fb extends T.MessageType{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Hb}])}}new Fb;class qb extends T.MessageType{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const jb=new qb;class Gb extends T.MessageType{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>jb}])}}const Wb=new Gb;class Jb extends T.MessageType{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Yb}])}}const Kb=new Jb;class zb extends T.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:()=>ch}])}}const Yb=new zb;class Qb extends T.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 Xb=new Qb;class Zb extends T.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:()=>Xb}])}}const ek=new Zb;class tk extends T.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:()=>ch}])}}const Wm=new tk;class sk extends T.MessageType{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Wm}])}}new sk;class rk extends T.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 ik=new rk;class nk extends T.MessageType{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>ck}])}}const ak=new nk;class ok extends T.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 ck=new ok;class dk extends T.MessageType{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Jm=new dk;class lk extends T.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",du,"BROADCAST_TYPE_"]}])}}const $a=new lk;class uk extends T.MessageType{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const hk=new uk;class pk extends T.MessageType{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const gk=new pk;class mk extends T.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 fk=new mk;class Tk extends T.MessageType{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>fk}])}}const Mp=new Tk;class Sk extends T.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 Ap=new Sk;var lu;(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"})(lu||(lu={}));var Ur;(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"})(Ur||(Ur={}));class vk extends T.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 yk=new vk;class Ek extends T.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 Pk=new Ek;class _k extends T.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 Ck=new _k;class wk extends T.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 Rk=new wk;class bk extends T.MessageType{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>Ck},{no:2,name:"private",kind:"message",T:()=>Rk}])}}const kk=new bk;class Mk extends T.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 Ak=new Mk;class Ik extends T.MessageType{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ur,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ur,"STREAM_PERMISSION_TYPE_"]}])}}const Fl=new Ik;class Dk extends T.MessageType{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Fl},{no:2,name:"audio",kind:"message",T:()=>Fl},{no:3,name:"screenshare",kind:"message",T:()=>Fl}])}}const Ok=new Dk;class Nk extends T.MessageType{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>yk},{no:2,name:"plugins",kind:"message",T:()=>Pk},{no:3,name:"chat",kind:"message",T:()=>kk},{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",lu,"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",cu,"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:()=>Ak},{no:23,name:"media",kind:"message",T:()=>Ok}])}}const dh=new Nk;class Lk extends T.MessageType{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Vk=new Lk;class xk extends T.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 Uk=new xk;class $k extends T.MessageType{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>Uk}])}}const Bk=new $k;class Hk extends T.MessageType{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>dh}])}}const Km=new Hk;class Fk extends T.MessageType{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Km}])}}const qk=new Fk;class jk extends T.MessageType{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Km}])}}const Ip=new jk;class Gk extends T.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 Wk=new Gk;class Jk extends T.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Wk},{no:2,name:"patch",kind:"message",T:()=>dh}])}}new Jk;class Kk extends T.MessageType{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>dh}])}}new Kk;class zk extends T.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 zk;class Yk extends T.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 Qk=new Yk;class Xk extends T.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:()=>Qk}])}}const Zk=new Xk;class eM extends T.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 tM=new eM;class sM extends T.MessageType{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Gr}])}}const zm=new sM;class rM extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const iM=new rM;class nM extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const ql=new nM;class aM extends T.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 oM=new aM;class cM extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const jl=new cM;class dM extends T.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 dM;class lM extends T.MessageType{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}new lM;class uM extends T.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 hM=new uM;class pM extends T.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 gM=new pM;class mM extends T.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 Nc=new mM;class fM extends T.MessageType{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Gr}])}}const Lc=new fM;class TM extends T.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 SM=new TM;class vM extends T.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 Vc=new vM;class yM extends T.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 EM=new yM;class PM extends T.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 PM;class _M extends T.MessageType{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new _M;class CM extends T.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 CM;class wM extends T.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 wM;class RM extends T.MessageType{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new RM;class bM extends T.MessageType{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new bM;class kM extends T.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 MM=new kM;class AM extends T.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:()=>MM},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const IM=new AM;class DM extends T.MessageType{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>IM}])}}new DM;class OM extends T.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 NM=new OM;class LM extends T.MessageType{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>NM}])}}new LM;class VM extends T.MessageType{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new VM;class xM extends T.MessageType{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new xM;class UM extends T.MessageType{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new UM;class $M extends T.MessageType{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new $M;class BM extends T.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}])}}new BM;class HM extends T.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}])}}new HM;class FM extends T.MessageType{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new FM;class qM extends T.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}])}}new qM;class jM extends T.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 lh=new jM;class GM extends T.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:()=>lh}])}}const WM=new GM;class JM extends T.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:()=>lh}])}}const KM=new JM;class zM extends T.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:()=>lh}])}}const YM=new zM;class QM extends T.MessageType{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new QM;class XM extends T.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 ZM=new XM;class eA extends T.MessageType{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>ZM}])}}new eA;class tA extends T.MessageType{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new tA;class sA extends T.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 rA=new sA;class iA extends T.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:()=>rA}])}}const Dp=new iA;class nA extends T.MessageType{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new nA;class aA extends T.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 Op=new aA;class oA extends T.MessageType{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Np=new oA;class cA extends T.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 dA=new cA;class lA extends T.MessageType{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>dA}])}}const Gl=new lA;class uA extends T.MessageType{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const hA=new uA;class pA extends T.MessageType{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const gA=new pA;class mA extends T.MessageType{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Lp=new mA;class fA extends T.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:()=>SA},{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 Ym=new fA;class TA extends T.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:()=>yA}])}}const SA=new TA;class vA extends T.MessageType{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const yA=new vA;class EA extends T.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 PA=new EA;class _A extends T.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 CA=new _A;class wA extends T.MessageType{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Ym}])}}const Wl=new wA;class RA extends T.MessageType{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Ym}])}}const bA=new RA;class kA extends T.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",qi]}])}}const Vp=new kA;class MA extends T.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=T.PbLong.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(T.PbLong.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=T.PbLong.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=T.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 n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"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 "+T.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 n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>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=T.PbLong.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new MA;class AA extends T.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 uu=new AA;class IA extends T.MessageType{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>uu}])}}new IA;class DA extends T.MessageType{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>uu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>uu}])}}new DA;const OA=0,NA=1,LA=2,VA=3,xA=5,UA={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},$A={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},BA={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},HA={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Qm={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},FA={getUserPresets:0,updateUserPreset:1};function wc(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Xm(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const V=wc(OA,UA),je=wc(NA,$A),ks=wc(LA,BA),Ms=wc(VA,HA),mr=Xm(Qm,16777216),os=Xm(Qm,50331648),jc=wc(xA,FA);var qA=Object.defineProperty,jA=Object.getOwnPropertyDescriptor,Wr=(s,t,e,r)=>{for(var i=r>1?void 0:r?jA(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&qA(t,e,i),i},jt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(jt||{}),yt,yn;class nr{constructor(t,e){g(this,yt,void 0);g(this,yn,void 0);m(this,yt,e),m(this,yn,t)}get telemetry(){return a(this,yn).getValue("telemetry")}get logger(){return a(this,yn).getValue("logger")}getChatMessages(){return a(this,yt).sendMessagePromise(je.getMessages)}async getChatMessagesPaginated(t,e,r,i){const n={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await a(this,yt).sendMessagePromise(je.getPaginatedMessages,Zk.toBinary(n));return o.payload?tM.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,yt).sendMessage(je.sendMessageToRoom,iM.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,yt).sendMessage(je.sendMessageToPeers,oM.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 n={chatId:t,payloadType:r,payload:e};i!==void 0&&(n.pinned=i);const o=await a(this,yt).sendMessagePromise(je.editMessage,hM.toBinary(n));return Lc.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,yt).sendMessagePromise(je.deleteMessage,SM.toBinary(e));return{id:Vc.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await a(this,yt).sendMessagePromise(je.searchChannelMessages,EM.toBinary(r));return zm.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,yt).sendMessagePromise(je.pinMessage,gM.toBinary(r));return Nc.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case je.sendMessageToRoom:{r=ql.fromBinary.bind(ql),i=ql.create();break}case je.sendMessageToPeers:{r=jl.fromBinary.bind(jl),i=jl.create();break}case je.editMessage:{r=Lc.fromBinary.bind(Lc),i=Lc.create();break}case je.pinMessage:{r=Nc.fromBinary.bind(Nc),i=Nc.create();break}case je.deleteMessage:{r=Vc.fromBinary.bind(Vc),i=Vc.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,yt).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}yt=new WeakMap,yn=new WeakMap;Wr([E.trace("SocketService.getChatMessages")],nr.prototype,"getChatMessages",1);Wr([E.trace("SocketService.getChatMessagesPaginated")],nr.prototype,"getChatMessagesPaginated",1);Wr([E.trace("SocketService.sendMessageToRoom")],nr.prototype,"sendMessageToRoom",1);Wr([E.trace("SocketService.sendMessageToPeers")],nr.prototype,"sendMessageToPeers",1);Wr([E.trace("SocketService.sendMessage")],nr.prototype,"sendMessage",1);Wr([E.trace("SocketService.editMessage")],nr.prototype,"editMessage",1);Wr([E.trace("SocketService.deleteMessage")],nr.prototype,"deleteMessage",1);Wr([E.trace("SocketService.searchMessages")],nr.prototype,"searchMessages",1);function GA(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Es(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Es(e));const t={};return Object.keys(s).forEach(e=>{const r=qr.validate(e)?e:GA(e);t[r]=Es(s[e])}),t}function WA(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=qr.validate(e)?e:WA(e);t[r]=s[e]}),t}class dd extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);h(this,"status");h(this,"response");h(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(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 xp{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 n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.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,S=setTimeout(()=>f.abort(),d);c.signal=f.signal;const y=await fetch(r,c);clearTimeout(S);let P=null;const R=y.headers.get("content-type");R&&R.includes("application/json")?P=await y.json():P=await y.text();const k={};y.headers.forEach((O,x)=>{k[x]=O});const I={data:P,status:y.status,statusText:y.statusText,headers:k,config:t};if(!y.ok)throw I;return I}catch(f){if(f instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,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 JA=3,KA=30,zA=8e3;class YA{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,"userDetails");h(this,"roomDetails");h(this,"context");this.context=t;const{timeout:r=zA,retry:i=JA,retryDelay:n=KA,baseURL:o=ri.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new xp({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new xp({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var f,S,y,P,R;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 w("Unknown network error occurred","0011");if(k instanceof w||k instanceof dd)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:((S=k.config)==null?void 0:S.baseURL)||this.requests.defaults.baseURL,url:(y=k.config)==null?void 0:y.url,retries:(P=k.config)==null?void 0:P.retry,method:(R=k.config)==null?void 0:R.method,isOnline:navigator.onLine?"online":"offline"}});const I=k instanceof Error&&k.message||"Network request failed";throw new w(I,"0011"),new dd(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 QA=Object.defineProperty,XA=Object.getOwnPropertyDescriptor,ar=(s,t,e,r)=>{for(var i=r>1?void 0:r?XA(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QA(t,e,i),i};class Cs extends YA{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 getPresignedUrls(e){const r=Ta(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:n,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:n,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=Es(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=Es((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 Es(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 w("Cant fetch transcript s3 url","1801")}}}ar([E.trace("APIClient.getICEServers")],Cs.prototype,"getICEServers",1);ar([E.trace("APIClient.startLivestreaming")],Cs.prototype,"startLivestreaming",1);ar([E.trace("APIClient.stopLivestreaming")],Cs.prototype,"stopLivestreaming",1);ar([E.trace("APIClient.getActiveLivestream")],Cs.prototype,"getActiveLivestream",1);ar([E.trace("APIClient.getUserDetails")],Cs.prototype,"getUserDetails",1);ar([E.trace("APIClient.startRecording")],Cs.prototype,"startRecording",1);ar([E.trace("APIClient.stopRecording")],Cs.prototype,"updateRecording",1);ar([E.trace("APIClient.getActiveRecording")],Cs.prototype,"getActiveRecording",1);ar([E.trace("APIClient.getActiveTranscript")],Cs.prototype,"getActiveTranscript",1);let hu;function ZA(s,t){return hu=new Cs(s,t),hu}function mt(){return hu}const va={maxInvocations:5,period:1};function It(s,t){return function(e,r,i){const n=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 w(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var eI=Object.defineProperty,tI=Object.getOwnPropertyDescriptor,ws=(s,t,e,r)=>{for(var i=r>1?void 0:r?tI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&eI(t,e,i),i};const sI=["text","image","file","custom","poll"],Gc={maxInvocations:180,period:60};var X,ni,Je,En,Td,ef,fo,pu,tg;let Wt=(tg=class extends At{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,Td);g(this,fo);h(this,"messages");g(this,X,void 0);g(this,ni,void 0);g(this,Je,void 0);g(this,En,void 0);h(this,"maxTextLimit",2e3);m(this,En,t),m(this,Je,e),m(this,X,r),m(this,ni,i),this.messages=[]}get telemetry(){return a(this,En).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,n,o,c,d,l;if(t.length>this.maxTextLimit)throw new w("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,X).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new w("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new w("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new w("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,X).id),r=a(this,ni).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,X).userId)),a(this,Je).sendMessage(t,jt.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,X).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,X).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,X).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(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=mt(),{getLocation:p,putLocation:f}=await u.getPresignedUrls(t.name);await u.uploadFile(t,f);let S=[];e&&e.length>0&&(e.push(a(this,X).id),S=a(this,ni).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),S.push(a(this,X).userId)),a(this,Je).sendMessage(p,jt.IMAGE,e)}catch(u){throw new w("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,n,o,c,d;if(e&&e.length>0){if(!((r=a(this,X).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,X).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,X).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(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=mt(),{getLocation:u,putLocation:p}=await l.getPresignedUrls(t.name);await l.uploadFile(t,p);let f=[];e&&e.length>0&&(e.push(a(this,X).id),f=a(this,ni).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),f.push(a(this,X).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,Je).sendMessage(S,jt.FILE,e)}catch(l){throw new w("Error sending file message.","0500",this.logger)}}get rateLimits(){return Gc}updateRateLimits(t,e){Gc.maxInvocations=t,Gc.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,p,f,S,y,P,R,k,I,O;if(e&&e.length>0){if(!((n=a(this,X).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,X).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,X).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,X).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((p=(u=a(this,X).permissions)==null?void 0:u.chatPublic)!=null&&p.files)||!((S=(f=a(this,X).permissions)==null?void 0:f.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async x=>{try{if(typeof x=="string")return{link:x};const B=mt(),{getLocation:$,putLocation:z}=await B.getPresignedUrls(x.name);return await B.uploadFile(x,z),{link:$,type:x.type,name:x.name,size:x.size}}catch(B){throw new w("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((P=(y=t.files)!=null?y:[])==null?void 0:P.map(async x=>r(x))),images:await Promise.all((k=(R=t.images)!=null?R:[])==null?void 0:k.map(async x=>r(x))),videos:await Promise.all((O=(I=t.videos)!=null?I:[])==null?void 0:O.map(async x=>r(x)))};a(this,Je).sendMessage(JSON.stringify(i),jt.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,n,o;if(!((i=(r=a(this,X).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,X).permissions)==null?void 0:n.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,Je).editMessage(t,e,jt.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,X).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(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=mt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,Je).editMessage(t,l,jt.IMAGE)}catch(d){throw new w("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,X).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,X).permissions)==null?void 0:n.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=mt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,Je).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),jt.FILE)}catch(c){throw new w("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){a(this,Je).deleteMessage(t)}async pin(t){if(!a(this,fo,pu))throw new w("Can`t pin message without joining room","0505");try{await a(this,Je).setPinState(t,!0)}catch(e){throw new w(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,fo,pu))throw new w("Can`t unpin message without joining room","0505");try{await a(this,Je).setPinState(t,!1)}catch(e){throw new w(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,Je).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>Za.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,Je).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>Za.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,Je).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>Za.formatSocketPeerMessage(o))}},X=new WeakMap,ni=new WeakMap,Je=new WeakMap,En=new WeakMap,Td=new WeakSet,ef=function(){return a(this,En).getValue("connectionHandler")},fo=new WeakSet,pu=function(){return a(this,Td,ef).socketJoined===!0},tg);ws([E.trace("Chat.sendTextMessage"),It(Gc)],Wt.prototype,"sendTextMessage",1);ws([E.trace("Chat.sendImageMessage"),It({maxInvocations:20,period:60})],Wt.prototype,"sendImageMessage",1);ws([E.trace("Chat.sendFileMessage"),It({maxInvocations:20,period:60})],Wt.prototype,"sendFileMessage",1);ws([E.trace("Chat.sendMessage"),It({maxInvocations:180,period:60})],Wt.prototype,"sendMessage",1);ws([E.trace("Chat.editTextMessage")],Wt.prototype,"editTextMessage",1);ws([E.trace("Chat.editImageMessage")],Wt.prototype,"editImageMessage",1);ws([E.trace("Chat.editFileMessage")],Wt.prototype,"editFileMessage",1);ws([E.trace("Chat.editMessage")],Wt.prototype,"editMessage",1);ws([E.trace("Chat.deleteMessage")],Wt.prototype,"deleteMessage",1);Wt=ws([tt("0500")],Wt);var rI=Object.defineProperty,iI=Object.getOwnPropertyDescriptor,nI=(s,t,e,r)=>{for(var i=r>1?void 0:r?iI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&rI(t,e,i),i},ai,sg;const ur=(sg=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 Wt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,ai).getValue("telemetry")}get logger(){return a(this,ai).getValue("logger")}static async init(s,t,e,r){return new ur(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:sI[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 jt.TEXT:{e.message=s.payload;break}case jt.IMAGE:{e.link=s.payload;break}case jt.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case jt.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return ur.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=zm.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>ur.formatSocketPeerMessage(e))}setupEvents(){a(this,ai).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(je.sendMessageToRoom,s=>{if(!s.message)return;const t=ur.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(je.sendMessageToPeers,s=>{const t=ur.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(je.editMessage,s=>{if(!s.message)return;const t=ur.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(je.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(je.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=ur.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,sg);let Za=ur;nI([E.trace("ChatController.setupEvents")],Za.prototype,"setupEvents",1);var aI=Object.defineProperty,oI=Object.getOwnPropertyDescriptor,cI=(s,t,e,r)=>{for(var i=r>1?void 0:r?oI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aI(t,e,i),i},Sd,tf,vd,sf,Pn,_n,To,rg;let gu=(rg=class extends At{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Sd);g(this,vd);h(this,"items");g(this,Pn,void 0);g(this,_n,void 0);g(this,To,void 0);m(this,To,t),m(this,Pn,e),m(this,_n,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,vd,sf))throw new w("Can't create polls without joining room","0705");if(!a(this,Pn).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 a(this,_n).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,Pn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,_n).votePoll(t,e)}},Sd=new WeakSet,tf=function(){return a(this,To).getValue("connectionHandler")},vd=new WeakSet,sf=function(){var t;return((t=a(this,Sd,tf))==null?void 0:t.socketJoined)===!0},Pn=new WeakMap,_n=new WeakMap,To=new WeakMap,rg);gu=cI([tt("0700")],gu);var dI=Object.defineProperty,lI=Object.getOwnPropertyDescriptor,uI=(s,t,e,r)=>{for(var i=r>1?void 0:r?lI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dI(t,e,i),i},Tr,Cn,oi,ig;const tn=(ig=class{constructor(s,t,e){h(this,"polls");g(this,Tr,void 0);g(this,Cn,void 0);g(this,oi,void 0);this.polls=new gu(s,t,e),m(this,Cn,t),m(this,Tr,s),m(this,oi,e),this.setupEvents()}get telemetry(){return a(this,Tr).getValue("telemetry")}get logger(){return a(this,Tr).getValue("logger")}static async init(s,t,e){return new tn(s,t,e)}canViewPolls(){return a(this,Cn).permissions.polls.canView}setupEvents(){const s={[Ms.createPoll]:r=>{r.poll&&this.updatePoll(tn.formatSocketServicePoll(r.poll))},[Ms.updatePoll]:r=>{r.poll&&this.updatePoll(tn.formatSocketServicePoll(r.poll))},[Ms.votePoll]:r=>{r.poll&&this.updatePoll(tn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Tr).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,oi).on(r,s[r])})},e=()=>{a(this,Tr).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,oi).removeListeners(r)})};a(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 a(this,oi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=bA.fromBinary(s.payload);this.polls.items=t.map(e=>tn.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}}},Tr=new WeakMap,Cn=new WeakMap,oi=new WeakMap,ig);let rf=tn;uI([E.trace("PollController.setupEvents")],rf.prototype,"setupEvents",1);var hI=Object.defineProperty,pI=Object.getOwnPropertyDescriptor,gI=(s,t,e,r)=>{for(var i=r>1?void 0:r?pI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hI(t,e,i),i},nf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(nf||{}),wn,So,fu,ci,vo,ng;let mu=(ng=class extends At{constructor(t,e,r,i,n){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=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,So,fu).socketState}get mediaState(){return a(this,So,fu).mediaState}get meetingId(){return a(this,wn).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,ci).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new w("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=a(this,ci).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,vo).broadcastMessage("spotlight",{userId:a(this,ci).userId,currentTab:this.selfActiveTab})}},wn=new WeakMap,So=new WeakSet,fu=function(){return a(this,wn).getValue("connectionHandler")},ci=new WeakMap,vo=new WeakMap,ng);mu=gI([tt("0800")],mu);function mI(s){let t="",e=[""];const r=[e];let i=0,n=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[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var fI=Object.defineProperty,TI=Object.getOwnPropertyDescriptor,af=(s,t,e,r)=>{for(var i=r>1?void 0:r?TI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fI(t,e,i),i},yo,ag;let Fr=(ag=class extends At{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 a(this,yo).getValue("telemetry")}static async init(t,e){const r=new Fr(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(n){i.error("Error fetching active transcriptions ",n)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,n,o,c,d]]=mI(t);return{id:qr.v4(),name:c,peerId:i,userId:n,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
8
+ `).map(e=>Fr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=mt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Fr.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,ag);af([E.trace("Ai.getActiveTranscript")],Fr.prototype,"getActiveTranscript",1);Fr=af([tt("0000")],Fr);var SI=Object.defineProperty,vI=Object.getOwnPropertyDescriptor,yI=(s,t,e,r)=>{for(var i=r>1?void 0:r?vI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&SI(t,e,i),i},Sr,Rn,Et,og;const of=(og=class{constructor(s,t,e,r,i,n){h(this,"meta");h(this,"ai");g(this,Sr,void 0);g(this,Rn,void 0);h(this,"aiSocketHandler");g(this,Et,void 0);m(this,Et,s),this.meta=new mu(s,t,t.config.viewType,e,n),this.ai=r,m(this,Sr,t),m(this,Rn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Et).getValue("telemetry")}get logger(){return a(this,Et).getValue("logger")}static async init(s,t,e,r,i){const n=await Fr.init(s,t.permissions.transcriptionEnabled);return new of(s,t,e,n,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,nf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Et).getValue("peerSessionStore").on(C.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Et).getValue("peerSessionStore").on(C.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Et).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})}}),a(this,Et).getValue("peerSessionStore").on(C.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Sr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Rn).broadcastMessage("spotlight",{userId:a(this,Sr).userId,currentTab:this.meta.selfActiveTab})),a(this,Et).getValue("peerSessionStore").on(C.PEER_JOINED_INTERNAL,async s=>{a(this,Sr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Rn).broadcastToPeers("spotlight",[s.id],{userId:a(this,Sr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Et).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)}),a(this,Et).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=Fr.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);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Sr=new WeakMap,Rn=new WeakMap,Et=new WeakMap,og);let cf=of;yI([E.trace("MetaController.setupEvents")],cf.prototype,"setupEvents",1);const Ba={},or={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var y,P;const l=(P=(this==null?void 0:this.peerId)||((y=d[0])==null?void 0:y.authToken))!=null?P:"",u=`${t}-${l}`,p=this==null?void 0:this.logger;if(Ba[u]){const R=new Error(`Unsupported concurrent calls on method: ${s}.`);throw R.name="UnsupportedConcurrentMethodExecution",p==null||p.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:R.stack},locker:{methodName:s,lockName:u}}),R}Ba[u]=!0;const f=setTimeout(()=>delete Ba[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete Ba[u],clearTimeout(f)}).catch(()=>{delete Ba[u],clearTimeout(f)}),S},n}}};var EI=Object.defineProperty,PI=Object.getOwnPropertyDescriptor,Yi=(s,t,e,r)=>{for(var i=r>1?void 0:r?PI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EI(t,e,i),i},xt,yd,te,Eo,hs,Ve,Po,Tu,bn,Wc;class Jr extends At{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);g(this,Po);g(this,bn);g(this,xt,void 0);g(this,yd,void 0);g(this,te,void 0);g(this,Eo,void 0);g(this,hs,void 0);g(this,Ve,void 0);m(this,Ve,e),m(this,xt,n),m(this,yd,o),m(this,te,r),m(this,Eo,i),m(this,hs,[]),this.setupEvents()}get telemetry(){return a(this,Ve).getValue("telemetry")}get status(){return a(this,Ve).getValue("stageStatus")}setupEvents(){const e={[C.GET_STAGE_REQUESTS]:async n=>{m(this,hs,n)},[C.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,hs).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Ve).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Ve).getValue("peerSessionStore").removeListener(n,o)})};a(this,te).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,te).permissions.acceptStageRequests?(r(),a(this,xt).getStageRequests()):(i(),m(this,hs,[]),this.emit("stageAccessRequestUpdate",a(this,hs))))}),a(this,te).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new w("You do not have permission to perform this action","2001");const e=a(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,hs,e),{stageRequests:a(this,hs)}}async requestAccess(){if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new w("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new w(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,te).permissions.stageAccess===q.Allowed){N(this,bn,Wc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,xt).requestAccess(),N(this,bn,Wc).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new w("Stage is disabled","2003");a(this,xt).cancelRequestAccess(),N(this,bn,Wc).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,te).roomJoined)throw new w("Can`t grant for participant without joining room");if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new w("You do not have permission to perform this action","2001");return a(this,xt).grantAccess(e)}denyAccess(e){if(!a(this,te).roomJoined)throw new w("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new w("You do not have permission to perform this action","2001");return a(this,xt).denyAccess(e)}get peerId(){return a(this,Ve).getValue("peerId")}async join(){const e=a(this,Ve).getValue("viewType");if(this.status==="ON_STAGE")throw new w("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,te).permissions.stageAccess===q.NotAllowed)throw new w(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Ve).setValue("stageStatus","ON_STAGE",!1),await a(this,xt).joinStage(),e===Xs.Livestream){await a(this,Ve).getValue("selfController").joinRoom();return}a(this,Ve).notify("stageStatus"),a(this,te).audioEnabled&&a(this,Po,Tu).shareMic(a(this,te).audioTrack),a(this,te).videoEnabled&&a(this,Po,Tu).shareWebcam(a(this,te).videoTrack)}async leave(){if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new w("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new w(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,te).setIsPinned(!1),a(this,Ve).setValue("stageStatus","OFF_STAGE",!1),await a(this,xt).leaveStage(a(this,te).userId);try{await a(this,Ve).getValue("peerSessionStore").emitAsync(C.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Ve).notify("stageStatus")}async kick(e){if(!a(this,te).roomJoined)throw new w("Can`t kick participant without joining room","2005");if(!a(this,te).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,te).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new w("You do not have permissions for kick","2001");return a(this,xt).kick(e)}}xt=new WeakMap,yd=new WeakMap,te=new WeakMap,Eo=new WeakMap,hs=new WeakMap,Ve=new WeakMap,Po=new WeakSet,Tu=function(){return a(this,Ve).getValue("roomNodeClient")},bn=new WeakSet,Wc=async function(e){this.status!==e&&a(this,Ve).setValue("stageStatus",e)};Yi([E.trace("Stage.getStageRequests")],Jr.prototype,"getAccessRequests",1);Yi([E.trace("Stage.requestAccess")],Jr.prototype,"requestAccess",1);Yi([E.trace("Stage.cancelRequestAccess")],Jr.prototype,"cancelRequestAccess",1);Yi([E.trace("Stage.grantAccess")],Jr.prototype,"grantAccess",1);Yi([E.trace("Stage.denyAccess")],Jr.prototype,"denyAccess",1);Yi([or.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],Jr.prototype,"join",1);Yi([E.trace("Stage.leaveStage")],Jr.prototype,"leave",1);function _I(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function uh(s){switch(s){case zs.UNSPECIFIED:return"OFF_STAGE";case zs.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case zs.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case zs.OFF_STAGE:return"OFF_STAGE";case zs.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var CI=Object.defineProperty,wI=Object.getOwnPropertyDescriptor,RI=(s,t,e,r)=>{for(var i=r>1?void 0:r?wI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CI(t,e,i),i},vr,Xt,yr,_o,rt;class df{constructor(t,e,r,i,n){h(this,"stage");g(this,vr,void 0);g(this,Xt,void 0);g(this,yr,void 0);g(this,_o,0);g(this,rt,void 0);m(this,rt,t),this.stage=new Jr(t,i,n,e,r),m(this,yr,e),m(this,vr,i),m(this,Xt,n),this.setupEvents()}get telemetry(){return a(this,rt).getValue("telemetry")}get logger(){return a(this,rt).getValue("logger")}setupEvents(){a(this,rt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,yr).on(V.grantStageAccess,()=>{a(this,vr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,yr).on(V.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,vr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,yr).on(V.denyStageAccess,()=>{a(this,vr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,yr).on(V.getStageRequests,async t=>{var r;if(a(this,vr).permissions.stageAccess!==q.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,rt).getValue("peerSessionStore").emitAsync(C.GET_STAGE_REQUESTS,e),a(this,_o)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),m(this,_o,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Xt).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&&a(this,rt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=uh(t.stageType),r=a(this,rt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,rt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,rt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Xt).joined.get(t.peerId),r=a(this,Xt).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,rt).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:a(this,Xt).viewMode,page:a(this,Xt).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&&a(this,rt).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:a(this,Xt).viewMode,page:a(this,Xt).currentPage});break}a(this,rt).getValue("peerSessionStore").emit(C.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}vr=new WeakMap,Xt=new WeakMap,yr=new WeakMap,_o=new WeakMap,rt=new WeakMap;RI([E.trace("Stage.setupEvents")],df.prototype,"setupEvents",1);var bI=Object.defineProperty,kI=Object.getOwnPropertyDescriptor,hh=(s,t,e,r)=>{for(var i=r>1?void 0:r?kI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bI(t,e,i),i},di,Ns,Co,wo,li,cg;let ho=(cg=class extends Sa{constructor(t,e,r,i){const n=t.getValue("logger");super(n);h(this,"name");h(this,"icon");h(this,"id");h(this,"permissions");g(this,di,void 0);g(this,Ns,void 0);g(this,Co,void 0);g(this,wo,void 0);g(this,li,void 0);h(this,"active");h(this,"enabledBy");m(this,Co,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,m(this,wo,e.component),this.permissions=e.permissions,m(this,di,i),m(this,Ns,r),this.active=!1,this.enabledBy=""}get component(){return a(this,wo)}get telemetry(){return a(this,Co).getValue("telemetry")}set activePluginsStore(t){m(this,Ns,t)}activateForSelf(){m(this,li,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){m(this,li,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!a(this,Ns))throw new w("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,Ns).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,di).id}),this.enabledBy=a(this,di).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==a(this,di).id)return;if(!a(this,Ns))throw new w("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,li)?new Date().getTime()-a(this,li).getTime():0;await a(this,Ns).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},di=new WeakMap,Ns=new WeakMap,Co=new WeakMap,wo=new WeakMap,li=new WeakMap,cg);hh([E.trace("Plugin.activatePlugin")],ho.prototype,"activate",1);hh([E.trace("Plugin.deactivatePlugin")],ho.prototype,"deactivate",1);ho=hh([tt("0600")],ho);var Ae,ui;class lf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();g(this,Ae,void 0);g(this,ui,void 0);h(this,"onAddEvent");h(this,"onDeleteEvent");h(this,"onClearEvent");m(this,Ae,new Sa(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,m(this,ui,new Map)}emit(e,...r){return a(this,Ae).emit(e,...r)}on(e,r){return a(this,Ae).on(e,r)}addListener(e,r){return a(this,Ae).addListener(e,r)}off(e,r){return a(this,Ae).off(e,r)}once(e,r){return a(this,Ae).once(e,r)}prependListener(e,r){return a(this,Ae).prependListener(e,r)}prependOnceListener(e,r){return a(this,Ae).prependOnceListener(e,r)}removeListener(e,r){return a(this,Ae).removeListener(e,r)}removeAllListeners(e){return a(this,Ae).removeAllListeners(e)}listeners(e){return a(this,Ae).listeners(e)}listenerCount(e){return a(this,Ae).listenerCount(e)}getMaxListeners(){return a(this,Ae).getMaxListeners()}setMaxListeners(e){return a(this,Ae).setMaxListeners(e)}eventNames(){return a(this,Ae).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,ui).set(e,o),r.on("*",o),i&&a(this,Ae).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,ui).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Ae).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,ui).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Ae).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ae=new WeakMap,ui=new WeakMap;class Up extends lf{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 MI=Object.defineProperty,AI=Object.getOwnPropertyDescriptor,II=(s,t,e,r)=>{for(var i=r>1?void 0:r?AI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&MI(t,e,i),i};let Su=class{constructor(s){h(this,"all");h(this,"active");this.all=new Up(s),this.active=new Up(s)}};Su=II([tt("0600")],Su);var DI=Object.defineProperty,OI=Object.getOwnPropertyDescriptor,NI=(s,t,e,r)=>{for(var i=r>1?void 0:r?OI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&DI(t,e,i),i},Zt,kn,Er,hi,Ed,hf,Ro,vu,bo,yu,ko,Eu,dg;const uf=(dg=class{constructor(s,t,e,r){g(this,Ed);g(this,Ro);g(this,bo);g(this,ko);h(this,"plugins");g(this,Zt,void 0);g(this,kn,void 0);g(this,Er,void 0);g(this,hi,null);m(this,Er,s),this.plugins=t,m(this,kn,e),m(this,Zt,r),this.setupEvents()}get telemetry(){return a(this,Er).getValue("telemetry")}get logger(){return a(this,Er).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new Su(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(ru,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(p=>{const f=new ho(s,p,c,e);o.all.add(f)});const d=new uf(s,o,r,c);return c?N(l=d,ko,Eu).call(l):N(u=d,Ed,hf).call(u),d}cleanup(){N(this,Ro,vu).call(this)}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)}),a(this,Er).getValue("peerSessionStore").onAsync(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!a(this,Zt)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await N(this,bo,yu).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},Zt=new WeakMap,kn=new WeakMap,Er=new WeakMap,hi=new WeakMap,Ed=new WeakSet,hf=function(){const s=a(this,Er).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,Zt))try{m(this,Zt,await a(this,kn).create(ru,!0)),N(this,Ro,vu).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,Zt)}),N(this,ko,Eu).call(this),this.logger.info("Active plugins store created after socket connected"),await N(this,bo,yu).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(C.SOCKET_STATE_UPDATE,t),m(this,hi,()=>{s.off(C.SOCKET_STATE_UPDATE,t)})},Ro=new WeakSet,vu=function(){a(this,hi)&&(a(this,hi).call(this),m(this,hi,null))},bo=new WeakSet,yu=async function(){try{await a(this,kn).refresh(a(this,Zt).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,Zt).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},ko=new WeakSet,Eu=function(){a(this,Zt).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},dg);let pf=uf;NI([E.trace("PluginController.setupEvents")],pf.prototype,"setupEvents",1);var Mo;class LI{constructor(t){h(this,"mediaJoined");h(this,"socketJoined");h(this,"socketJoinAttempted");h(this,"mediaJoinAttempted");h(this,"socketState");h(this,"mediaState");g(this,Mo,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,Mo,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&&(a(this,Mo).getValue("peerSessionStore").emit(C.SOCKET_STATE_UPDATE,r),this.socketState=r)}}Mo=new WeakMap;var VI=Object.defineProperty,xI=Object.getOwnPropertyDescriptor,Rc=(s,t,e,r)=>{for(var i=r>1?void 0:r?xI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&VI(t,e,i),i};const $p="Cannot start recording: another recording is already in progress.";var Mn,An,In,Jc,lg;let Wi=(lg=class extends At{constructor(t,e){const r=t.getValue("logger");super(r);g(this,In);g(this,Mn,void 0);g(this,An,void 0);h(this,"recordingPeerIds",[]);h(this,"recordings",[]);m(this,An,t),m(this,Mn,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 a(this,An).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,Mn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new w("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 w($p,"1005");try{const e=mt(),{recording:r={}}=a(this,An).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::start::recording_failed_to_start",{error:e}),e instanceof dd&&e.status===409?new w($p,"1005"):new w("Error while starting recording","1000",this.logger)}}async stop(t){await N(this,In,Jc).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await N(this,In,Jc).call(this,"pause",["RECORDING"],t)}async resume(t){await N(this,In,Jc).call(this,"resume",["PAUSED"],t)}},Mn=new WeakMap,An=new WeakMap,In=new WeakSet,Jc=async function(t,e,r){if(!a(this,Mn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new w("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new w("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await mt().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new w("Error while stopping recording","1000",this.logger)}})},lg);Rc([E.trace("Recording.start")],Wi.prototype,"start",1);Rc([E.trace("Recording.stop")],Wi.prototype,"stop",1);Rc([E.trace("Recording.stop")],Wi.prototype,"pause",1);Rc([E.trace("Recording.stop")],Wi.prototype,"resume",1);Wi=Rc([tt("1000")],Wi);var UI=Object.defineProperty,$I=Object.getOwnPropertyDescriptor,BI=(s,t,e,r)=>{for(var i=r>1?void 0:r?$I(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&UI(t,e,i),i},pi;class gf{constructor(t,e,r){h(this,"recording");h(this,"room");g(this,pi,void 0);m(this,pi,t),this.recording=new Wi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,pi).getValue("telemetry")}get logger(){return a(this,pi).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case qi.BROWSER:e="BROWSER";break;case qi.COMPOSITE:e="COMPOSITE";break;case qi.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,pi).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)})}}pi=new WeakMap;BI([E.trace("RecordingController.setupEvents")],gf.prototype,"setupEvents",1);var gi;class HI{constructor(t){g(this,gi,void 0);m(this,gi,t)}hasFeature(t){return a(this,gi).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,gi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,gi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}gi=new WeakMap;class ph{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=me,this.callStats=i}static init(t){return new ph(t.getValue("authToken"),t.getValue("logger"),new HI(t),t.getValue("callstats"))}}class gh{constructor(t){h(this,"internals");this.internals=t}static async init(t){const e=ph.init(t);return new gh(e)}}var FI=Object.defineProperty,qI=Object.getOwnPropertyDescriptor,Dt=(s,t,e,r)=>{for(var i=r>1?void 0:r?qI(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FI(t,e,i),i},Le,pe,de,Ls,Ut,Ao,Ce;class Tt extends Sa{constructor(e,r,i=ld,n=!0){const o=e.getValue("logger");super(o);g(this,Le,void 0);g(this,pe,void 0);g(this,de,void 0);g(this,Ls,void 0);g(this,Ut,void 0);g(this,Ao,void 0);g(this,Ce,void 0);h(this,"audioUpdateInProgress");h(this,"videoUpdateInProgress");m(this,Ce,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,m(this,Le,new mf(e,r)),m(this,pe,new h0(e,a(this,Le),void 0,i)),m(this,de,new v0(e,a(this,Le),void 0,i)),m(this,Ut,new f0(a(this,Ce),a(this,Le))),m(this,Ls,new g0(e,a(this,Le))),m(this,Ao,n),a(this,pe).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,pe).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,de).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,de).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,Ut).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Ce).getValue("telemetry")}set context(e){m(this,Ce,e)}async onVisibilityChange(){a(this,Ce).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Ce).getValue("callstats").browserBackgrounded():(a(this,Ce).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Ce).getValue("callstats").audioOn():a(this,Ce).getValue("callstats").audioOff(),r?a(this,Ce).getValue("callstats").videoOn():a(this,Ce).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,Le).getAudioAndVideoTrack(a(this,pe).userSelectedDevice,a(this,de).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,Le).getAudioTrack(!1,a(this,pe).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Le).getVideoTrack(a(this,de).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Ce).getValue("callstats").audioOff(),r&&!n&&a(this,Ce).getValue("callstats").videoOff(),await a(this,pe).setMediaTrack(i),await a(this,de).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Ce).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Ce).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,Ls).currentDevice)!=null&&o.deviceId&&a(this,Ce).getValue("callstats").selectedDevice("SPEAKER",a(this,Ls).currentDevice),a(this,Le).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,pe).currentDevice,video:a(this,de).currentDevice,speaker:a(this,Ls).currentDevice}}get permissions(){return a(this,Le).permissions}getAllDevices(){return a(this,Le).getAvailableDevices()}getDeviceById(e,r){return a(this,Le).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,pe).mediaTrack}get audioTrack(){return a(this,pe).transformedMediaTrack}get audioEnabled(){return a(this,pe).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,pe).enableTrack(!1,e):await a(this,pe).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,pe).mediaTrack&&!a(this,pe).isCustomTrack?a(this,pe).muteTrack():a(this,pe).disableTrack()}getAudioDevices(e){return a(this,Le).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,pe).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ce).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,Ls).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 a(this,Ls).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ce).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 a(this,de).mediaTrack}get videoTrack(){return a(this,de).transformedMediaTrack}get videoEnabled(){return a(this,de).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,de).enableTrack(!1,e):await a(this,de).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,de).disableTrack()}getVideoDevices(e){return a(this,Le).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,de).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ce).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,de).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,Ut).audioMediaTrack,video:a(this,Ut).videoMediaTrack}}get screenShareEnabled(){return a(this,Ut).trackEnabled}async enableScreenShare(){await a(this,Ut).enableScreenShare()}async disableScreenShare(){a(this,Ut).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,Ut).updateConstraints(e)}getSpeakerDevices(e){return a(this,Le).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,pe).addMiddleware(e)}removeAudioMiddleware(e){return a(this,pe).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,pe).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,de).addMiddleware(e)}removeVideoMiddleware(e){return a(this,de).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,de).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,de).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,pe).disableTrack(),a(this,de).disableTrack(),a(this,de).terminateMiddlewareWebWorker(),a(this,Ut).disableScreenShare(),a(this,Le).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,Ao))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!ld(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(){a(this,pe).disableTrack()}removeVideoTrack(){a(this,de).disableTrack(),a(this,de).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Le=new WeakMap,pe=new WeakMap,de=new WeakMap,Ls=new WeakMap,Ut=new WeakMap,Ao=new WeakMap,Ce=new WeakMap;Dt([E.trace("MediaHandler.setupStreams")],Tt.prototype,"setupStreams",1);Dt([E.trace("MediaHandler.enableAudio")],Tt.prototype,"enableAudio",1);Dt([E.trace("MediaHandler.disableAudio")],Tt.prototype,"disableAudio",1);Dt([E.trace("MediaHandler.setAudioDevice")],Tt.prototype,"setAudioDevice",1);Dt([E.trace("MediaHandler.enableVideo")],Tt.prototype,"enableVideo",1);Dt([E.trace("MediaHandler.disableVideo")],Tt.prototype,"disableVideo",1);Dt([E.trace("MediaHandler.setVideoDevice")],Tt.prototype,"setVideoDevice",1);Dt([E.trace("MediaHandler.updateVideoConstraints")],Tt.prototype,"updateVideoConstraints",1);Dt([E.trace("MediaHandler.enableScreenShare")],Tt.prototype,"enableScreenShare",1);Dt([E.trace("MediaHandler.disableScreenShare")],Tt.prototype,"disableScreenShare",1);Dt([E.trace("MediaHandler.updateScreenshareConstraints")],Tt.prototype,"updateScreenshareConstraints",1);Dt([E.trace("MediaHandler.destruct")],Tt.prototype,"destruct",1);Dt([E.trace("MediaHandler.onDeviceChange")],Tt.prototype,"onDeviceChange",1);function xc(s,t,e){switch(!0){case me.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case me.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case me.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 jI=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function ld(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=me._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:jI.some(i=>t==null?void 0:t.includes(i))}async function GI(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=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<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}var mi,Io;class WI{constructor(t){g(this,mi,void 0);g(this,Io,void 0);m(this,Io,t)}get logger(){return a(this,Io).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,mi))try{Bc.clearInterval(a(this,mi)),m(this,mi,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"),n=await Promise.all(t==null?void 0:t.map(f=>f({canvas:i,WorkerTimers:Bc})));if(r.disablePerFrameCanvasRendering){const S=i.captureStream().getVideoTracks()[0];return Object.defineProperty(S,"originalSettings",{value:e.getSettings()}),S}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<n.length;f+=1)typeof n[f]=="function"&&await n[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,mi,Bc.setInterval(l,50))},!1);const p=i.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:e.getSettings()}),p}}mi=new WeakMap,Io=new WeakMap;const JI={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}}},KI=[[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}]]],zI=(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=KI,n=i.map(([p])=>p).sort((p,f)=>p-f);let o=Number.MAX_VALUE,c=0;return n.forEach((p,f)=>{Math.abs(p-r)<o&&(o=Math.abs(p-r),c=f)}),i[c][1]};var Pe=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Pe||{});const YI=xC(),Zi=Es(YI.config.media);function QI(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 fi,Pd;class XI{constructor(t,e){g(this,fi,void 0);g(this,Pd,void 0);h(this,"getScreenShareConstraints",()=>{var l,u,p,f,S,y,P,R,k;const t=(l=a(this,fi))==null?void 0:l.screenshare,e=(p=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?p:1920,r=(S=(f=t==null?void 0:t.height)==null?void 0:f.max)!=null?S:1080,i=(P=(y=t==null?void 0:t.frameRate)==null?void 0:y.max)!=null?P:5,n=(k=(R=t==null?void 0:t.frameRate)==null?void 0:R.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:n,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 n,o,c,d,l,u,p;const e={},r=(n=a(this,fi))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return me.isFirefox()||me.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=a(this,fi))==null?void 0:o.video,i=ZP(JI);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});m(this,Pd,t),m(this,fi,e)}getUpdatedVideoConstraints(t){return t}}fi=new WeakMap,Pd=new WeakMap;class Jl extends Error{constructor(e,r,i){super(r);h(this,"constraints");h(this,"name");this.name=e,this.constraints=i}}class ZI{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,us=(s,t,e,r)=>{for(var i=r>1?void 0:r?t0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&e0(t,e,i),i},Dn,$t,xe,ug;let Mt=(ug=class extends ZI{constructor(t,e){super();g(this,Dn,void 0);g(this,$t,void 0);g(this,xe,void 0);m(this,xe,t),m(this,$t,new XI(t,e)),m(this,Dn,new AbortController)}get telemetry(){return a(this,xe).getValue("telemetry")}get logger(){return a(this,xe).getValue("logger")}get constraintsBuilder(){return a(this,$t)}async destruct(){var t;(t=a(this,Dn))==null||t.abort()}handlePermissionErrors(t,e){const r=xc(t,e.name,e.message);return this.permissions[t]=r,a(this,xe).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,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&&((n=d[0])!=null&&n.deviceId)&&(f=(o=d[0])==null?void 0:o.deviceId);const S={audio:a(this,$t).getAudioConstraints(u).audio,video:a(this,$t).getVideoConstraints(f).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const y=await navigator.mediaDevices.getUserMedia(S);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)});const P=y.getAudioTracks()[0];let R=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",R.label.includes("OBS Virtual")){const I=(await this.getVideoInputDevices()).find(O=>O.label.includes("OBS Virtual"));R=await this.getVideoTrack(I.deviceId)}return a(this,xe).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,xe).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:P,videoTrack:R}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new w("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",a(this,xe).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new w("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(f=>f.deviceId!==l),u=a(this,$t).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=xc("audio",p.name,p.message),S=new Jl(p.name,p.message,u);if(f==="COULD_NOT_START"){const y=r.shift();if(!y)throw S;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const P=a(this,$t).getAudioConstraints(y.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(P)}),o(y.deviceId)}throw S}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,xe).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new w(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",a(this,xe).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new w("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let n;t&&i?n=t:(d=r[0])!=null&&d.deviceId&&(n=(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[S]=(await navigator.mediaDevices.getUserMedia(p)).getVideoTracks();if(e&&typeof f!="boolean"&&typeof f.width=="object"){const{width:y,height:P}=S.getSettings(),{ideal:R}=f.width;S.applyConstraints({width:{ideal:R},height:{ideal:Math.floor(P*R/y)},frameRate:f.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(p)}),S}catch(p){const f=xc("video",p.name,p.message),S=new Jl(p.name,p.message,u);if(f==="COULD_NOT_START"){const y=r.shift();if(!y)throw S;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:p});const P=a(this,$t).getVideoConstraints(y.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(P)}),o({video:P.video})}throw S}};try{const u=a(this,$t).getVideoConstraints(n),p=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,xe).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),p}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new w(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,xe).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=xc("video",r.name,r.message),n=new Jl(r.name,r.message,e),o={video:!0};if(oC(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,$t).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,xe).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 w(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 n=((o=i.label)==null?void 0:o.toLowerCase())||"";return ld(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,p;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((p=n.label)==null?void 0:p.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const f=r(i),S=r(n);if(f&&!S)return-1;if(!f&&S)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 w("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 w("Failed to get device","1609")}}async onDeviceChange(t){if(me.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}`,n=new Set(e.map(p=>i(p))),o=await this.getAvailableDevices(),c=new Set(o.map(p=>i(p))),d={added:o.filter(p=>!n.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")&&a(this,xe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&a(this,xe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&a(this,xe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(f=>f.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,Dn).signal})}}},Dn=new WeakMap,$t=new WeakMap,xe=new WeakMap,ug);us([E.trace("WebMediaInterface.destruct")],Mt.prototype,"destruct",1);us([E.trace("WebMediaInterface.handlePermissionErrors")],Mt.prototype,"handlePermissionErrors",1);us([E.trace("WebMediaInterface.getAudioAndVideoTrack")],Mt.prototype,"getAudioAndVideoTrack",1);us([E.trace("WebMediaInterface.getAudioTrack")],Mt.prototype,"getAudioTrack",1);us([E.trace("WebMediaInterface.getVideoTrack")],Mt.prototype,"getVideoTrack",1);us([E.trace("WebMediaInterface.getScreenShareTracks")],Mt.prototype,"getScreenShareTracks",1);us([E.trace("WebMediaInterface.getAvailableDevices")],Mt.prototype,"getAvailableDevices",1);us([E.trace("WebMediaInterface.getAvailableDevicesByKind")],Mt.prototype,"getAvailableDevicesByKind",1);us([E.trace("WebMediaInterface.getDevice")],Mt.prototype,"getDevice",1);us([E.trace("WebMediaInterface.onDeviceChange")],Mt.prototype,"onDeviceChange",1);Mt=us([tt("1600")],Mt);const mf=Mt,ji={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),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.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 mh{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:mh}})}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 Bp=new mh,n0=3,a0=250;function o0(s){const t={},e=Bp.getOrCreate(t);let r=n0;function i(){return r-=1,r0(e,s.srcObject,a0).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Bp.release(t)})}async function Hp(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await o0(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,ff=(s,t,e,r)=>{for(var i=r>1?void 0:r?d0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&c0(t,e,i),i};let ud=class extends Sa{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);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=>ji.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>ji.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 w("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 w("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(me.isWebKitBased()&&!(me.isSafari()&&EC.test(me.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))}};ff([E.trace("BaseMediaHandler.unmuteTrack")],ud.prototype,"unmuteTrack",1);ud=ff([tt("1600")],ud);const Tf=ud;var l0=Object.defineProperty,u0=Object.getOwnPropertyDescriptor,fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?u0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&l0(t,e,i),i};const Kl="[Realtimekit]nonSilentDeviceLabels";class wl extends Tf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new w("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new w("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 w(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 GI(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(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse(ji.getItem(Kl,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await Hp(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return ji.setItem(Kl,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await Hp(this.logger,r)){const p=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return ji.setItem(Kl,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}fh([E.trace("AudioMediaHandler.setTransformedTrack")],wl.prototype,"setTransformedTrack",1);fh([E.trace("AudioMediaHandler.onTrackEnded")],wl.prototype,"onTrackEnded",1);fh([E.trace("AudioMediaHandler.conditionallyChangeTrack")],wl.prototype,"conditionallyChangeTrack",1);const h0=wl;var Ti;class p0{constructor(t,e){g(this,Ti,void 0);h(this,"currentDevice");h(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");h(this,"logger");h(this,"setUserPreferredDevice",t=>ji.setItem(this.userPreferredDeviceKey,t,this.logger));h(this,"getUserPreferredDevice",()=>ji.getItem(this.userPreferredDeviceKey,this.logger));m(this,Ti,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Ti).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,Ti)instanceof mf))return;let r=t;if(t||([r]=(await a(this,Ti).getAvailableDevicesByKind("audiooutput")).filter(d=>!ld(d))),!r)throw new w("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.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){}})}}Ti=new WeakMap;const g0=p0;var Do;class m0 extends Sa{constructor(e,r){const i=e.getValue("logger");super(i);h(this,"mediaInterface");h(this,"audioMediaTrack");h(this,"videoMediaTrack");g(this,Do,void 0);m(this,Do,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,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",a(this,Do).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 w("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new w("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)),me.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")}}Do=new WeakMap;const f0=m0;var T0=Object.defineProperty,S0=Object.getOwnPropertyDescriptor,Rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?S0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&T0(t,e,i),i},On,Oo;class bc extends Tf{constructor(e,r,i,n){super(e,r,i,n);g(this,On,void 0);g(this,Oo,{disablePerFrameCanvasRendering:!1});m(this,On,new WI(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new w("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new w("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 w("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 a(this,On).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Oo)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){m(this,Oo,e)}async updateConstraints(e){if(!this._mediaTrack)throw new w("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new w("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(){a(this,On).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 n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;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}}On=new WeakMap,Oo=new WeakMap;Rl([E.trace("VideoMediaHandler.setTransformedTrack")],bc.prototype,"setTransformedTrack",1);Rl([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],bc.prototype,"setVideoMiddlewareGlobalConfig",1);Rl([E.trace("VideoMediaHandler.onTrackEnded")],bc.prototype,"onTrackEnded",1);Rl([E.trace("VideoMediaHandler.conditionallyChangeTrack")],bc.prototype,"conditionallyChangeTrack",1);const v0=bc,Fp=Es(oh());var it,Si,No,Nn;const cn=class{constructor(t){g(this,it,void 0);g(this,Si,void 0);g(this,No,void 0);g(this,Nn,void 0);if(!t)throw new w("Could not load preset.","0904");m(this,it,t.config),m(this,No,t.name),m(this,Si,t.ui||Es(oh().ui)),m(this,Nn,t.permissions.plugins.config)}static fromResponse(t){return new cn(t)}static default(){return new cn(Fp)}static init(t,e=!0){return!t||e?new cn(Fp):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:a(this,Si).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,it).viewType}get livestreamViewerQualities(){return a(this,it).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,it).maxVideoStreams}get maxScreenShareCount(){return a(this,it).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,Nn)).filter(t=>a(this,Nn)[t].disabled)}get designTokens(){return a(this,Si).designTokens}get configDiff(){return a(this,Si).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,it))==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,n,o,c,d,l,u,p,f,S,y,P,R,k,I,O,x,B,$,z,he;return{audio:{enableStereo:(i=(r=(e=(t=a(this,it))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Zi.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,it))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Zi.audio.enableHighBitrate},video:{quality:(f=(p=(u=(l=a(this,it))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:p.quality)!=null?f:Zi.video.quality,frameRate:(R=(P=(y=(S=a(this,it))==null?void 0:S.media)==null?void 0:y.video)==null?void 0:P.frameRate)!=null?R:Zi.video.frameRate},screenshare:{quality:(x=(O=(I=(k=a(this,it))==null?void 0:k.media)==null?void 0:I.screenshare)==null?void 0:O.quality)!=null?x:Zi.screenshare.quality,frameRate:(he=(z=($=(B=a(this,it))==null?void 0:B.media)==null?void 0:$.screenshare)==null?void 0:z.frameRate)!=null?he:Zi.screenshare.frameRate}}}get name(){return a(this,No)}};let Pu=cn;it=new WeakMap,Si=new WeakMap,No=new WeakMap,Nn=new WeakMap;var y0=Object.defineProperty,E0=Object.getOwnPropertyDescriptor,Sf=(s,t,e,r)=>{for(var i=r>1?void 0:r?E0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&y0(t,e,i),i},Ln,Lo;class Th extends At{constructor(e,r){const i=e.getValue("logger");super(i);g(this,Ln,void 0);h(this,"state","IDLE");h(this,"playbackUrl");h(this,"ingestionCredentials");h(this,"viewerCount");g(this,Lo,void 0);m(this,Ln,r),m(this,Lo,e),this.viewerCount=0}get telemetry(){return a(this,Lo).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(!a(this,Ln).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new w("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=mt(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,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 w("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,Ln).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new w("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 w("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await mt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new w("Error while stopping livestream","1900",this.logger)}}}Ln=new WeakMap,Lo=new WeakMap;Sf([E.trace("livestream.start")],Th.prototype,"start",1);Sf([E.trace("livestream.stop")],Th.prototype,"stop",1);var P0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,C0=(s,t,e,r)=>{for(var i=r>1?void 0:r?_0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&P0(t,e,i),i},Vn,xn,Vs,ps;class vf{constructor(t,e,r){h(this,"livestream");g(this,Vn,void 0);g(this,xn,void 0);g(this,Vs,void 0);g(this,ps,void 0);m(this,ps,t),m(this,xn,e),this.livestream=new Th(t,e),m(this,Vs,r),this.setupEvents()}get logger(){return a(this,ps).getValue("logger")}get telemetry(){return a(this,ps).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=mt(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,Vs).on(V.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,xn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,Vs).on(V.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,xn).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,Vs).on(V.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Vs).on(V.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Vs).on(V.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(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,Vn,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,ps).getValue("peerSessionStore").on(C.PEER_CLOSED,t=>{t.id===a(this,Vn)&&(m(this,Vn,void 0),this.livestream.setLivestreamState("IDLE"))}),a(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})}}}),a(this,ps).getValue("peerSessionStore").on(C.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}Vn=new WeakMap,xn=new WeakMap,Vs=new WeakMap,ps=new WeakMap;C0([E.trace("LivestreamController.setupEvents")],vf.prototype,"setupEvents",1);var w0=Object.defineProperty,R0=Object.getOwnPropertyDescriptor,kc=(s,t,e,r)=>{for(var i=r>1?void 0:r?R0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&w0(t,e,i),i},Ke,Pr,_r,_d,yf;class ya{constructor({name:t,socketHandler:e,meetingId:r}){g(this,_d);h(this,"name","");g(this,Ke,{});g(this,Pr,"");g(this,_r,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});h(this,"listeners",{});this.name=t,m(this,_r,e),m(this,Pr,r)}async set(t,e,r=!0,i=!1){a(this,Ke)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,Ke)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,Ke)[t]})))}remoteSet(t,e){a(this,_r).storeInsertKeys(a(this,Pr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,Ke)[e]=r}),a(this,_r).storeInsertKeys(a(this,Pr),this.name,t)}async update(t,e,r=!0){N(this,_d,yf).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,Ke)[t]&&delete a(this,Ke)[t],e)return a(this,_r).storeDeleteKeys(a(this,Pr),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})=>{a(this,Ke)[e]&&delete a(this,Ke)[e]}),a(this,_r).storeDeleteKeys(a(this,Pr),this.name,t)}get(t){if(a(this,Ke)[t])return a(this,Ke)[t]}getAll(){return a(this,Ke)}clear(){m(this,Ke,{})}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,Ke,t)}}Ke=new WeakMap,Pr=new WeakMap,_r=new WeakMap,_d=new WeakSet,yf=function(t,e,r=!0){let i;const n=a(this,Ke)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)};kc([It(va,"rateLimitConfig")],ya.prototype,"remoteSet",1);kc([It(va,"bulkRateLimitConfig")],ya.prototype,"bulkSet",1);kc([It(va,"rateLimitConfig")],ya.prototype,"update",1);kc([It(va,"rateLimitConfig")],ya.prototype,"delete",1);kc([It(va,"bulkRateLimitConfig")],ya.prototype,"bulkDelete",1);var Cr,wr,Vo,_u,xo,es,Cd,Ef;class b0{constructor(t,e){g(this,Vo);g(this,Cd);h(this,"stores",new Map);g(this,Cr,void 0);g(this,wr,"");g(this,xo,void 0);g(this,es,new Map);m(this,Cr,e),m(this,wr,t.getValue("meetingId")),m(this,xo,t),N(this,Cd,Ef).call(this)}create(t,e=!1){if(PC.includes(t)&&!e)throw new w(`'${t}' is a reserved store name.`,"0601");const r=new ya({name:t,socketHandler:a(this,Cr),meetingId:a(this,wr)});return a(this,Cr).storeGetKeys(a(this,wr),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,es).delete(t),o(Error("Failed"))},3e3);a(this,es).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,Cr).storeGetKeys(a(this,wr),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,es).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,es).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}Cr=new WeakMap,wr=new WeakMap,Vo=new WeakSet,_u=function(){return a(this,xo).getValue("peerId")},xo=new WeakMap,es=new WeakMap,Cd=new WeakSet,Ef=function(){[ks.storeInsertKeys,ks.storeGetKeys,ks.storeDeleteKeys].forEach(t=>{a(this,Cr).on(t,async e=>{var n,o;if(e.pluginId!==a(this,wr))return;const r=(n=e.storeItems)==null?void 0:n.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===ks.storeGetKeys){const c=a(this,es).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,es).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,es).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,es).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===ks.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Vo,_u)&&i.set(c,l,!1,!0)}),t===ks.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Vo,_u)&&i.delete(c,!1,!0)}))})})};function si(s){var t,e,r,i,n,o,c,d,l,u,p,f,S;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?(n=s.mediaPermissions)==null?void 0:n.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:(S=(f=s.screenShareTracks)==null?void 0:f.video)==null?void 0:S.id}}}}:{}}var k0=Object.defineProperty,M0=Object.getOwnPropertyDescriptor,Ea=(s,t,e,r)=>{for(var i=r>1?void 0:r?M0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&k0(t,e,i),i};const A0=.8,I0=1.2;var Un,$n,Pt,vi,Fa,Rr,sn,yi,qa,wd,Pf,xs,Uo,br,Ei,ja,Us,Rd,$o,Cu,bd,_f,kd,Cf,hg;let sr=(hg=class extends At{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,vi);g(this,Rr);g(this,yi);g(this,wd);g(this,Ei);g(this,$o);g(this,bd);g(this,kd);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,Un,void 0);h(this,"supportsRemoteControl",!1);g(this,$n,void 0);h(this,"presetName");g(this,Pt,void 0);g(this,xs,void 0);g(this,Uo,void 0);g(this,br,new Map);g(this,Us,1);g(this,Rd,ah(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>I0&&a(this,Us)===1?(m(this,Us,0),a(this,Pt).getValue("peerSessionStore").emit(C.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Us)})):d<A0&&a(this,Us)===0&&(m(this,Us,1),a(this,Pt).getValue("peerSessionStore").emit(C.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Us)}))},2e3));m(this,Pt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:p,flags:f,stageStatus:S,customParticipantId:y,audioMuted:P,audioTrack:R,videoEnabled:k=!1,videoTrack:I,producers:O,metadata:x}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=p,this.flags=f,this.manualProducerConfig=mC,m(this,$n,S!=null?S:"ON_STAGE"),this.customParticipantId=y,this.audioEnabled=!P,this.audioTrack=R,this.videoEnabled=k,this.videoTrack=I,this.screenShareTracks={audio:void 0,video:void 0},this.producers=O!=null?O:[],this.presetName=x==null?void 0:x.preset_name,m(this,Un,!1),m(this,xs,r),m(this,Uo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),N(this,$o,Cu).call(this)}get stageStatus(){return a(this,$n)}get telemetry(){return a(this,Pt).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",N(this,$o,Cu)),a(this,Rr,sn)&&(this.on("audioUpdate",N(this,bd,_f)),this.on("screenShareUpdate",N(this,kd,Cf)))}async pin(){if(!a(this,yi,qa))throw new w("Can`t pin participant without joining room","1205");if(!a(this,xs).permissions.pinParticipant)throw new w("You do not have permission to pin participants.","1201");return a(this,vi,Fa).pinPeer(this.id)}async unpin(){if(!a(this,yi,qa))throw new w("Can`t unpin participant without joining room","1205");if(!a(this,xs).permissions.pinParticipant)throw new w("You do not have permission to unpin participants.","1201");return a(this,vi,Fa).pinPeer(null)}setIsPinned(t,e=!0){var i;m(this,Un,t);const r=t?"pinned":"unpinned";(i=a(this,Ei,ja))==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}}),!a(this,yi,qa))throw new w("Can`t disable participant audio without joining room","1205");if(a(this,xs).permissions.canDisableParticipantAudio)return a(this,vi,Fa).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new w("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}}),!a(this,wd,Pf))throw new w("Can`t kick participant without joining room","1205");if(a(this,xs).permissions.kickParticipant){await a(this,Pt).getValue("peerSessionStore").emitAsync(C.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new w("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}}),!a(this,yi,qa))throw new w("Can`t disable participant video without joining room","1205");if(a(this,xs).permissions.canDisableParticipantVideo)return a(this,vi,Fa).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new w("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,Uo).getUserPermissions(this.userId)}setStageStatus(t){m(this,$n,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Un)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,br).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,Rd).call(this,t)),e.observe(t)),a(this,br).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Ei,ja))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,Ei,ja))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,br).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,br).delete(t),(n=a(this,Ei,ja))==null||n.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"}},Un=new WeakMap,$n=new WeakMap,Pt=new WeakMap,vi=new WeakSet,Fa=function(){return a(this,Pt).getValue("roomNodeClient")},Rr=new WeakSet,sn=function(){return a(this,Pt).getValue("audioPlayback")},yi=new WeakSet,qa=function(){return a(this,Pt).getValue("connectionHandler").mediaJoined},wd=new WeakSet,Pf=function(){return a(this,Pt).getValue("connectionHandler").socketJoined},xs=new WeakMap,Uo=new WeakMap,br=new WeakMap,Ei=new WeakSet,ja=function(){return a(this,Pt).getValue("pip")},Us=new WeakMap,Rd=new WeakMap,$o=new WeakSet,Cu=function(){Array.from(a(this,br).keys()).forEach(this.updateVideo)},bd=new WeakSet,_f=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,Rr,sn))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,Rr,sn))==null||e.removeParticipantTrack(this.id)},kd=new WeakSet,Cf=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,Rr,sn))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,Rr,sn))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},hg);Ea([E.trace("Participant.disableAudio")],sr.prototype,"disableAudio",1);Ea([E.trace("Participant.kick")],sr.prototype,"kick",1);Ea([E.trace("Participant.disableVideo")],sr.prototype,"disableVideo",1);Ea([E.trace("Participant.getPermissions")],sr.prototype,"getPermissions",1);Ea([E.trace("Participant.setStageStatus")],sr.prototype,"setStageStatus",1);sr=Ea([tt("1200")],sr);class Ha extends lf{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},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 kr;class D0 extends Sa{constructor(e){super(e);g(this,kr,void 0);m(this,kr,new Map)}__set(e,r){return a(this,kr).set(e,r)}__clear(){return a(this,kr).clear()}get(e){return a(this,kr).get(e)}toArray(){return Array.from(a(this,kr).values())}}kr=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 wf=new N0;var L0=Object.defineProperty,V0=Object.getOwnPropertyDescriptor,Rs=(s,t,e,r)=>{for(var i=r>1?void 0:r?V0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&L0(t,e,i),i};const x0=["ACTIVE_GRID","PAGINATED","MANUAL"];var we,Bo,wu,Pi,Ga,Bn,Kc,_i,lt,pg;let Jt=(pg=class extends At{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Bo);g(this,Pi);g(this,Bn);h(this,"waitlisted");h(this,"joined");h(this,"active");h(this,"videoSubscribed");h(this,"audioSubscribed");h(this,"pinned");h(this,"all");g(this,we,void 0);g(this,_i,void 0);g(this,lt,void 0);h(this,"rateLimitConfig",{maxInvocations:5,period:1});h(this,"viewMode");h(this,"currentPage");h(this,"lastActiveSpeaker");h(this,"selectedPeers",wf);m(this,we,t),m(this,_i,e),m(this,lt,r),this.waitlisted=new Ha(i),this.joined=new Ha(i),this.videoSubscribed=new Ha(i),this.audioSubscribed=new Ha(i),this.active=this.videoSubscribed,this.pinned=new Ha(i),this.all=new D0(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,we).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,we).getValue("telemetry")}setupEvents(){a(this,we).getValue("peerSessionStore").on(C.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,we).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=a(this,we).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,we))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new w("0 <= Max active participants count limit <= 24","1203");a(this,we).setValue("maxPreferredStreams",t),a(this,Bn,Kc)&&a(this,we).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(!a(this,Pi,Ga))throw new w("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 a(this,lt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,lt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,Pi,Ga))throw new w("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;a(this,lt).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 w(`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,a(this,we).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,we).getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,we).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 w("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)))}),a(this,we).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 w("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)))}),a(this,we).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)),n=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(n,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 w(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,a(this,we).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}}}),!a(this,Bn,Kc))throw new w("Can`t disable all audio without joining room","1205");if(a(this,_i).permissions.canAllowParticipantAudio)return a(this,Bo,wu).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new w("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,Bn,Kc))throw new w("Can`t disable all video without joining room","1205");if(a(this,_i).permissions.canAllowParticipantVideo)return a(this,Bo,wu).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new w("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,we).getValue("viewType")!=="LIVESTREAM"&&!a(this,Pi,Ga))throw new w("Can`t kick all without joining room","1205");if(!a(this,_i).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new w("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,lt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,Pi,Ga))throw new w("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new w("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,lt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,lt).broadcastToPeers(t,i,e)}else await a(this,lt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,lt).getRoomPeers(t,e,r)).peers.map(cr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new w("Cannot update permissions, no valid userIDs found","1204");a(this,lt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,lt).getRoomPeersNonPaginated()}},we=new WeakMap,Bo=new WeakSet,wu=function(){return a(this,we).getValue("roomNodeClient")},Pi=new WeakSet,Ga=function(){var t;return((t=a(this,we).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Bn=new WeakSet,Kc=function(){var t;return((t=a(this,we).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},_i=new WeakMap,lt=new WeakMap,pg);Rs([E.trace("Participants.setViewMode")],Jt.prototype,"setViewMode",1);Rs([E.trace("Participants.setPage")],Jt.prototype,"setPage",1);Rs([E.trace("Participants.disableAllAudio")],Jt.prototype,"disableAllAudio",1);Rs([E.trace("Participants.disableAllVideo")],Jt.prototype,"disableAllVideo",1);Rs([E.trace("Participants.kickAll")],Jt.prototype,"kickAll",1);Rs([E.trace("Participants.broadcastMessage"),It(va,"rateLimitConfig")],Jt.prototype,"broadcastMessage",1);Rs([E.trace("Participants.getAllJoinedPeers"),It({maxInvocations:10,period:60})],Jt.prototype,"getAllJoinedPeers",1);Rs([E.trace("Participant.updatePermissions"),It({maxInvocations:1e3,period:60})],Jt.prototype,"updatePermissions",1);Rs([E.trace("Participants.getParticipantsInMeetingPreJoin")],Jt.prototype,"getParticipantsInMeetingPreJoin",1);Jt=Rs([tt("1200")],Jt);var U0=Object.defineProperty,$0=Object.getOwnPropertyDescriptor,Qi=(s,t,e,r)=>{for(var i=r>1?void 0:r?$0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&U0(t,e,i),i},Bt,ts,Hn,gg;const Rf=(gg=class{constructor(s,t,e){h(this,"participants");h(this,"self");h(this,"selectedPeers",wf);h(this,"maxSpatialLayerUpdates",new Map);h(this,"consumerPeerMap");h(this,"events");h(this,"roomSocketHandler");h(this,"context");h(this,"videoPeerConsumerMap",new Map);g(this,Bt,{mode:"ACTIVE_GRID",page:0});g(this,ts,!1);g(this,Hn,!1);h(this,"updateConsumerSpatialLayers",ah(()=>{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: ${a(this,ts)}`);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 Jt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=os,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,s=>{const t=this.participants.joined.size>0;this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.joined.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",t&&this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))})}),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:n,producerStates:o})=>this.onParticipantMediaJoined(n,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: ${a(this,ts)}, 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 n=i.producers.find(o=>o.producerId===t);n&&(n.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: ${a(this,ts)}, 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 sr(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)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,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),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,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&&a(this,Bt).mode!==s&&(a(this,Bt).mode=s),e&&a(this,Bt).page!==e&&(a(this,Bt).page=e);const{mode:r,page:i}=a(this,Bt);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),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=a(this,Bt))==null?void 0:e.mode)==="PAGINATED"&&!a(this,ts)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,Bt))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,ts)}, Delay: ${t}, Page: ${(i=a(this,Bt))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var l,u,p,f,S;if(((p=(u=(l=this.context.getValue("connectionHandler"))==null?void 0:l.mediaState)==null?void 0:u.recv)==null?void 0:p.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,ts)){m(this,Hn,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),m(this,ts,!0),m(this,Hn,!1);let s=[];this.participants.videoSubscribed.forEach(y=>{var k,I;const P=this.participants.joined.get(y.id),R=(I=(k=y.producers)==null?void 0:k.filter(O=>O.kind==="video"))!=null?I:[];P&&(R!=null&&R.length)&&R.forEach(O=>{var $,z,he,Oe;const x=((z=($=P.manualProducerConfig)==null?void 0:$.video)!=null?z:!0)&&O.kind==="video"&&!O.screenShare,B=((Oe=(he=P.manualProducerConfig)==null?void 0:he.screenshareVideo)!=null?Oe:!0)&&O.kind==="video"&&O.screenShare;(x||B)&&(O.pause||s.push(O))})}),this.participants.audioSubscribed.forEach(y=>{var k,I;const P=this.participants.joined.get(y.id),R=(I=(k=y.producers)==null?void 0:k.filter(O=>O.kind==="audio"))!=null?I:[];P&&(R!=null&&R.length)&&R.forEach(O=>{var $,z,he,Oe;const x=((z=($=P.manualProducerConfig)==null?void 0:$.audio)!=null?z:!0)&&O.kind==="audio"&&!O.screenShare,B=((Oe=(he=P.manualProducerConfig)==null?void 0:he.screenshareAudio)!=null?Oe:!0)&&O.kind==="audio"&&O.screenShare;(x||B)&&s.push(O)})}),s=gC(s,y=>y.producerId);const t=new Map;s.forEach(y=>{t.set(y.producerId,y)});const e=(f=this.roomNodeClient)==null?void 0:f.getConsumers();let r=s.filter(y=>!(e!=null&&e.has(y.producerId)));s.filter(y=>!y.consumer&&(e==null?void 0:e.has(y.producerId))).forEach(y=>{const P=e.get(y.producerId);P&&(this.logger.info(`syncConsumers: remapping existing consumer ${P.id} to producer ${y.producerId}`),this.context.getValue("peerSessionStore").emit(C.NEW_CONSUMER,{id:P.id,appData:P.appData,peerId:P.peerId}))});let n=[],o=Array.from((S=e==null?void 0:e.values())!=null?S:[]).map(y=>y.peerId);o=pC(o),o==null||o.forEach(y=>{var R;const P=this.participants.joined.get(y);if(!P){this.logger.warn(`Peer with ${y} doesn't exist in joined list but producers of it are being consumed.`);return}(R=P.producers)!=null&&R.length&&P.producers.forEach(k=>{const I=k.consumer&&e.has(k.consumer.id);!t.has(k.producerId)&&(e.has(k.producerId)||I)&&n.push(k)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(y=>y.producerId).join(", ")}], RemoveProducers: ${n.length} [${n.map(y=>y.producerId).join(", ")}]`.substring(0,5e3));const c=35,d=35;r.length>c&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${r.length}. Only adding ${c} in this run.`),r=r.slice(0,c),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"})),n.length>d&&(this.logger.warn(`syncConsumers: Too many remote producers to close consumers: ${n.length}. Only removing ${d} in this run.`),n=n.slice(0,d),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{r.length>0||n.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${n.length}.`),await this.updateConsumers(r,n),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(y){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:y})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),m(this,ts,!1)}a(this,Hn)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=Rf.formatSocketPeerMessage(s);return new sr(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===Zs.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Zs.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===Zs.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),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.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.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),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 n=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:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,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,({viewMode:s,page:t,createAllConsumers:e}={})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,Bt).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:n,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:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n}=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:n}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===n);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,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:n,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(S=>S.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:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(f=this.context)==null||f.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,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:n,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:n,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:n,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:n,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:n,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:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),n.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:n,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&&n.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=uh(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:(n=s.flags)==null?void 0:n.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})}},Bt=new WeakMap,ts=new WeakMap,Hn=new WeakMap,gg);let cr=Rf;Qi([E.trace("ParticipantController.setupEvents")],cr.prototype,"setupEvents",1);Qi([E.trace("ParticipantController.setupEvents")],cr.prototype,"setupEventsGlobal",1);Qi([E.trace("ParticipantController.processMedia")],cr.prototype,"processMedia",1);Qi([E.trace("ParticipantController.processConsumerClosed")],cr.prototype,"processConsumerClosed",1);Qi([E.trace("ParticipantController.processConsumerResumed")],cr.prototype,"processConsumerResumed",1);Qi([E.trace("ParticipantController.processConsumerPaused")],cr.prototype,"processConsumerPaused",1);Qi([E.trace("ParticipantController.processNewConsumer")],cr.prototype,"processNewConsumer",1);const Ee=Es(oh().permissions);var J,Fn,qn,Md,nt,St;const Ad=class extends At{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);g(this,nt);g(this,J,void 0);g(this,Fn,void 0);g(this,qn,void 0);g(this,Md,e=>{var l,u,p;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&lr(a(this,J).chat.private,r.private),r.public&&lr(a(this,J).chat.public,r.public),this.emit("chatUpdate")),i&&lr(a(this,J).connectedMeetings,i),c){const f=y=>{switch(y){case Ur.NONE:return q.Allowed;case Ur.ALLOWED:return q.Allowed;case Ur.NOT_ALLOWED:return q.NotAllowed;case Ur.CAN_REQUEST:return q.CanRequest;default:return}},S={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(S.audio={canProduce:f(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(S.video={canProduce:f(c.video.canProduce)}),(p=c.screenshare)!=null&&p.canProduce&&(S.screenshare={canProduce:f(c.screenshare.canProduce)}),lr(a(this,J).media,S)}n&&(lr(a(this,J).plugins,n),this.emit("pluginsUpdate")),o&&(lr(a(this,J).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&lr(a(this,J),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new w("Could not load preset permissions.","0904");m(this,qn,e),m(this,Fn,i),m(this,J,r),n&&this.setupEvents()}setupEvents(){a(this,qn).getValue("peerSessionStore").on(C.UPDATE_PERMISSIONS,a(this,Md))}static init(e,r,i){let n;return i?n=new Ad(e,i,r,!0):n=new Ad(e,Ee,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,J))==null?void 0:e.stageEnabled)||a(this,Fn)===Xs.Webinar||a(this,Fn)===Xs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,J))==null?void 0:e.acceptStageRequests)||((r=a(this,J))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,J))==null?void 0:e.stageAccess)===q.NotAllowed?q.NotAllowed:((r=a(this,J))==null?void 0:r.stageAccess)===q.CanRequest?q.CanRequest:((i=a(this,J))==null?void 0:i.stageAccess)===q.Allowed||a(this,J).media.audio.canProduce===q.Allowed||a(this,J).media.video.canProduce===q.Allowed||a(this,J).media.screenshare.canProduce===q.Allowed?q.Allowed:a(this,J).media.audio.canProduce===q.CanRequest||a(this,J).media.video.canProduce===q.CanRequest||a(this,J).media.screenshare.canProduce===q.CanRequest?q.CanRequest:q.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,J))==null?void 0:e.acceptWaitingRequests)!=null?r:Ee.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,J))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,J))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,J))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===q.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,J))==null?void 0:e.disableParticipantAudio)!=null?r:Ee.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,J))==null?void 0:e.canAcceptProductionRequests)!=null?r:Ee.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,J))==null?void 0:e.disableParticipantVideo)!=null?r:Ee.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,J))==null?void 0:e.kickParticipant)!=null?r:Ee.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,J))==null?void 0:e.pinParticipant)!=null?r:Ee.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,J))==null?void 0:e.canRecord)!=null?r:Ee.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,J))==null?void 0:e.waitingRoomType)!=null?r:Ee.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,J))==null?void 0:e.plugins)!=null?r:Ee.plugins}get polls(){var e,r;return(r=(e=a(this,J))==null?void 0:e.polls)!=null?r:Ee.polls}get canProduceVideo(){var r;const e=(r=a(this,J).media.video.canProduce)!=null?r:Ee.media.video.canProduce;return this.stageEnabled&&(a(this,nt,St)==="ACCEPTED_TO_JOIN_STAGE"||a(this,nt,St)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,nt,St)==="OFF_STAGE"||a(this,nt,St)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,J).media.screenshare.canProduce)!=null?r:Ee.media.screenshare.canProduce;return this.stageEnabled&&(a(this,nt,St)==="ACCEPTED_TO_JOIN_STAGE"||a(this,nt,St)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,nt,St)==="OFF_STAGE"||a(this,nt,St)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,J).media.audio.canProduce)!=null?r:Ee.media.audio.canProduce;return this.stageEnabled&&(a(this,nt,St)==="ACCEPTED_TO_JOIN_STAGE"||a(this,nt,St)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,nt,St)==="OFF_STAGE"||a(this,nt,St)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,J))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Ee.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,J))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Ee.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,J))==null?void 0:e.connectedMeetings)!=null?r:Ee==null?void 0:Ee.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,J))==null?void 0:e.hiddenParticipant)!=null?r:Ee.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,J).showParticipantList)!=null?e:Ee.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,J))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Ee.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,J).canEditDisplayName)!=null?e:!1}get isRecorder(){return a(this,J).isRecorder}get canSpotlight(){return a(this,J).canSpotlight}get canLivestream(){return a(this,J).canLivestream}get transcriptionEnabled(){return a(this,J).transcriptionEnabled}};let Ru=Ad;J=new WeakMap,Fn=new WeakMap,qn=new WeakMap,Md=new WeakMap,nt=new WeakSet,St=function(){return a(this,qn).getValue("stageStatus")};var _t;class bf extends At{constructor(e,r){super(r);h(this,"localMediaHandler");g(this,_t,void 0);m(this,_t,e)}async updatePermission(){var d,l;const e=(u,p)=>{this.mediaPermissions[u]=p;const f={message:this.mediaPermissions[u],kind:u};p==="DENIED"?a(this,_t).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_ERROR,f):a(this,_t).getValue("peerSessionStore").emit(C.MEDIA_PERMISSION_UPDATE,f)};if(me.getName()==="firefox")return;const r="microphone",i="camera",n=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()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,_t))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,_t))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,_t))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,_t))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,_t))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,p;if(me.init(),i&&m(this,_t,i),!this.localMediaHandler)try{let f=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)f=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:S}=navigator;this.localMediaHandler=await S.init(e)}else this.localMediaHandler=new Tt(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 S=>{if(this.populateMediaPermissionsInCallstats({message:S.message,kind:S.kind}),S.message==="NOT_REQUESTED")switch(S==null?void 0:S.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",S)}),i==null||i.getValue("peerSessionStore").on(C.MEDIA_PERMISSION_ERROR,async S=>{const{kind:y,message:P,constraints:R}=S;this.populateMediaPermissionsInCallstats({message:P,kind:y}),y==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="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:P},constraints:R,mediaPermissionsErrors:{kind:y,message:P}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:P,kind:y})}),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 S=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 S}}catch(f){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:f.name,message:f.message}})}}set context(e){m(this,_t,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})}}_t=new WeakMap;var B0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,dt=(s,t,e,r)=>{for(var i=r>1?void 0:r?H0(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&B0(t,e,i),i},jn,at,Gn,Ue,$s,Qr,$e,Ye,Wn,zc,Ie,Ne,Jn,Kn,Ho,bu,mg;let We=(mg=class extends bf{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);g(this,$s);g(this,$e);g(this,Wn);g(this,Ie);g(this,Ho);h(this,"name");h(this,"picture");h(this,"customParticipantId");h(this,"waitlistStatus");g(this,jn,void 0);g(this,at,void 0);g(this,Gn,void 0);h(this,"role");h(this,"userId");h(this,"organizationId");h(this,"supportsRemoteControl",!1);h(this,"device");g(this,Ue,void 0);h(this,"hidden",!1);h(this,"presetName");h(this,"roomState","init");g(this,Jn,new Set);g(this,Kn,new Set);m(this,Ue,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",m(this,at,r),m(this,jn,i),this.hidden=!1,m(this,Gn,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=me.isElectron(),this.device=me.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),N(this,Ho,bu).call(this)}get telemetry(){return a(this,Ue).getValue("telemetry")}get stageStatus(){return a(this,Ue).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,$e,Ye).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,Ue).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var f,S,y,P,R,k;let c=(S=(f=t.getValue("defaults"))==null?void 0:f.audio)!=null?S:!0,d=(P=(y=t.getValue("defaults"))==null?void 0:y.video)!=null?P:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new We(t,e,r,i,n),u=QI(i.mediaConstraints);lr(u,(R=t.getValue("defaults"))==null?void 0:R.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"),a(this,at).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",N(this,Ho,bu));const t=a(this,Wn,zc);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)}),a(this,Ie,Ne)&&this.audioEnabled)try{await a(this,$e,Ye).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)}),a(this,Ie,Ne)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,Ie,Ne))try{await a(this,$e,Ye).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=a(this,Wn,zc))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,Ie,Ne)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,$e,Ye).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=a(this,Ue))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,Ie,Ne)&&await a(this,$e,Ye).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,Ue))==null||e.getValue("callstats").videoOff()}),a(this,at).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,at).canProduceAudio!==q.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&&a(this,at).canProduceVideo!==q.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,at).canProduceScreenshare!==q.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,at)}get config(){return a(this,jn)}get roomJoined(){var t;return a(this,jn).viewType===Xs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Ue).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,Ie,Ne)}setName(t){if(!t)throw new w("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!==q.NotAllowed&&!(a(this,at).canProduceAudio===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,Ue))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,Ie,Ne)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,$e,Ye).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(a(this,at).canProduceVideo!==q.NotAllowed&&!(a(this,at).canProduceVideo===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,Ue))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,Ie,Ne)&&this.stageStatus==="ON_STAGE")try{await a(this,$e,Ye).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 w("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,Ie,Ne))throw new w("Can`t enable screenshare without joining room","1105");if(a(this,at).canProduceScreenshare!==q.NotAllowed&&!(a(this,at).canProduceScreenshare===q.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 a(this,$e,Ye).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 w("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,Ie,Ne)&&a(this,$e,Ye).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,Ue))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,Ie,Ne)&&await a(this,$e,Ye).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,Ue))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,Ie,Ne)&&await a(this,$e,Ye).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;m(this,Gn,t);const r=t?"pinned":"unpinned";(i=a(this,$s,Qr))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Gn)}async pin(){if(!a(this,Ie,Ne))throw new w("Can`t pin participants without joining room","1105");return this.show(),a(this,$e,Ye).pinPeer(this.id)}async unpin(){if(!a(this,Ie,Ne))throw new w("Can`t unpin participants without joining room","1105");return a(this,$e,Ye).pinPeer(null)}async hide(){if(!a(this,Ie,Ne))throw new w("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,Ie,Ne))throw new w("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,n;if(!t)throw new w("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||((n=e==null?void 0:e.speaker)==null?void 0:n.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){a(this,Ie,Ne)&&await a(this,$e,Ye).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){a(this,Ie,Ne)&&await a(this,$e,Ye).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=a(this,Wn,zc))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Jn).add(t):a(this,Kn).add(t),this.updateVideo(t),e||(i=a(this,$s,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){a(this,$s,Qr).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Jn).delete(t):(a(this,Kn).delete(t),a(this,$s,Qr).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;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=a(this,$s,Qr))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,$s,Qr))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},jn=new WeakMap,at=new WeakMap,Gn=new WeakMap,Ue=new WeakMap,$s=new WeakSet,Qr=function(){return a(this,Ue).getValue("pip")},$e=new WeakSet,Ye=function(){return a(this,Ue).getValue("roomNodeClient")},Wn=new WeakSet,zc=function(){return a(this,Ue).getValue("audioPlayback")},Ie=new WeakSet,Ne=function(){var t;return((t=a(this,Ue).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Jn=new WeakMap,Kn=new WeakMap,Ho=new WeakSet,bu=function(){Array.from(a(this,Kn)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Jn)).forEach(t=>this.updateVideo(t,!0))},mg);dt([E.trace("Self.cleanupEvents")],We.prototype,"cleanupEvents",1);dt([E.trace("Self.setupEvents")],We.prototype,"setupEvents",1);dt([E.trace("Self.setupTracks")],We.prototype,"setupTracks",1);dt([E.trace("Self.destructMediaHandler")],We.prototype,"destructMediaHandler",1);dt([E.trace("Self.removeDocumentEventListeners")],We.prototype,"removeDocumentEventListeners",1);dt([or.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],We.prototype,"enableAudio",1);dt([or.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],We.prototype,"enableVideo",1);dt([E.trace("Self.updateVideoConstraints")],We.prototype,"updateVideoConstraints",1);dt([E.trace("Self.enableScreenShare"),or.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],We.prototype,"enableScreenShare",1);dt([E.trace("Self.updateScreenshareConstraints")],We.prototype,"updateScreenshareConstraints",1);dt([or.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],We.prototype,"disableAudio",1);dt([or.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],We.prototype,"disableVideo",1);dt([or.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],We.prototype,"disableScreenShare",1);dt([E.trace("Self.setDevice")],We.prototype,"setDevice",1);We=dt([tt("1100")],We);class Sh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Sh)}}class vh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,vh)}}var Fo;class ku{constructor(t,e=!1){h(this,"pendingTasks",new Map);h(this,"nextTaskId",0);h(this,"stopping",!1);g(this,Fo,void 0);this.log=e,m(this,Fo,{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,n)=>{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),n(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 Sh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new vh)}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();a(this,Fo).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)}}}Fo=new WeakMap;function F0(s,t){const e=new Error(t);return e.name=s,e}class po extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,po):this.stack=new Error(t).stack}}class ft extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ft):this.stack=new Error(t).stack}}class fr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ft):this.stack=new Error(t).stack}}const qp=s=>new Promise(t=>setTimeout(t,s));async function kf(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=p=>{l=!0,r(p)};for(;c<n;){try{const p=await s(c,u);return e(p)}catch(p){if(d=p,l)break;if(c<n)i==="linear"?await qp(o*(c+1)):i==="exponential"&&await qp(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 Uc(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 n={audio:Uc(t),video:Uc(e)};return{sender:{audio:Uc(r),video:Uc(i)},receiver:n}}var Be;class W0{constructor(t){g(this,Be,void 0);h(this,"events");m(this,Be,t),this.events=os}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,Be).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:Pw.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,Be).sendMessagePromise(this.events.createWebRTCTransport,YC.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Um.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,Be).sendMessagePromise(this.events.produce,xw.toBinary(t))).payload,r=vR.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,Be).sendMessagePromise(this.events.consume,Iw.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=TR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,Be).sendMessagePromise(this.events.closeProducer,jw.toBinary(t))).payload,{description:r}=RR.fromBinary(e);return r}async closeConsumer(t){return(await a(this,Be).sendMessagePromise(this.events.closeConsumer,Ww.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,Be).sendMessagePromise(this.events.updateConsumersSimulcastConfig,Lw.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,Be).sendMessagePromise(this.events.hostControlPeer,Xw.toBinary(r))).payload;if(!i)return!1;const{status:n}=OR.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,Be).sendMessagePromise(this.events.hostControlAllPeers,eR.toBinary(e))).payload;if(!r)return!1;const{status:i}=LR.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,Be).sendMessagePromise(V.kickAll,Fm.toBinary(t))}async kickPeer(t){a(this,Be).sendMessagePromise(V.kick,Jm.toBinary(t))}async changeDisplayName(t){const e=(await a(this,Be).sendMessagePromise(this.events.changeDisplayName,Yw.toBinary(t))).payload;if(!e)return!1;const{status:r}=xR.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,Be).sendMessagePromise(this.events.selfJoinComplete,Cw.toBinary(t))).payload;return au.fromBinary(e)}async audioActivity(t){a(this,Be).sendMessage(this.events.audioActivity,XC.toBinary(t))}}Be=new WeakMap;var ys=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(ys||{}),qo;class bl extends et.EventEmitter{constructor(e){super();g(this,qo,void 0);m(this,qo,e),this.setMaxListeners(1/0)}get logger(){return a(this,qo).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),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((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}qo=new WeakMap;class yh extends bl{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:n,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",...n},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 n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}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 n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}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 Eh extends yh{static createFactory(t){return()=>new Eh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=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(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const S=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const y=Array.from(new Set(S).values());p.sdpFmtpLine=y.join(";")}l.push(p)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),n.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(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.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 hd extends yh{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new hd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?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 O;const S=Yt.parse(p),y=S.media[S.media.length-1],P=y.rtp.filter(x=>f.some(B=>B.name===x.codec)),R=y.fmtp.filter(x=>P.some(B=>B.payload===x.payload)),k=(O=y.rtcpFb)==null?void 0:O.filter(x=>P.some(B=>B.payload===x.payload)),I=P.map(x=>x.payload);return S.media[S.media.length-1].rtp=P,S.media[S.media.length-1].fmtp=R,S.media[S.media.length-1].rtcpFb=k,S.media[S.media.length-1].payloads=I.join(" "),Yt.write(S)},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,S=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=${S}`)}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 n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Ph extends yh{static createFactory(t){return()=>new Ph(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 n=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(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];S.push(...u.parameters);const y=[...new Set(S).values()];p.sdpFmtpLine=y.join(";")}c.push(p)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.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(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.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 jo,Ci,gs,Id,ms,hr,Go,Mu,Dd,Mf,Od,Af;class K0 extends bl{constructor(e,r){var i;super(e);g(this,ms);g(this,Go);g(this,Dd);g(this,Od);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,jo,void 0);g(this,Ci,void 0);g(this,gs,void 0);g(this,Id,void 0);this.id=r.id,this.localId=r.localId,m(this,jo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,gs,!1),this.producerId=r.producerId,this.track=r.track,m(this,Ci,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,N(this,Dd,Mf).call(this),m(this,Id,e)}get closed(){return a(this,gs)}get kind(){return this.track.kind}get paused(){return a(this,Ci)}close(e,r){a(this,gs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,ms,hr)),m(this,gs,!0),r&&(N(this,Od,Af).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,gs))throw new ft("closed");return a(this,jo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,ms,hr)),a(this,gs)){this.logger.error("consumer::pause() | Consumer closed",a(this,ms,hr));return}m(this,Ci,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,ms,hr)),a(this,gs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,ms,hr));return}m(this,Ci,!1),this.track.enabled=!0,this.safeEmit("resume")}}jo=new WeakMap,Ci=new WeakMap,gs=new WeakMap,Id=new WeakMap,ms=new WeakSet,hr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Go=new WeakSet,Mu=function(){this.logger.debug('Consumer::track "ended" event',a(this,ms,hr)),this.safeEmit("trackended")},Dd=new WeakSet,Mf=function(){this.track.addEventListener("ended",N(this,Go,Mu).bind(this))},Od=new WeakSet,Af=function(){try{this.track.removeEventListener("ended",N(this,Go,Mu)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,ms,hr),error:e})}};var ss,zn,Yn,wi,Ht,ze,Mr,Qn,Nd,Ct,zt;class z0 extends bl{constructor(e,r){var i,n;super(e);g(this,Ct);h(this,"id");h(this,"localId");g(this,ss,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");g(this,zn,void 0);g(this,Yn,void 0);g(this,wi,void 0);g(this,Ht,!1);g(this,ze,void 0);g(this,Mr,void 0);g(this,Qn,void 0);g(this,Nd,void 0);this.id=r.id,this.localId=r.localId,m(this,ze,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Mr,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),m(this,Qn,void 0),m(this,zn,r.stopTracks),m(this,Yn,r.disableTrackOnPause),m(this,wi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,ss,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,Nd,e)}get closed(){return a(this,Ht)}get track(){return a(this,ze)}get paused(){return a(this,Mr)}get maxSpatialLayer(){return a(this,Qn)}async close(e){if(a(this,Ht))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Ct,zt)),m(this,Ht,!0),this._destroyTrack(),e===go){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,ss).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,Ht))throw new ft("closed");return a(this,ss).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Ct,zt)),a(this,Ht)&&this.logger.error("Producer::pause() | Producer closed",a(this,Ct,zt)),m(this,Mr,!0),a(this,ze)&&a(this,Yn)&&(a(this,ze).enabled=!1),a(this,wi)&&a(this,ss).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Ct,zt)),a(this,Ht)){this.logger.error("Producer::resume() | Producer closed",a(this,Ct,zt));return}m(this,Mr,!1),a(this,ze)&&a(this,Yn)&&(a(this,ze).enabled=!0),a(this,wi)&&a(this,ss).replaceTrack(this.localId,a(this,ze)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Ct,zt)),a(this,Ht)){if(e&&a(this,zn))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Ct,zt),error:r})}throw new ft("closed")}else if(e&&e.readyState==="ended")throw new ft("track ended");if(e===a(this,ze)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Ct,zt));return}(!a(this,wi)||!a(this,Mr))&&await a(this,ss).replaceTrack(this.localId,e),this._destroyTrack(),m(this,ze,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,Ht))throw new ft("closed");if(this.kind!=="video")throw new po("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,ss).setMaxSpatialLayer(this.localId,e),m(this,Qn,e)}async setRtpEncodingParameters(e){if(a(this,Ht))throw new ft("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,ss).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Ct,zt)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,ze)&&a(this,ze).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,ze))try{a(this,ze).removeEventListener("ended",this._onTrackEnded),a(this,zn)&&a(this,ze).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Ct,zt),error:r})}}}ss=new WeakMap,zn=new WeakMap,Yn=new WeakMap,wi=new WeakMap,Ht=new WeakMap,ze=new WeakMap,Mr=new WeakMap,Qn=new WeakMap,Nd=new WeakMap,Ct=new WeakSet,zt=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function If(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function zl(s){return Math.random().toString(36).substring(2,2+s)}const $c=1;function jp(s){const t=s;return delete t.payload._bolt,t}function Y0(s){return s.payload&&If(s.payload)}function Q0(s){var t,e;return Y0(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var Ar,Ld,Ri;const dn=class extends et.EventEmitter{constructor(e,r,i,n){super();h(this,"channel");h(this,"queue");h(this,"serverProtocolVersion");g(this,Ar,new Map);g(this,Ld,void 0);g(this,Ri,void 0);h(this,"respond",(e,r,i=!1)=>{let n;i?n=dn.createErrorResponse(e,r):n=dn.createResponse(e,r),this.channel.send(JSON.stringify(n))});h(this,"notify",e=>{const r=dn.createNotification(e);this.channel.send(JSON.stringify(r))});h(this,"request",async e=>{const r=dn.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(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 n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,p=(l+1)*n;c.push(r.slice(u,p))}const d=qr.v4();for(let l=0;l<o;l+=1){const u=c[l],f=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,Ri).debug(`Sending message chunk over dc: ${f}`),this.channel.send(f)}}else a(this,Ri).debug(`Sending message over dc: ${r}`),this.channel.send(r)});h(this,"processMessage",e=>{var i;a(this,Ar).has(e.id)||a(this,Ar).set(e.id,[]);const r=a(this,Ar).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,Ar).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,Ar).delete(e.id);const c=JSON.parse(o);if(!c.payload||!If(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?(a(this,Ri).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(jp(e)):i.resolve(jp(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:zl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,m(this,Ld,e),m(this,Ri,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Xr=dn;Ar=new WeakMap,Ld=new WeakMap,Ri=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:zl(8),type:"REQUEST",version:$c}}}}),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:$c}}}}),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:zl(8),type:"NOTIFY",version:$c}}}}),h(Xr,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:$c}}}));const go="transport closed";var bi;const ln=class extends bl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:p}){var P,R,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,bi,void 0);m(this,bi,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=J0(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new ku(f,!0),this.handler=n(),this.handler.enableHighBitrate=(P=p==null?void 0:p.enableHighBitrate)!=null?P:!1,this.handler.enableStereo=(R=p==null?void 0:p.enableStereo)!=null?R:!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 y=3e4;this.transportConnectionPromise=new Promise(I=>{const O=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),I(!1)},y);this.once("connected",()=>{clearTimeout(O),I(!0)}),this.once("disconnect",()=>{clearTimeout(O),I(!1)}),this.once("close",()=>{clearTimeout(O),I(!1)})}),this.eventsDCReadyPromise=new Promise(I=>{this.eventsDCReadyPromiseResolver=I}),this.handler.on("@connectionstatechange",I=>{I!==this.connectionState&&(this.logger.debug(`connection state changed to ${I}`),this.connectionState=I,I==="connected"&&(this.connected=!0,this.emit("connected")),I==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(I==="failed"||I==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",I))}),this.handler.on("@icecandidate",({candidate:I})=>{this.closed||this.safeEmit("icecandidate",I)}),this.handler.on("dc_open",I=>{let O=this.datachannels.get(I.label);O||(O||(O=new Xr(a(this,bi),I,I.label,this.serverId),this.datachannels.set(I.label,O)),this.eventsDCFailureTimer=setTimeout(()=>{I.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",I.label))},5e3))}),this.handler.on("datachannel",(I,O)=>{I.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const x=this.datachannels.get(I.label);if(!x){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:I.label,message:O}});return}try{const B=JSON.parse(O);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:B.id,count:B.count,chunkIndex:B.chunkIndex,chunk:B.chunk,transprtId:this.serverId}});const $=x.processMessage(B);if(!$)return;this.logger.debug(`datachannel message with id:${B.id} on transport:${this.serverId}complete - ${JSON.stringify($)}`),this.emit(`datachannel:${I.label}`,x.label,$)}catch(B){this.logger.error("error parsing message",{error:B})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",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(go).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(go)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new ft("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:n,answer:o}=await e(r);this.setServerId(n),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 ft("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new po("not a sending Transport");if(r.readyState==="ended")throw new ft("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 fr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:f,localId:S,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:P,callback:R,sender:k,mid:I}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:O,producerId:x}=await r({offer:P,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...p||{},mid:I},codecOptions:c,producingTransportId:this.serverId}),B=await R(O);return{producerId:x,localId:B,rtpSender:k}},"Transport.produce");return this.createProducerObject({id:f,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:p,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new z0(a(this,bi),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 ft("closed");if(this.direction!=="recv")throw new po("not a receiving transport");if(!await this.transportConnectionPromise)throw new fr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,p)=>{n[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(n).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=Yt.parse(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=Yt.parse(e.sdp);return n.media=n.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:Yt.write(n)}}static parseHeaderExtensionMappings(e){const r=Yt.parse(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Yt.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Yt.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=ln.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=ln.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=ln.setCodecAndFmtpMappings(c,i,n),c=ln.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=Yt.parse(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},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 n}),r.sdp=Yt.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 n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:p,mimeType:f}=e,S=`${c}:${p}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(P,R)=>{const k=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,R(y)},5e3),I=(x,B)=>{try{if(x.readyState==="ended")clearTimeout(k),R(y);else{const $=x;$.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const z=new K0(a(this,bi),{id:r,localId:B.mid,transceiver:B,track:$,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:B.receiver,mimeType:f});this.consumers.set(r,z),z.once("close",()=>{this.consumers.delete(z.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:p,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",z),clearTimeout(k),P(z)}}catch($){this.logger.warn("error while creating consumer:",$),clearTimeout(k),R(y)}},O=this.unknownTracksMap.get(S);O?(this.logger.info(`track event already received [trackId: ${O.track.id}] [mid: ${O.transceiver.mid}]`),this.unknownTracksMap.delete(S),I(O.track,O.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,I))})}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 n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Au=ln;bi=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=yg.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 Bs,ki;class Z0{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");g(this,Bs,void 0);g(this,ki,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),m(this,Bs,t),m(this,ki,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,ki).debug(`Device::constructor() | handler given: ${e}`);else if(e=X0(a(this,ki)),e)a(this,ki).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Eh.createFactory(a(this,Bs));break;case"Safari12":this.handlerFactory=Ph.createFactory(a(this,Bs));break;case"Firefox60":this.handlerFactory=hd.createFactory(a(this,Bs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=hd.createFactory(a(this,Bs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=qr.v4();return new Au(a(this,Bs),{id:e,...t,handlerFactory:this.handlerFactory})}}Bs=new WeakMap,ki=new WeakMap;const eD=2e3;var Xn,He,Fe,Wo,Jo,Mi,Zn,Ko,ea,Ai,fs,ta,Yc,zo,Iu,Vd,Df,Yo,Du,xd,Of,Ud,Nf,$d,Lf,Bd,Vf,Hd,xf,Qo,Ou,Ir,rn;class tD extends et.EventEmitter{constructor(e,r){super();g(this,ta);g(this,zo);g(this,Vd);g(this,Yo);g(this,xd);g(this,Ud);g(this,$d);g(this,Bd);g(this,Hd);g(this,Qo);g(this,Ir);h(this,"context");g(this,Xn,void 0);g(this,He,void 0);g(this,Fe,void 0);g(this,Wo,void 0);g(this,Jo,void 0);g(this,Mi,void 0);g(this,Zn,void 0);g(this,Ko,void 0);g(this,ea,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Ai,void 0);g(this,fs,"all");this.context=e,m(this,Mi,r),m(this,Xn,new Z0(e)),m(this,Zn,new W0(r)),m(this,Ko,os),a(this,ta,Yc).mediaState={send:{state:ys.NEW},recv:{state:ys.NEW}},Ta(this.context,"forceRelay")&&m(this,fs,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,fs)}`),N(this,zo,Iu).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Mi)}get socketHandler(){return a(this,Zn)}get sendTransport(){return a(this,He)}get recvTransport(){return a(this,Fe)}get events(){return a(this,Ko)}set sendTransportConnectedCallback(e){m(this,Wo,e)}set recvTransportConnectedCallback(e){m(this,Jo,e)}async setupTransports(e){await N(this,Vd,Df).call(this,e);let r,i;e.send&&(r=N(this,Yo,Du).call(this,a(this,He)).then(n=>{try{a(this,Wo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=N(this,Yo,Du).call(this,a(this,Fe)).then(n=>{try{a(this,Jo).call(this,n)}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:n,serverId:o,direction:c}=a(this,He);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,He).close(),a(this,He).removeAllListeners(),m(this,He,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,Fe);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,Fe))==null||r.close(),(i=a(this,Fe))==null||i.removeAllListeners(),m(this,Fe,void 0)}N(this,zo,Iu).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Xn=new WeakMap,He=new WeakMap,Fe=new WeakMap,Wo=new WeakMap,Jo=new WeakMap,Mi=new WeakMap,Zn=new WeakMap,Ko=new WeakMap,ea=new WeakMap,Ai=new WeakMap,fs=new WeakMap,ta=new WeakSet,Yc=function(){return this.context.getValue("connectionHandler")},zo=new WeakSet,Iu=function(){m(this,Ai,{send:void 0,recv:void 0})},Vd=new WeakSet,Df=async function(e){var o,c,d,l,u,p,f,S;Ta(this.context,"forceRelay")&&m(this,fs,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,fs)}`);const n=await mt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&N(this,Ud,Nf).call(this,{iceServers:n,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:a(this,fs)}),e.recv&&N(this,$d,Lf).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,fs)})},Yo=new WeakSet,Du=async function(e){const{id:r,serverId:i,direction:n}=e;N(this,Bd,Vf).call(this,e);try{return await kf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new fr("Cannot reconnect closed transport");await N(this,xd,Of).call(this,e)}catch(l){if(l instanceof fr){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:n}}),e.close(),e.removeAllListeners(),o}},xd=new WeakSet,Of=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Mi).isConnected)throw new fr("Socket is not connected");if(e.connectionState==="closed")throw new fr("Transport is closed");try{await e.connect(n=>N(this,Hd,xf).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,ea).transportFailureCount[i]+=1,n.message==="ice connection failed"?new fr(n.message):n}},Ud=new WeakSet,Nf=function(e){var r,i;if(a(this,He)&&a(this,He).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,He))==null?void 0:r.id,serverId:(i=a(this,He))==null?void 0:i.serverId,type:"send"}});return}m(this,He,a(this,Xn).createTransport({...e,direction:"send"})),N(this,Ir,rn).call(this,{state:ys.NEW,direction:"send",sfuSessionId:a(this,He).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,He))},$d=new WeakSet,Lf=function(e){var r,i;if(a(this,Fe)&&a(this,Fe).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,Fe))==null?void 0:r.id,serverId:(i=a(this,Fe))==null?void 0:i.serverId,type:"recv"}});return}m(this,Fe,a(this,Xn).createTransport({...e,direction:"recv"})),N(this,Ir,rn).call(this,{state:ys.NEW,direction:"recv",sfuSessionId:a(this,Fe).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,Fe))},Bd=new WeakSet,Vf=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{N(this,Ir,rn).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{N(this,Ir,rn).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,Ai)[r];c!==void 0&&(clearTimeout(c),a(this,Ai)[r]=void 0)};switch(n){case"connected":o(),a(this,ea).lastConnectionTime=performance.now();break;case"disconnected":a(this,Ai)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await N(this,Qo,Ou).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 N(this,Qo,Ou).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,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 ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Hd=new WeakSet,xf=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?tr.SUBSCRIBER:tr.PUBLISHER},producers:[]};return a(this,Zn).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},Qo=new WeakSet,Ou=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Mi).isConnected&&a(this,ea).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,fs,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,He)}),this.context.getValue("peerSessionStore").emit(C.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,Fe)}),this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,He):a(this,Fe);N(this,Ir,rn).call(this,{state:ys.CONNECTED,direction:e,sfuSessionId:r.serverId})},Ir=new WeakSet,rn=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,ta,Yc).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(C.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,ta,Yc).mediaState[i]})};var Fd,Ft;class sD{constructor(t,e,r,i,n){g(this,Fd,void 0);g(this,Ft,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,m(this,Fd,t),m(this,Ft,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}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,Ft).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{a(this,Ft).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,Ft).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:tr.SUBSCRIBER}};return a(this,Ft).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,tw.toBinary(r)),a(this,Ft).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,Ft).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,Ft).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:tr.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=kR.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(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,Ft).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Fd=new WeakMap,Ft=new WeakMap;class _h{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Yt.parse(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var p,f;const c=_h.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:tr.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(f=n[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function rD(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}var Dr,Or,sa,Xo,Ts,qd,Hs,ra,Zo,Nu,jd,Uf,Gd,$f,Wd,Bf,Jd,Hf;class iD extends tD{constructor(e,r){super(e,r);g(this,Zo);g(this,jd);g(this,Gd);g(this,Wd);g(this,Jd);g(this,Dr,void 0);g(this,Or,void 0);g(this,sa,void 0);g(this,Xo,void 0);g(this,Ts,void 0);g(this,qd,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Hs,[]);g(this,ra,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,Xo,new _h(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,sa).clear(),m(this,Ts,new sD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,Dr)}get consumers(){return a(this,Or)}get producerIdToConsumerIdMap(){return a(this,sa)}get logger(){return this.context.getValue("logger")}reset(){m(this,Dr,new Map),m(this,Or,new Map),m(this,sa,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,N(this,jd,Uf).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_PRODUCER,o),N(this,Gd,$f).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,qd).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;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),(n=this.context.getValue("modules").e2ee)!=null&&n.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(a(this,Dr).entries()).map(([,e])=>e.close()))}async closeAllProducersLocally(){var r;const e=(r=this.sendTransport)==null?void 0:r.handler;await Promise.all(Array.from(a(this,Dr).values()).map(async i=>{try{if(e){const n=e.midTransceiverMap.get(i.localId);n&&(await n.sender.replaceTrack(null),n.direction="inactive")}}catch(n){this.logger.warn("closeAllProducersLocally: failed to deactivate transceiver",{producer:{id:i.id,kind:i.kind,appData:i.appData},error:n})}await i.close(go)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,ra)||clearTimeout(a(this,ra)),m(this,Hs,a(this,Hs).concat(e)),await N(this,Zo,Nu).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Ts))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,Ts).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Or).keys()))}async switchConsumersToLayer(e,r){a(this,Ts).switchConsumersToLayer(e,r)}}Dr=new WeakMap,Or=new WeakMap,sa=new WeakMap,Xo=new WeakMap,Ts=new WeakMap,qd=new WeakMap,Hs=new WeakMap,ra=new WeakMap,Zo=new WeakSet,Nu=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Hs).splice(0,a(this,Hs).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,N(this,Wd,Bf).bind(this),a(this,Ts).negotiate.bind(a(this,Ts)));if(o.forEach(N(this,Jd,Hf).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,Hs,a(this,Hs).concat(d)),m(this,ra,setTimeout(N(this,Zo,Nu).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=rD(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},jd=new WeakSet,Uf=function(e){return a(this,Xo).create(e)},Gd=new WeakSet,$f=function(e,r){e.on("close",async(i,n)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==go){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:tr.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"}}),n({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"}})}),a(this,Dr).set(e.id,e)},Wd=new WeakSet,Bf=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Ts).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Jd=new WeakSet,Hf=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,Or).delete(e.id),this.context.getValue("peerSessionStore").emit(C.CONSUMER_CLOSED,{id:e.id})}),a(this,Or).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 ec,tc,sc,ia,na,aa,rc,ic,oa,ut,rs,is,Ii,Di,Fs,nc,Kd,Ff,zd,qf,Yd,jf,Qd,Gf;const Xd=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,Kd);g(this,zd);g(this,ec,void 0);g(this,tc,void 0);g(this,sc,void 0);g(this,ia,void 0);g(this,na,void 0);g(this,aa,void 0);g(this,rc,void 0);g(this,ic,void 0);g(this,oa,void 0);g(this,ut,void 0);g(this,rs,void 0);g(this,is,!1);g(this,Ii,0);g(this,Di,0);g(this,Fs,[]);g(this,nc,void 0);m(this,ia,t),m(this,ut,t),m(this,ec,e),m(this,tc,r),m(this,sc,i),m(this,na,n),m(this,aa,o),m(this,rc,c),m(this,ic,d),m(this,oa,l),m(this,nc,u),m(this,rs,t/2)}get voiceDetected(){return a(this,is)}processAudioChunk(t){var o,c;const e=N(o=Xd,Yd,jf).call(o,t),r=N(c=Xd,Qd,Gf).call(c,t);return N(this,Kd,Ff).call(this,e),e/a(this,rs)>a(this,oa)&&e>a(this,ut)&&r>a(this,ec)?(m(this,Ii,a(this,Ii)+1),m(this,Di,a(this,sc)),a(this,Ii)>=a(this,tc)&&m(this,is,!0)):(m(this,Ii,0),a(this,Di)>0?m(this,Di,a(this,Di)-1):a(this,is)&&m(this,is,!1),a(this,is)||N(this,zd,qf).call(this,e)),{energy:e,isVoice:a(this,is)}}reset(){m(this,is,!1),m(this,Ii,0),m(this,Di,0),m(this,ut,a(this,ia)),m(this,rs,a(this,ia)/2),m(this,Fs,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,ut),backgroundNoiseEnergy:a(this,rs),energyRatioThreshold:a(this,oa)}}};let Wa=Xd;ec=new WeakMap,tc=new WeakMap,sc=new WeakMap,ia=new WeakMap,na=new WeakMap,aa=new WeakMap,rc=new WeakMap,ic=new WeakMap,oa=new WeakMap,ut=new WeakMap,rs=new WeakMap,is=new WeakMap,Ii=new WeakMap,Di=new WeakMap,Fs=new WeakMap,nc=new WeakMap,Kd=new WeakSet,Ff=function(t){a(this,is)?m(this,ut,a(this,aa)*a(this,ut)+(1-a(this,aa))*t):m(this,ut,a(this,na)*a(this,ut)+(1-a(this,na))*a(this,rs)),m(this,ut,Math.max(a(this,rc),Math.min(a(this,ic),a(this,ut))))},zd=new WeakSet,qf=function(t){if(t<a(this,ut)*1.2)if(a(this,Fs).push(t),a(this,Fs).length>a(this,nc)&&a(this,Fs).shift(),a(this,Fs).length>=10){const e=[...a(this,Fs)].sort((i,n)=>i-n),r=Math.floor(e.length/2);m(this,rs,e[r])}else m(this,rs,.95*a(this,rs)+.05*t)},Yd=new WeakSet,jf=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Qd=new WeakSet,Gf=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(Wa,Yd),g(Wa,Qd);var ac;class Gp{constructor(t){h(this,"RNAudioSampleHandler");g(this,ac,void 0);m(this,ac,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 a(this,ac).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()}}ac=new WeakMap;var oc;class Wp{constructor(t){h(this,"audioContext");h(this,"analyser");g(this,oc,void 0);m(this,oc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,oc).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)}}oc=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 qs,js,Gs,cc,ca,da,Nr,Oi,la,Ni,Ws,Ss,Zd,Wf,dc,Lu,el,Jf,tl,Kf;const no=class{constructor(t,e){g(this,Zd);g(this,el);g(this,qs,void 0);g(this,js,void 0);g(this,Gs,void 0);g(this,cc,void 0);g(this,ca,void 0);g(this,da,void 0);g(this,Nr,void 0);g(this,Oi,void 0);g(this,la,void 0);g(this,Ni,void 0);g(this,Ws,void 0);g(this,Ss,void 0);this.reportRequest=e,m(this,Ni,t),m(this,da,new Wa);const{isReactNative:r}=navigator;m(this,Ws,r?new Gp(a(this,Ni)):new Wp(a(this,Ni))),m(this,Ss,r?nD:Bc)}get logger(){return a(this,Ni).getValue("logger")}set producerId(t){m(this,Gs,t)}set audioTrack(t){m(this,cc,t),a(this,Ws)instanceof Wp&&(a(this,Ws).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Gs)}`),a(this,qs)&&a(this,Ss).clearInterval(a(this,qs)),m(this,qs,a(this,Ss).setInterval(async()=>{var i;if(!a(this,cc)||!a(this,Gs))return;const{energy:t}=N(this,Zd,Wf).call(this),e=N(i=no,dc,Lu).call(i,t);let r=.9;a(this,la)!==e&&a(this,la)?r=.9:e?r=.3:r=.5,m(this,ca,(a(this,ca)||0)*(1-r)+t*r)},aD)),a(this,js)&&a(this,Ss).clearInterval(a(this,js)),m(this,js,a(this,Ss).setInterval(N(this,el,Jf).bind(this),oD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Gs)}`),a(this,qs)&&(a(this,Ss).clearInterval(a(this,qs)),m(this,qs,void 0)),a(this,js)&&(a(this,Ss).clearInterval(a(this,js)),m(this,js,void 0))}catch(t){}a(this,da).reset(),a(this,Ws)instanceof Gp&&a(this,Ws).stop()}};let Ja=no;qs=new WeakMap,js=new WeakMap,Gs=new WeakMap,cc=new WeakMap,ca=new WeakMap,da=new WeakMap,Nr=new WeakMap,Oi=new WeakMap,la=new WeakMap,Ni=new WeakMap,Ws=new WeakMap,Ss=new WeakMap,Zd=new WeakSet,Wf=function(){var o;const{samples:t}=a(this,Ws),{energy:e,isVoice:r}=a(this,da).processAudioChunk(t),i=N(o=no,tl,Kf).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Nr)||i<a(this,Nr))&&m(this,Nr,i),(!a(this,Oi)||i>a(this,Oi))&&m(this,Oi,i),{energy:(i-a(this,Nr))/(a(this,Oi)-a(this,Nr))*10||0,isVoice:r})},dc=new WeakSet,Lu=function(t){return t<5},el=new WeakSet,Jf=function(t=a(this,ca)){var r;if(!a(this,Gs)||!t)return;const e={producerId:a(this,Gs),energy:Math.round(t),silent:N(r=no,dc,Lu).call(r,t)};m(this,la,e.silent),this.reportRequest(e)},tl=new WeakSet,Kf=function(t){const e=Math.log10(t);return Math.round(e)},g(Ja,dc),g(Ja,tl);var cD=Object.defineProperty,dD=Object.getOwnPropertyDescriptor,oe=(s,t,e,r)=>{for(var i=r>1?void 0:r?dD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cD(t,e,i),i},lc,uc,Xe,H,sl,ot,Li,Vi,xi,hc,wt,vs,Ze,ht,Js,Zr,rl,zf,il,Yf,nl,Qf,pc,Vu,al,Xf,ol,Zf,ct,vt,Ui,Ka,cl,eT,dl,tT,ll,sT;class se{constructor(t,e){g(this,Js);g(this,rl);g(this,il);g(this,nl);g(this,pc);g(this,al);g(this,ol);g(this,ct);g(this,Ui);g(this,cl);g(this,dl);g(this,ll);h(this,"context");h(this,"authToken");h(this,"e2ee");g(this,lc,void 0);g(this,uc,void 0);g(this,Xe,void 0);g(this,H,void 0);g(this,sl,void 0);g(this,ot,void 0);g(this,Li,void 0);g(this,Vi,void 0);g(this,xi,void 0);g(this,hc,void 0);g(this,wt,null);g(this,vs,void 0);g(this,Ze,void 0);g(this,ht,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,Xe,r),m(this,Li,!1),m(this,H,new iD(t,r)),m(this,ot,a(this,H).events),m(this,vs,new Set),m(this,Ze,new Map),m(this,Vi,!1),m(this,xi,new ku(t.getValue("logger"))),m(this,ht,new Ja(this.context,a(this,H).socketHandler.audioActivity.bind(a(this,H).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,hc,ah(async()=>{if(!a(this,Js,Zr).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,uc),a(this,lc),!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 a(this,Js,Zr).mediaJoined}set mediaJoined(t){a(this,Js,Zr).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,H).closeAllProducers(),a(this,H).closeAllConsumers(),a(this,Ze).clear(),a(this,vs).clear(),m(this,wt,null),t&&a(this,xi).stop(),a(this,H).stopAllTransports(),a(this,H).reset(),t&&m(this,xi,new ku)}async joinRoom(t,e,r=!1,i={}){a(this,Js,Zr).mediaJoinAttempted=!0,m(this,Li,!0);try{return await a(this,xi).push(()=>N(this,rl,zf).call(this,t,e,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(t,e,r=!1,i={}){return a(this,wt)?a(this,wt):(m(this,wt,(async()=>{try{await N(this,pc,Vu).call(this,t,e,r,i)}catch(n){throw m(this,wt,null),n}})()),a(this,wt))}getConsumers(){return a(this,H).consumers}getProducers(){return a(this,H).producers}async leaveRoom(){a(this,H).stopAllTransports(),m(this,Vi,!1),a(this,Js,Zr).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,Xe).sendMessagePromise(a(this,ot).leaveRoom,Rw.toBinary(t)).then(r=>{var i;(i=gR.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(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,H).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,H).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,H).closeConsumers(e)}async _shareWebcam(t){var u,p,f,S;const e=Pe.WEBCAM,r=N(this,ct,vt).call(this,e);if(r){const y=await r;if(a(this,H).producers.has(y)){const P=a(this,H).producers.get(y);if(!P.closed)return await P.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=N(this,ll,sT).call(this,t),n=Ta(this.context,"disableSimulcast"),o=(p=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:p.simulcastConfig;n||o&&o.disable||!((S=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&S.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=zI(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ze).delete(e)},l=a(this,H).createProducer(i,d);return N(this,Ui,Ka).call(this,e,l.then(y=>y.id)),l.then(y=>y.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:me.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ze).delete(Pe.SCREENSHARE_VIDEO),a(this,Ze).delete(Pe.SCREENSHARE_AUDIO)},o=a(this,H).createProducer(i,n);N(this,Ui,Ka).call(this,Pe.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:me.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,H).createProducer(d,l),N(this,Ui,Ka).call(this,Pe.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 ft("track undefined");const e=N(this,ct,vt).call(this,Pe.MIC);if(e){const o=await e;if(a(this,H).producers.has(o)){const c=a(this,H).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,ht)&&(a(this,ht).audioTrack=t,a(this,ht).producerId=o,a(this,ht).start());return}await a(this,H).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=N(this,dl,tT).call(this,t),i=()=>{a(this,Ze).delete(Pe.MIC)},n=a(this,H).createProducer(r,i);N(this,Ui,Ka).call(this,Pe.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,ht)&&(a(this,ht).audioTrack=o.track,a(this,ht).producerId=o.id,a(this,ht).start())})}catch(e){throw new w(e)}}async pauseMic(){var i;const t=await N(this,ct,vt).call(this,Pe.MIC),e=a(this,H).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=a(this,ht))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,Xe).sendMessage(a(this,ot).toggleProducer,Oc.toBinary(r))}async pauseWebcam(){const t=await N(this,ct,vt).call(this,Pe.WEBCAM),e=a(this,H).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,Xe).sendMessage(a(this,ot).toggleProducer,Oc.toBinary(r))}async resumeMic(){const t=await N(this,ct,vt).call(this,Pe.MIC),e=a(this,H).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};a(this,Xe).sendMessage(a(this,ot).toggleProducer,Oc.toBinary(r))}async resumeWebcam(t=Pe.WEBCAM){const e=await N(this,ct,vt).call(this,t),r=a(this,H).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};a(this,Xe).sendMessage(a(this,ot).toggleProducer,Oc.toBinary(i))}async disableWebcam(){const t=Pe.WEBCAM,e=await N(this,ct,vt).call(this,t);N(this,cl,eT).call(this,t),e&&await a(this,H).closeProducer(e)}async disableMic(){var e;const t=await N(this,ct,vt).call(this,Pe.MIC);t&&await a(this,H).closeProducer(t),(e=a(this,ht))==null||e.stop(),a(this,Ze).delete(Pe.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await N(this,ct,vt).call(this,Pe.SCREENSHARE_VIDEO),e=await N(this,ct,vt).call(this,Pe.SCREENSHARE_AUDIO);t&&await a(this,H).closeProducer(t),e&&await a(this,H).closeProducer(e),a(this,vs).clear(),a(this,Ze).delete(Pe.SCREENSHARE_VIDEO),a(this,Ze).delete(Pe.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await N(this,ct,vt).call(this,Pe.WEBCAM);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await N(this,ct,vt).call(this,Pe.SCREENSHARE_VIDEO);await a(this,H).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,H).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,H).socketHandler.kickPeer(e)}kickAll(){a(this,H).socketHandler.kickAll()}async muteAll(t){if(!await a(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,H).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,H).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 a(this,Xe).sendMessagePromise(a(this,ot).globalPinPeer,Bw.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,H).producers.get(t.producerId)&&a(this,vs).add(t.consumerPeerId),a(this,vs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,H).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,Xe).on(a(this,ot).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=jR.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===Zs.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===Zs.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,Xe).on(a(this,ot).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=Pp.fromBinary(t);if(c)return;const d=i===Zs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Pp.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&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:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(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})}}),a(this,Xe).on(a(this,ot).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ou.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,vs).delete(e),a(this,H).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})}}),a(this,Xe).on(a(this,ot).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=JR.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=a(this,H).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,H).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,H).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(C.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,Xe).on(a(this,ot).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Li)&&!a(this,Vi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_DISCONNECTED),a(this,hc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,H).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(a(this,H).producers.values()).find(n=>n.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})})})}}lc=new WeakMap,uc=new WeakMap,Xe=new WeakMap,H=new WeakMap,sl=new WeakMap,ot=new WeakMap,Li=new WeakMap,Vi=new WeakMap,xi=new WeakMap,hc=new WeakMap,wt=new WeakMap,vs=new WeakMap,Ze=new WeakMap,ht=new WeakMap,Js=new WeakSet,Zr=function(){return this.context.getValue("connectionHandler")},rl=new WeakSet,zf=async function(t,e,r,i){var o;m(this,uc,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,Js,Zr).mediaState)!=null?o:{};(d==null?void 0:d.state)===ys.CONNECTED&&(c==null?void 0:c.state)===ys.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,H).closeAllProducersLocally(),a(this,Ze).clear(),a(this,vs).clear(),m(this,wt,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,wt)?await a(this,wt):await N(this,pc,Vu).call(this,t,e,r,i,n),N(this,nl,Qf).call(this,e);const{joined:c,error:d}=await N(this,il,Yf).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{m(this,wt,null)}},il=new WeakSet,Yf=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,H).socketHandler.notifySelfJoinComplete();return m(this,lc,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}}},nl=new WeakSet,Qf=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...me.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)},pc=new WeakSet,Vu=async function(t,e,r,i,n=!1){try{const o=N(this,al,Xf).call(this);await N(this,ol,Zf).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,H).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},al=new WeakSet,Xf=function(){const t=G0("video/VP8");return m(this,sl,t),t},ol=new WeakSet,Zf=async function(t,e,r,i){await kf(async(n,o)=>{if(!a(this,Xe).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,H).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})},ct=new WeakSet,vt=function(t){return a(this,Ze).get(t)},Ui=new WeakSet,Ka=function(t,e){return a(this,Ze).set(t,e)},cl=new WeakSet,eT=function(t){return a(this,Ze).delete(t)},dl=new WeakSet,tT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},ll=new WeakSet,sT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};oe([E.trace("MediaNodeClient.reset")],se.prototype,"reset",1);oe([E.trace("MediaNodeClient.joinRoom")],se.prototype,"joinRoom",1);oe([E.trace("MediaNodeClient.leaveRoom")],se.prototype,"leaveRoom",1);oe([E.trace("MediaNodeClient.activatePeers")],se.prototype,"activatePeers",1);oe([E.trace("MediaNodeClient.createConsumers")],se.prototype,"createConsumers",1);oe([E.trace("MediaNodeClient.closeConsumers")],se.prototype,"closeConsumers",1);oe([E.trace("MediaNodeClient._shareWebcam")],se.prototype,"_shareWebcam",1);oe([E.trace("MediaNodeClient.shareWebcam")],se.prototype,"shareWebcam",1);oe([E.trace("MediaNodeClient.shareScreen")],se.prototype,"shareScreen",1);oe([E.trace("MediaNodeClient.shareMic")],se.prototype,"shareMic",1);oe([E.trace("MediaNodeClient.pauseMic")],se.prototype,"pauseMic",1);oe([E.trace("MediaNodeClient.pauseWebcam")],se.prototype,"pauseWebcam",1);oe([E.trace("MediaNodeClient.resumeMic")],se.prototype,"resumeMic",1);oe([E.trace("MediaNodeClient.resumeWebcam")],se.prototype,"resumeWebcam",1);oe([E.trace("MediaNodeClient.disableWebcam")],se.prototype,"disableWebcam",1);oe([E.trace("MediaNodeClient.disableMic")],se.prototype,"disableMic",1);oe([E.trace("MediaNodeClient.disableScreenShare")],se.prototype,"disableScreenShare",1);oe([E.trace("MediaNodeClient.muteSelf")],se.prototype,"muteSelf",1);oe([E.trace("MediaNodeClient.resetVideoProducers")],se.prototype,"resetVideoProducers",1);oe([E.trace("MediaNodeClient.changeDisplayName")],se.prototype,"changeDisplayName",1);oe([E.trace("MediaNodeClient.kickPeer")],se.prototype,"kick",1);oe([E.trace("MediaNodeClient.kickAllPeers")],se.prototype,"kickAll",1);oe([E.trace("MediaNodeClient.muteAll")],se.prototype,"muteAll",1);oe([E.trace("MediaNodeClient.muteAllVideo")],se.prototype,"muteAllVideo",1);oe([E.trace("MediaNodeClient.disableAudio")],se.prototype,"disableAudio",1);oe([E.trace("MediaNodeClient.disableVideo")],se.prototype,"disableVideo",1);oe([E.trace("MediaNodeClient.pinPeer")],se.prototype,"pinPeer",1);oe([E.trace("MediaNodeClient.validateScreenShare")],se.prototype,"validateScreenShare",1);function rT(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 lD(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 uD=Object.defineProperty,hD=Object.getOwnPropertyDescriptor,Xi=(s,t,e,r)=>{for(var i=r>1?void 0:r?hD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uD(t,e,i),i},ua,ns,Q,pt,Ot,fg;const iT=(fg=class{constructor(s,t,e,r){g(this,pt);h(this,"self");h(this,"authToken");g(this,ua,void 0);h(this,"viewType");g(this,ns,void 0);g(this,Q,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,m(this,Q,s),this.viewType=r,this.authToken=n,m(this,ua,i),m(this,ns,e),this.setupEvents()}get peerId(){return a(this,Q).getValue("peerId")}get telemetry(){return a(this,Q).getValue("telemetry")}get logger(){return a(this,Q).getValue("logger")}get mediaJoined(){return a(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=mt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await We.__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:me.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:SC(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 iT(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===q.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,pt,Ot).shareMic(s),this.self.audioEnabled||a(this,pt,Ot).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===q.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,pt,Ot).shareWebcam(t),this.self.videoEnabled||a(this,pt,Ot).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===q.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,pt,Ot))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),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){a(this,Q).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,pt,Ot).reset({resetTransportQueue:!0}))}setupEvents(){a(this,Q).getValue("peerSessionStore").on(C.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,Q).getValue("peerSessionStore").on(C.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Q).getValue("peerSessionStore").on(C.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Q).getValue("peerSessionStore").on(C.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Q).getValue("peerSessionStore").on(C.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Q).getValue("peerSessionStore").on(C.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,ua).updateURL(t),a(this,Q).getValue("telemetry").resetPeerId(t),mt().setHeader("tracing-id",t),Hr.remapContext(t,a(this,Q)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Q).getValue("peerSessionStore").on(C.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ns).on(V.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ns).on(jc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Q).getValue("peerSessionStore").emit(C.UPDATE_PERMISSIONS,t.patch)})}),a(this,ns).on(V.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ns).on(V.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ns).on(V.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Q).getValue("peerSessionStore").onAsync(C.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Q).getValue("peerSessionStore").on(C.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,Q).getValue("peerSessionStore").on(C.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,Q).getValue("callstats").audioOff())}),a(this,Q).getValue("peerSessionStore").on(C.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,Q).getValue("callstats").videoOff())}),a(this,Q).getValue("peerSessionStore").onAsync(C.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Q).getValue("peerSessionStore").on(C.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await a(this,ns).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,ns).socket.flush();const e=uh(t.stageType);if(a(this,Q).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new w("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),a(this,Q).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof fr&&t.message==="ice connection failed"?new w("A firewall or network restriction may be blocking the connection.","0014"):new w("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,Q).setValue("roomNodeClient",void 0),a(this,Q).notify("stageStatus"),(t=a(this,Q).getValue("roomSocketHandler"))==null||t.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,Q).getAllValues();try{if(e===Xs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}rT(a(this,Q),{socket:a(this,ua),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:p}=(o=await((n=a(this,pt,Ot))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw p!=null?p:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),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=a(this,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Xs.Webinar)&&a(this,pt,Ot)&&(a(this,pt,Ot).mediaJoined&&s!=="disconnected"&&await a(this,pt,Ot).leaveRoom(),!(s==="stageLeft"&&t===Xs.Livestream)&&(a(this,pt,Ot).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()}},ua=new WeakMap,ns=new WeakMap,Q=new WeakMap,pt=new WeakSet,Ot=function(){return a(this,Q).getValue("roomNodeClient")},fg);let Kr=iT;Xi([E.trace("SelfController.resetSelf")],Kr.prototype,"resetSelf",1);Xi([E.trace("SelfController.setupEvents")],Kr.prototype,"setupEvents",1);Xi([E.trace("SelfController.joinRoom")],Kr.prototype,"joinRoom",1);Xi([E.trace("SelfController.leaveRoom")],Kr.prototype,"leaveRoom",1);Xi([E.trace("SelfController.joinMediaRoom")],Kr.prototype,"joinMediaRoom",1);Xi([E.trace("SelfController.leaveMediaRoom")],Kr.prototype,"leaveMediaRoom",1);Xi([E.trace("SelfController.init")],Kr,"init",1);var gc;class pD{constructor(t){g(this,gc,void 0);m(this,gc,t)}on(t,e){let r;t===V.roomPeerCount?r=wp.fromBinary.bind(wp):r=Op.fromBinary.bind(Op),a(this,gc).on(t,({payload:i})=>{if(t===V.roomPeerCount&&!i)return;const n=r(i);e(n)})}}gc=new WeakMap;var mc,fc;class gD{constructor(t,e){g(this,mc,void 0);g(this,fc,void 0);m(this,mc,e),m(this,fc,t)}get logger(){return a(this,fc).getValue("logger")}on(t,e){let r,i;switch(t){case V.transcript:{r=Bl.fromBinary.bind(Bl),i=Bl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,mc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}mc=new WeakMap,fc=new WeakMap;var mD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,Ch=(s,t,e,r)=>{for(var i=r>1?void 0:r?fD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mD(t,e,i),i},Ks,ha;class kl{constructor(t,e){g(this,Ks,void 0);g(this,ha,void 0);m(this,Ks,e),m(this,ha,t)}get logger(){return a(this,ha).getValue("logger")}get telemetry(){return a(this,ha).getValue("telemetry")}getPolls(){return a(this,Ks).sendMessagePromise(Ms.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Ks).sendMessage(Ms.createPoll,PA.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Ks).sendMessage(Ms.votePoll,CA.toBinary(r))}on(t,e){let r,i;switch(t){case Ms.updatePoll:case Ms.createPoll:case Ms.votePoll:{r=Wl.fromBinary.bind(Wl),i=Wl.create();break}}a(this,Ks).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Ks).removeListeners(t)}}Ks=new WeakMap,ha=new WeakMap;Ch([E.trace("PollSocketHandler.getPolls")],kl.prototype,"getPolls",1);Ch([E.trace("PollSocketHandler.createPoll")],kl.prototype,"createPoll",1);Ch([E.trace("PollSocketHandler.votePoll")],kl.prototype,"votePoll",1);var TD=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,vD=(s,t,e,r)=>{for(var i=r>1?void 0:r?SD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&TD(t,e,i),i},Rt;class nT{constructor(t,e){h(this,"socket");g(this,Rt,void 0);m(this,Rt,t),this.socket=e,this.handleSocketEvents(),a(this,Rt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Rt).getValue("telemetry")}get logger(){return a(this,Rt).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,Pb.toBinary(e));try{const{peer:n}=en.fromBinary((await r).payload);a(this,Rt).getValue("connectionHandler").socketJoined=!0,a(this,Rt).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Rt).getValue("peerSessionStore").emit(C.ROOM_STATE,d),a(this,Rt).getValue("peerSessionStore").emit(C.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return ak.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 n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(V.getRoomPeersInfo,hb.toBinary(n));i=Hl.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(V.getRoomPeersInfo);t=Hl.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=Hl.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,Gm.toBinary({peerId:t}));e=en.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Rp.create();try{const e=await this.socket.sendMessagePromise(V.getRoomInfo);t=Rp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Ap.create();try{const e=await this.socket.sendMessagePromise(V.getRoomStageState);t=Ap.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,$a.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,$a.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,$a.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(V.leaveRoom,Cb.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(V.kick,Jm.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(V.kickAll,Fm.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(V.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.acceptWaitingRoomRequests,hk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.denyWaitingRoomRequests,gk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(jc.updateUserPreset,qk.toBinary(r))}handleSocketEvents(){this.socket.on(V.broadcastMessage,({payload:t})=>{try{const e=$a.fromBinary(t);a(this,Rt).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=$a.fromBinary(t);a(this,Rt).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=en.fromBinary.bind(en),i=en.create();break}case V.getWaitingRoomRequests:{r=(n,o)=>n?Mp.fromBinary(n,o):{requests:[]},i=Mp.create();break}case V.recordingPaused:case V.recordingStarted:case V.recordingStopped:{r=Vp.fromBinary.bind(Vp);break}case jc.updateUserPreset:{r=Ip.fromBinary.bind(Ip);break}case os.peerJoinedBroadcast:case mr.peerJoinedBroadcast:{r=yp.fromBinary.bind(yp);break}case os.selfJoinComplete:case mr.selfJoinComplete:{r=au.fromBinary.bind(au);break}case os.globalPeerPinBroadcast:case mr.globalPeerPinBroadcast:{r=_p.fromBinary.bind(_p);break}case os.selectedPeer:case mr.selectedPeer:{r=nu.fromBinary.bind(nu);break}case os.selectedPeerDiff:case mr.selectedPeerDiff:{r=vp.fromBinary.bind(vp);break}case os.leaveRoom:case mr.leaveRoom:{r=ou.fromBinary.bind(ou);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}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(jc.getUserPresets,Vk.toBinary(e)),i=Bk.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).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}}}Rt=new WeakMap;vD([E.trace("RoomSocketHandler.joinRoom")],nT.prototype,"joinRoom",1);var gt;class yD{constructor(t){g(this,gt,void 0);m(this,gt,t)}async getStageRequests(){const{payload:t}=await a(this,gt).sendMessagePromise(V.getStageRequests);return t?Gl.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,gt).sendMessage(V.requestStageAccess)}cancelRequestAccess(){a(this,gt).sendMessage(V.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,gt).sendMessage(V.grantStageAccess,hA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,gt).sendMessage(V.denyStageAccess,gA.toBinary(e))}joinStage(){return a(this,gt).sendMessagePromise(V.joinStage,void 0,void 0,V.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,gt).sendMessagePromise(V.leaveStage,Lp.toBinary(e),void 0,V.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,gt).sendMessagePromise(V.leaveStage,Lp.toBinary(e))}on(t,e){let r;switch(t){case V.grantStageAccess:case V.denyStageAccess:{r=void 0;break}case V.getStagePeers:{r=Np.fromBinary.bind(Np);break}case V.getStageRequests:case V.requestStageAccess:case V.cancelStageRequest:{r=Gl.fromBinary.bind(Gl);break}case V.peerStageStatusUpdate:{r=Cp.fromBinary.bind(Cp);break}}a(this,gt).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,gt).sendMessagePromise(V.getPeerInfo,Gm.toBinary({peerId:t}));return en.fromBinary(e.payload)}}gt=new WeakMap;var Lr,pa;class ED{constructor(t,e){g(this,Lr,void 0);g(this,pa,void 0);m(this,Lr,e),m(this,pa,t)}get logger(){return a(this,pa).getValue("logger")}get peerId(){return a(this,pa).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,Lr).sendMessage(ks.storeInsertKeys,WM.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Lr).sendMessage(ks.storeGetKeys,KM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Lr).sendMessage(ks.storeDeleteKeys,YM.toBinary(n),i)}on(t,e){const r=Dp.fromBinary.bind(Dp);a(this,Lr).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Lr=new WeakMap,pa=new WeakMap;var PD=Object.defineProperty,_D=(s,t,e)=>t in s?PD(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,CD=(s,t,e)=>(_D(s,typeof t!="symbol"?t+"":t,e),e),wh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>(wh(s,t,"read from private field"),e?e.call(s):t.get(s)),re=(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)},Z=(s,t,e,r)=>(wh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ee=(s,t,e)=>(wh(s,t,"access private method"),e),pd={},wD={get exports(){return pd},set exports(s){pd=s}},gn=typeof Reflect=="object"?Reflect:null,Jp=gn&&typeof gn.apply=="function"?gn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Qc;gn&&typeof gn.ownKeys=="function"?Qc=gn.ownKeys:Object.getOwnPropertySymbols?Qc=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Qc=function(s){return Object.getOwnPropertyNames(s)};function RD(s){console&&console.warn&&console.warn(s)}var aT=Number.isNaN||function(s){return s!==s};function ae(){ae.init.call(this)}wD.exports=ae;pd.once=AD;ae.EventEmitter=ae;ae.prototype._events=void 0;ae.prototype._eventsCount=0;ae.prototype._maxListeners=void 0;var Kp=10;function Ml(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ae,"defaultMaxListeners",{enumerable:!0,get:function(){return Kp},set:function(s){if(typeof s!="number"||s<0||aT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Kp=s}});ae.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};ae.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||aT(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 oT(s){return s._maxListeners===void 0?ae.defaultMaxListeners:s._maxListeners}ae.prototype.getMaxListeners=function(){return oT(this)};ae.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 n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,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=hT(c,d),e=0;e<d;++e)Jp(l[e],this,t);return!0};function cT(s,t,e,r){var i,n,o;if(Ml(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=oT(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,RD(c)}return s}ae.prototype.addListener=function(s,t){return cT(this,s,t,!1)};ae.prototype.on=ae.prototype.addListener;ae.prototype.prependListener=function(s,t){return cT(this,s,t,!0)};function bD(){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 dT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=bD.bind(r);return i.listener=e,r.wrapFn=i,i}ae.prototype.once=function(s,t){return Ml(t),this.on(s,dT(this,s,t)),this};ae.prototype.prependOnceListener=function(s,t){return Ml(t),this.prependListener(s,dT(this,s,t)),this};ae.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Ml(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,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():kD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ae.prototype.off=ae.prototype.removeListener;ae.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),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);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 lT(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?MD(i):hT(i,i.length)}ae.prototype.listeners=function(s){return lT(this,s,!0)};ae.prototype.rawListeners=function(s){return lT(this,s,!1)};ae.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):uT.call(s,t)};ae.prototype.listenerCount=uT;function uT(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}ae.prototype.eventNames=function(){return this._eventsCount>0?Qc(this._events):[]};function hT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function kD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function MD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function AD(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}pT(s,t,n,{once:!0}),t!=="error"&&ID(s,i,{once:!0})})}function ID(s,t,e){typeof s.on=="function"&&pT(s,"error",t,e)}function pT(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(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class DD extends T.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 zp=new DD;class gT{static encode(t){return zp.toBinary(t)}static decode(t){return zp.fromBinary(new Uint8Array(t))}}function OD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var pr;class ND{constructor(t={}){CD(this,"opts"),re(this,pr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},Z(this,pr,0)}async wait(){Z(this,pr,A(this,pr)+1);const t=OD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,pr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,pr)}reset(){Z(this,pr,0)}}pr=new WeakMap;const dr={debug:0,info:1,warn:2,error:3};var ei,ti;class LD{constructor(t){re(this,ei,void 0),re(this,ti,void 0),Z(this,ei,console),Z(this,ti,t)}debug(...t){dr[A(this,ti)]>dr.debug||A(this,ei).debug("[Sockrates]:",...t)}info(...t){dr[A(this,ti)]>dr.info||A(this,ei).info("[Sockrates]:",...t)}warn(...t){dr[A(this,ti)]>dr.warn||A(this,ei).warn("[Sockrates]:",...t)}error(...t){dr[A(this,ti)]>dr.error||A(this,ei).error("[Sockrates]:",...t)}}ei=new WeakMap,ti=new WeakMap;var mT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(mT||{});const Yp="2",Qp="3";var Re,nn,ie,ve,gr,Ge,Ys,$r,as,an,on,bs,xu,fT,za,Xc,Uu,TT,Zc,Yl,gd,$u,Bu,ST,eo,ed,mn,to,md,Hu,fn,so,Fu,vT,ro,td,io,fd;class VD{constructor(t,e){var y,P,R,k,I,O,x,B,$,z,he,Oe;re(this,xu),re(this,za),re(this,Uu),re(this,Zc),re(this,gd),re(this,Bu),re(this,eo),re(this,mn),re(this,md),re(this,fn),re(this,Fu),re(this,ro),re(this,io),re(this,Re,void 0),re(this,nn,void 0),re(this,ie,void 0),re(this,ve,void 0),re(this,gr,void 0),re(this,Ge,void 0),re(this,Ys,void 0),re(this,$r,void 0),re(this,as,void 0),re(this,an,void 0),re(this,on,void 0),re(this,bs,void 0);var r,i,n,o,c,d,l,u,p,f,S;Z(this,nn,t),Z(this,gr,[]),Z(this,Ge,new pd),Z(this,Ys,!0),Z(this,as,!1),Z(this,ie,e!=null?e:{}),(y=(r=A(this,ie)).autoReconnect)!=null||(r.autoReconnect=!0),(P=(i=A(this,ie)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(R=(n=A(this,ie)).pingTimeout)!=null||(n.pingTimeout=3e4),(k=(o=A(this,ie)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(I=(c=A(this,ie)).debug)!=null||(c.debug=!0),(O=(d=A(this,ie)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(x=(l=A(this,ie)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=A(this,ie)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),($=(p=A(this,ie)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),(z=(f=A(this,ie)).clientInitiatedPings)!=null||(f.clientInitiatedPings=!1),(he=(S=A(this,ie)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),Z(this,$r,{code:void 0,reason:void 0}),Z(this,ve,(Oe=A(this,ie).logger)!=null?Oe:new LD(A(this,ie).debug?"debug":"info")),Z(this,bs,new ND)}get readyState(){var t;return(t=A(this,Re))==null?void 0:t.readyState}get url(){return A(this,nn)}updateURL(t){Z(this,nn,t),ee(this,Bu,ST).call(this)}get config(){return A(this,ie)}get sendQueue(){return A(this,gr)}flush(){if(!A(this,ie).queueOnDisconnect)return!1;const t=[];return A(this,gr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),Z(this,gr,t),A(this,gr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,ve).debug("Websocket was already connecting or connected.");return}if(A(this,Ys)!==!1)return new Promise((e,r)=>{ee(this,fn,so).call(this),ee(this,io,fd).call(this);try{Z(this,Re,new WebSocket(ee(this,xu,fT).call(this,A(this,nn)))),A(this,Re).binaryType="arraybuffer",A(this,ve).debug("Connecting");const i=setTimeout(()=>{A(this,ve).debug("Connection timeout. Closing socket"),Z(this,Ys,!0),ee(this,io,fd).call(this),A(this,Re).close(3001,"Connection Timeout"),A(this,ie).autoReconnect&&!A(this,as)&&(A(this,Ge).emit("reconnecting"),ee(this,eo,ed).call(this)),r(new Error("Connection timed out!"))},A(this,ie).connectionTimeout);A(this,Re).onopen=()=>{A(this,ve).debug(`Ready State: ${mT[A(this,Re).readyState]}`),i&&clearTimeout(i),ee(this,md,Hu).call(this),ee(this,Fu,vT).call(this),Z(this,$r,{code:void 0,reason:void 0}),A(this,Ge).emit("connected"),A(this,ie).flushOnReconnect&&this.flush(),e()},A(this,Re).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),A(this,ve).debug("Socket closed. Close event:",{event:n}),A(this,ve).debug(`Connection closed code: ${o}`),A(this,ve).debug(`Connection closed reason: ${c}`),A(this,as)||ee(this,gd,$u).call(this,o,c)}catch(o){ee(this,za,Xc).call(this,o)}},A(this,Re).onerror=n=>{ee(this,za,Xc).call(this,n)},A(this,Re).onmessage=n=>ee(this,Uu,TT).call(this,n)}catch(i){ee(this,za,Xc).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(A(this,ie).queueOnDisconnect&&(!A(this,Re)||A(this,Re).readyState!==1))return A(this,ve).debug("Queuing message since socket is not connected!",n),A(this,gr).push(n),!1;const o=gT.encode(n);return ee(this,mn,to).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ee(this,mn,to).call(this,t)}receive(t,e){return A(this,Ge).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")){A(this,Ge).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,Ge).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,Ge).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,Ge).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){Z(this,Ys,!1),ee(this,fn,so).call(this),ee(this,ro,td).call(this),this.removeAllListeners(),Z(this,$r,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,Re).close(1e3,"Sockrates disconnect method called.")}}Re=new WeakMap,nn=new WeakMap,ie=new WeakMap,ve=new WeakMap,gr=new WeakMap,Ge=new WeakMap,Ys=new WeakMap,$r=new WeakMap,as=new WeakMap,an=new WeakMap,on=new WeakMap,bs=new WeakMap,xu=new WeakSet,fT=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,Xc=function(s,t){A(this,ve).error("Error:",{error:s}),A(this,Ge).emit("errored",{error:s}),t==null||t(s)},Uu=new WeakSet,TT=function(s){if(ee(this,md,Hu).call(this),s.data===Yp){A(this,ve).debug("Received ping from server"),ee(this,mn,to).call(this,Qp);return}if(s.data===Qp){A(this,ve).debug("Received pong from server");return}const t=gT.decode(s.data),{id:e,payload:r}=t;A(this,ve).debug("Received message",{event:t.event,messageID:e}),A(this,Ge).emit(t.event.toString(),{id:e,payload:r})},Zc=new WeakSet,Yl=function(){return A(this,Re).readyState===1},gd=new WeakSet,$u=function(s,t){Z(this,$r,{reason:t,code:s}),A(this,Ge).emit("disconnected",{code:s,reason:t})},Bu=new WeakSet,ST=function(){const{reason:s,code:t}=A(this,$r);t&&t!==1e3&&A(this,Ys)&&A(this,ie).autoReconnect&&!A(this,as)&&(A(this,ve).debug(`Triggering reconnection due to ${s}.`),A(this,Ge).emit("reconnecting"),ee(this,eo,ed).call(this))},eo=new WeakSet,ed=async function(s=!0){if(s&&A(this,as)){A(this,ve).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,as)||A(this,bs).reset(),A(this,ie).maxReconnectionAttempts!==null&&A(this,bs).getAttempts()>=A(this,ie).maxReconnectionAttempts){A(this,Ge).emit("failed"),Z(this,as,!1);return}Z(this,as,!0),ee(this,io,fd).call(this),ee(this,fn,so).call(this);try{if(await A(this,bs).wait(),A(this,Ys)===!1)return;if(A(this,ve).debug(`Reconnection attempt ${A(this,bs).getAttempts()}`),A(this,Ge).emit("reconnectAttempt",{attempt:A(this,bs).getAttempts()}),await this.connect(),!ee(this,Zc,Yl).call(this))throw Error("Reconnect Failed");Z(this,as,!1),Z(this,$r,{code:void 0,reason:void 0}),A(this,Ge).emit("reconnected")}catch(t){A(this,ve).debug("Failed to reconnect."),A(this,Ge).emit("reconnectFailure",{attempt:A(this,bs).getAttempts()}),ee(this,eo,ed).call(this,!1)}},mn=new WeakSet,to=function(s){try{return A(this,Re).send(s),!0}catch(t){return A(this,ve).error(t.message),!1}},md=new WeakSet,Hu=function(){this.config.disconnectOnPingTimeout&&(A(this,ve).debug("Resetting ping timeout"),ee(this,fn,so).call(this),Z(this,an,setTimeout(()=>{var s;A(this,ve).debug("Disconnecting the socket due to ping timeout"),Z(this,Ys,!0);const t=3002,e="Ping timeout";(s=A(this,Re))==null||s.close(t,e),ee(this,gd,$u).call(this,t,e)},A(this,ie).pingTimeout)))},fn=new WeakSet,so=function(){A(this,an)&&(clearTimeout(A(this,an)),Z(this,an,void 0))},Fu=new WeakSet,vT=function(){ee(this,ro,td).call(this),A(this,ie).clientInitiatedPings&&Z(this,on,setInterval(()=>{ee(this,Zc,Yl).call(this)&&(A(this,ve).debug("Sending client-initiated ping"),ee(this,mn,to).call(this,Yp))},A(this,ie).clientInitiatedPingInterval))},ro=new WeakSet,td=function(){A(this,on)&&(clearInterval(A(this,on)),Z(this,on,void 0))},io=new WeakSet,fd=function(){ee(this,ro,td).call(this),A(this,Re)&&(A(this,Re).onopen=void 0,A(this,Re).onerror=void 0,A(this,Re).onmessage=void 0,A(this,Re).onclose=void 0)};var xD=Object.defineProperty,UD=Object.getOwnPropertyDescriptor,Al=(s,t,e,r)=>{for(var i=r>1?void 0:r?UD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xD(t,e,i),i};const Xp=65535,$D=3e3;var Vr,Te,Se,ke,qt,qe,Tc,qu,Sc,ju,Tg;const yT=(Tg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Se);g(this,Tc);g(this,Sc);g(this,Vr,void 0);g(this,Te,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");g(this,qt,void 0);g(this,qe,void 0);if(!t||!e||!r)throw new w("peerId, meetingId, or authToken can not be empty","0404");m(this,qt,void 0),m(this,qe,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,Vr,N(this,Tc,qu).call(this,t));const n=i.includes("PING");m(this,Te,new VD(a(this,Vr),{autoReconnect:!0,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,maxReconnectionAttempts:50,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Se,ke).socketJoinAttempted}set joinAttempted(s){a(this,Se,ke).socketJoinAttempted=s}get telemetry(){return a(this,qe).getValue("telemetry")}get logger(){return a(this,qe).getValue("logger")}get peerId(){return a(this,qe).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,Vr,N(this,Tc,qu).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Te).updateURL(a(this,Vr))}static getSocketEdgeDomain(s){return pn({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,Vr)}async connect(){a(this,Se,ke).socketJoinAttempted=!0,await a(this,Te).connect(),a(this,Se,ke).socketJoinAttempted=!0,a(this,Se,ke).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Se,ke).socketJoinAttempted=!1,a(this,Te).disconnect(),a(this,Se,ke).socketJoinAttempted=!0,a(this,Se,ke).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Te).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,qe).getValue("telemetry").injectContext(r),a(this,Te).send(s,e!=null?e:N(this,Sc,ju).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 n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,P)=>{a(this,Te).removeListener(n,y),a(this,Te).removeListener(Xp,P),a(this,Te).removeListener(mr.errorResponse,P),a(this,Te).removeListener(os.errorResponse,P)},l=r!=null?r:N(this,Sc,ju).call(this),u={};a(this,qe).getValue("telemetry").injectContext(u);const f=({id:y,payload:P})=>{if(l===y){let R;try{const k=iR.fromBinary(P);R=new Error(k.errorMessage)}catch(k){R=new Error("failed to parse error message",{cause:k});try{const I=nb.fromBinary(P);R=new Error(I.message)}catch(I){R=new Error("failed to parse error message",{cause:I})}}c(R),d(S,f)}},S=({id:y,payload:P})=>{l===y&&(o({id:y,payload:P}),d(S,f))};a(this,Te).on(n,S),a(this,Te).on(Xp,f),a(this,Te).on(mr.errorResponse,f),a(this,Te).on(os.errorResponse,f),setTimeout(()=>{d(S,f),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Te).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Te).on(s,t)}onStateEvent(s,t){a(this,Te).on(s,t)}removeListener(s,t){a(this,Te).removeListener(s,t)}removeListeners(s){a(this,Te).removeListeners(s)}flush(){return a(this,Te).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,qt)&&(clearTimeout(a(this,qt)),m(this,qt,void 0)),a(this,Se,ke).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=a(this,Se,ke).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==ys.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==ys.CONNECTED?a(this,qe).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Se,ke).joinAttempted}):m(this,qt,setTimeout(()=>{a(this,qe).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Se,ke).joinAttempted}),m(this,qt,void 0)},$D)),a(this,Se,ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Se,ke).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Se,ke).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Se,ke).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Se,ke).mediaJoinAttempted}}),a(this,qt)&&(clearTimeout(a(this,qt)),m(this,qt,void 0)),a(this,qe).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Se,ke).mediaJoinAttempted}),a(this,Se,ke).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,qe).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_FAILED),a(this,Se,ke).updateSocketConnectionState("failed")})}},Vr=new WeakMap,Te=new WeakMap,Se=new WeakSet,ke=function(){return a(this,qe).getValue("connectionHandler")},qt=new WeakMap,qe=new WeakMap,Tc=new WeakSet,qu=function(s){const t=a(this,qe).getValue("socketBaseURI")||a(this,qe).getValue("baseURI");let e=yT.getSocketEdgeDomain(t);typeof Ta(a(this,qe),"socket_server_base")=="string"&&(e=Ta(a(this,qe),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>cd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Sc=new WeakSet,ju=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Tg);let Mc=yT;Al([E.trace("SocketService.connect")],Mc.prototype,"connect",1);Al([E.trace("SocketService.disconnect")],Mc.prototype,"disconnect",1);Al([E.trace("SocketService.sendMessagePromise")],Mc.prototype,"sendMessagePromise",1);Al([E.trace("SocketService.sendMessagePromiseWithTimeout")],Mc.prototype,"sendMessagePromiseWithTimeout",1);class BD{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=Db.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:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=ik.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Wm.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return kp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Kb.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,Vb.toBinary({payloads:t}));return kp.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,Wb.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(V.movePeers,ek.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,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&HD(t,e,i),i},bt;class ET extends At{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);g(this,bt,void 0);m(this,bt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,bt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,bt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,bt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,bt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,bt).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.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,bt).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.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.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 a(this,bt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,bt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.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}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,bt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.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}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.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=>n.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})}}bt=new WeakMap;qD([It({maxInvocations:60,period:60})],ET.prototype,"getConnectedMeetings",1);var jD=Object.defineProperty,GD=Object.getOwnPropertyDescriptor,Rh=(s,t,e,r)=>{for(var i=r>1?void 0:r?GD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&jD(t,e,i),i},le,Sg;const PT=(Sg=class{constructor(s){h(this,"connectedMeetings");g(this,le,void 0);m(this,le,s),this.connectedMeetings=new ET(s)}get telemetry(){return a(this,le).getValue("telemetry")}get logger(){return a(this,le).getValue("logger")}static init(s){const t=new PT(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(V.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(V.transferPeer,this.handleTransferPeer.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(V.movedPeer,this.handleMovedPeer.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,le).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,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,le).getValue("self").videoEnabled,audio:a(this,le).getValue("self").audioEnabled};try{a(this,le).getValue("self").cleanupEvents(),await a(this,le).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,le).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await CT.init({...a(this,le).getValue("options"),cachedUserDetails:null,defaults:{...a(this,le).getValue("options").defaults,...e,mediaHandler:a(this,le).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}=a(this,le).getValue("self");r.self.setName(a(this,le).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=a(this,le).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 a(this,le).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,le).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=a(this,le).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})}},le=new WeakMap,Sg);let Il=PT;Rh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Il.prototype,"getConnectedMeetings",1);Rh([E.trace("ConnectedMeetingsController.setupEvents")],Il.prototype,"setupEvents",1);Rh([E.trace("ConnectedMeetingsController.switchMeeting")],Il.prototype,"switchMeeting",1);var WD=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,bh=(s,t,e,r)=>{for(var i=r>1?void 0:r?JD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WD(t,e,i),i};const Ya=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 O,x,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(lD(s),me.isSupported()===!1)throw new w("Browser not supported","0010",c,!0);const d=ZA(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new LI(s);s.setValue("connectionHandler",l);let u="",p="",f=null;c.info("CF SFU is being used.");try{f=await d.getUserDetails(),u=((O=f.meeting)==null?void 0:O.title)||"",p=((x=f.socket)==null?void 0:x.baseUri)||s.getValue("baseURI"),s.setValue("presetName",f.preset.name),s.setValue("socketBaseURI",p),c.info(`Socket Base URI ${p} is being used`)}catch($){throw c.error("Failed to get user details",{error:$}),$ instanceof dd?$.status===401?new w("Unauthorized. The auth token may be invalid or expired. (401)","0004"):$.status===403?new w("Access denied. Insufficient permissions to join the meeting. (403)","0004"):$.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new w("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")):$.status>=500?new w(`The server encountered an error. Try again. (${$.status})`,"0001"):$.isHttpError?new w(`Request rejected by the server. (${$.status})`,"0001"):$.isTimeout?new w("Connection timed out. Check the network and try again.","0001"):new w("Unable to connect to the server. Check the internet connection.","0001"):new w(($==null?void 0:$.message)||"Failed to initialize.","0001")}const S=Ya.createSocketService(s),y=S.connect();try{await y}catch($){c.error("[Controller]: Failed to connect to socket server:",{error:$})}const P=Pu.init(f.preset,!s.getValue("modules").theme);s.setValue("theme",P);const R=Ru.init(s,P.viewType,f.preset.permissions),k=Ya.setupControllers(S,s,f,u,P,R);_I(P)&&((B=Ya.createRoomNodeClient(s,S).initializeConnection(f.participant.name,i,!1,R))==null||B.catch(z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:z})}));const{controllers:I}=await k;return $C(),new Ya(e,I,s)}static async setupControllers(s,t,e,r,i,n){var ye,L,b;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:p}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(ye=p.enableHighBitrate)!=null?ye:!1,enableStereo:(L=p.enableStereo)!=null?L:!1}},...d}),t.setValue("maxPreferredStreams",me.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let f,S,y,P,R,k,I,O,x;const B=new gD(t,s),$=new BD(s);t.setValue("connectedMeetingsSocketHandler",$);const z=new kl(t,s),he=new nr(t,s),Oe=new yD(s),Kt=new nT(t,s),zr=new ED(t,s),M=new pD(s),v=await Kr.init(t,Kt,c,n,i);t.setValue("selfController",v);const _=await cf.init(t,v.self,Kt,B,r);o.participant&&(O=new cr(t,v.self,Kt)),(b=o.e2ee)!=null&&b.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await Za.init(t,he,v.self,O.participants)),o.internals&&(R=await gh.init(t)),o.livestream&&i.viewType===Xs.Livestream&&(I=new vf(t,v.self,M)),o.poll&&(f=await rf.init(t,v.self,z)),o.recording&&(k=new gf(t,v.self,Kt)),o.stage&&(y=new df(t,Oe,Kt,v.self,O.participants));const U=new b0(t,zr);if(o.plugin){if(!O)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const be=d.plugins||[];P=await pf.init(t,be,v.self,U)}if(o.connectedMeetings&&(x=await Il.init(t)),o.pip){const be=await iu._init(t,v.self);t.setValue("pip",be)}return{theme:i,permissions:n,controllers:{storesManager:U,pollController:f,selfController:v,metaController:_,chatController:S,stageController:y,pluginController:P,recordingController:k,internalsController:R,livestreamController:I,participantController:O,connectedMeetingsController:x}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return rT(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 Mc(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Dl=Ya;bh([E.trace("Controller.init")],Dl,"init",1);bh([E.trace("Controller.createRoomNodeClient")],Dl,"createRoomNodeClient",1);bh([E.trace("Controller.createSocketService")],Dl,"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 Zp=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 n=ri.baseURI.prod;t&&(n=t);const o=`https://${pn({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new w("Invalid auth token","0004")}}var xr,$i,Bi,vc,ul,_T;class YD{constructor(){g(this,ul);g(this,xr,new Audio);g(this,$i,new MediaStream);g(this,Bi,new Map);g(this,vc,void 0);a(this,xr).srcObject=a(this,$i),a(this,xr).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Bi).has(e.id)||(a(this,$i).addTrack(e),a(this,Bi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,xr).setSinkId(t)}removeTrack(t){const e=a(this,Bi).get(t);e&&(a(this,$i).removeTrack(e),a(this,Bi).delete(t))}async play(){return a(this,xr).srcObject=a(this,$i),a(this,xr).play().catch(t=>{N(this,ul,_T).call(this,t)})}onError(t){m(this,vc,t)}}xr=new WeakMap,$i=new WeakMap,Bi=new WeakMap,vc=new WeakMap,ul=new WeakSet,_T=function(t){var e;(e=a(this,vc))==null||e.call(this,t)};var Hi;class QD extends YD{constructor(){super();g(this,Hi,void 0);m(this,Hi,new Map)}addParticipantTrack(e,r){a(this,Hi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,Hi).get(e);r&&this.removeTrack(r),a(this,Hi).delete(e)}}Hi=new WeakMap;var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,Ol=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XD(t,e,i),i},De,Fi,vg;let jr=(vg=class{constructor(t,e){g(this,De,void 0);g(this,Fi,void 0);m(this,Fi,t),m(this,De,e)}get peerId(){return a(this,Fi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:qr.v4(),n=Hr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new bf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,S,y,P,R,k,I,O,x;me.init();const e=(S=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?S:qr.v4(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=zD(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new w("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=jr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");IT(l),Zp.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(R=(P=t.modules)==null?void 0:P.tracing)!=null?R:!0,(I=(k=t==null?void 0:t.modules)==null?void 0:k.devTools)==null?void 0:I.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(O=t.authToken)==null?void 0:O.slice(0,10)}...
10
+ ${(x=t.authToken)==null?void 0:x.slice(-10)}`}});const u=await Dl.init(c),p=new jr(c,u);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const n=Hr.createContext(t,e),o={...fC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",TC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Es(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.2-staging.7"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new QD),n}async join(){const{selfController:t}=a(this,De);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Zp.cleanup(),a(this,Fi).getValue("peerSessionStore").reset(),(r=a(this,De).pluginController)==null||r.cleanup();const{selfController:e}=a(this,De);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,De).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,De).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,De).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,De).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,De).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,De).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,De).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,De).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,De).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,De).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,De).stageController)==null?void 0:t.stage}get stores(){return a(this,De).storesManager}get audio(){return a(this,Fi).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,De).internalsController)==null?void 0:t.internals}},De=new WeakMap,Fi=new WeakMap,vg);Ol([tt("0002"),or.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],jr.prototype,"join",1);Ol([tt("0003")],jr.prototype,"leave",1);Ol([tt("0001"),or.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],jr,"init",1);jr=Ol([tt("0000")],jr);const CT=jr;module.exports=CT;