@cloudflare/realtimekit 1.2.5-staging.3 → 1.2.5-staging.5

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/browser.js CHANGED
@@ -18,4 +18,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,Ir)},
18
18
  maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Ir)||i<a(this,Ir))&&f(this,Ir,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,Ir))/(a(this,ui)-a(this,Ir))*10||0,isVoice:r})},Pc=new WeakSet,Tp=function(t){return t<5},su=new WeakSet,Dv=function(t=a(this,pn)){var r;if(!a(this,Ns)||!t){a(this,Ar).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Ns)}`);return}const e={producerId:a(this,Ns),energy:Math.round(t),silent:x(r=_c,Pc,Tp).call(r,t)};f(this,Ja,e.silent),this.reportRequest(e)},ru=new WeakSet,Nv=function(t){const e=Math.log10(t);return Math.round(e)},m(_o,Pc),m(_o,ru);const P1=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},_1=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var C1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?R1(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&&C1(t,e,i),i};const Wt=["video/VP9","video/VP8"],gS=(rp=class{constructor(s,t){m(this,hi);m(this,iu);m(this,nu);m(this,au);m(this,Ac);m(this,cu);m(this,du);m(this,lu);m(this,at);m(this,Tn);m(this,uu);m(this,hu);m(this,pu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Cc,void 0);m(this,Rc,void 0);m(this,vt,void 0);m(this,j,void 0);m(this,Ka,void 0);m(this,Rt,void 0);m(this,gn,void 0);m(this,mn,void 0);m(this,fn,void 0);m(this,kc,void 0);m(this,fs,null);m(this,Or,void 0);m(this,Ic,void 0);m(this,Sn,void 0);m(this,vn,void 0);m(this,kt,void 0);m(this,xt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,Sn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,vt,e),f(this,gn,!1),f(this,j,new y1(s,e)),f(this,Rt,a(this,j).events),f(this,Or,new Set),f(this,kt,new Map),f(this,mn,!1),f(this,fn,new Uh(s.getValue("logger"))),f(this,xt,new _o(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,kc,Ju(async()=>{if(!a(this,hi,Qa).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Rc),a(this,Cc),!0,!0);n&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,hi,Qa).mediaJoined}set mediaJoined(s){a(this,hi,Qa).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,kt).clear(),a(this,Or).clear(),f(this,fs,null),a(this,fn).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,fn,new Uh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,hi,Qa).mediaJoinAttempted=!0,f(this,gn,!0),e&&this.reset();try{return await a(this,fn).push(()=>x(this,iu,Vv).call(this,s,t,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(s,t,e=!1,r={}){return a(this,fs)?a(this,fs):(f(this,fs,(async()=>{try{await x(this,Ac,yp).call(this,s,t,e,r)}catch(i){throw f(this,fs,null),i}})()),a(this,fs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,mn,!1),a(this,hi,Qa).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,vt).sendMessagePromise(a(this,Rt).leaveRoom,PR.toBinary(s)).then(e=>{var r;(r=hk.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g;const e=t==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,r=x(this,at,At).call(this,e);if(r){const S=await r;if(a(this,j).producers.has(S)){const y=a(this,j).producers.get(S);if(!y.closed)return await y.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Wt.filter(S=>S!==t)),n=x(this,pu,jv).call(this,s,i),o=On(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(X.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=nD(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,kt).delete(e)},u=a(this,j).createProducer(n,l);return x(this,Tn,rd).call(this,e,u.then(S=>S.id)),u.then(S=>S.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Wt.filter(i=>{var n,o;return((o=(n=a(this,Ka).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,vn).get(i).size>0});return e.length===0&&e.push(Wt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s}async shareScreen(s){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ve.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,kt).delete(me.SCREENSHARE_VIDEO),a(this,kt).delete(me.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);x(this,Tn,rd).call(this,me.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ve.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),x(this,Tn,rd).call(this,me.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Dt("track undefined");const t=x(this,at,At).call(this,me.MIC);if(t){const n=await t;if(a(this,j).producers.has(n)){const o=a(this,j).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,xt)&&(a(this,xt).audioTrack=s,a(this,xt).producerId=n,a(this,xt).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=x(this,hu,qv).call(this,s),r=()=>{a(this,kt).delete(me.MIC)},i=a(this,j).createProducer(e,r);x(this,Tn,rd).call(this,me.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,xt)&&(a(this,xt).audioTrack=n.track,a(this,xt).producerId=n.id,a(this,xt).start())})}catch(t){throw new k(t)}}async pauseMic(){var r;const s=await x(this,at,At).call(this,me.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=a(this,xt))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(e))}async pauseWebcam(){const s=await x(this,at,At).call(this,me.WEBCAM),t=await x(this,at,At).call(this,me.WEBCAM_BACKUP),e=a(this,j).producers.get(s),r=a(this,j).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=n=>{const o={producerId:n.id,pause:!0};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await x(this,at,At).call(this,me.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(e))}async resumeWebcam(s=me.WEBCAM){const t=await x(this,at,At).call(this,s),e=a(this,j).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,vt).sendMessage(a(this,Rt).toggleProducer,Ud.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,e=await x(this,at,At).call(this,t);x(this,uu,Hv).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await x(this,at,At).call(this,me.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,xt))==null||t.stop(),a(this,kt).delete(me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await x(this,at,At).call(this,me.SCREENSHARE_VIDEO),t=await x(this,at,At).call(this,me.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Or).clear(),a(this,kt).delete(me.SCREENSHARE_VIDEO),a(this,kt).delete(me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await x(this,at,At).call(this,me.WEBCAM),r=await x(this,at,At).call(this,me.WEBCAM_BACKUP);await a(this,j).closeProducer(e,{stopTrack:!1}),await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await x(this,at,At).call(this,me.SCREENSHARE_VIDEO);await a(this,j).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,j).socketHandler.kickPeer(t)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(s){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await a(this,vt).sendMessagePromise(a(this,Rt).globalPinPeer,UR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,j).producers.get(s.producerId)&&a(this,Or).add(s.consumerPeerId),a(this,Or).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,vt).on(a(this,Rt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Hk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===qs.AUDIO?"audio/opus":"video/VP8"),i.kind===qs.VIDEO&&!i.screenShare&&((e=(t=a(this,Ka).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Wt[0]))>=0&&a(this,Sn).get(Wt[0]).has(r)&&i.mimeType!==Wt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===qs.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,vt).on(a(this,Rt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=tf.fromBinary(s);if(o)return;const c=r===qs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(tf.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.PRODUCER_TOGGLE,{peerId:t,producerId:n,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===n).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,vt).on(a(this,Rt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=ah.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Or).delete(t),a(this,j).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,vt).on(a(this,Rt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=Gk.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,j).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),a(this,j).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,j).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),a(this,vt).on(a(this,Rt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,gn)&&!a(this,mn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,kc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,j).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(_.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(a(this,j).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,n;for(let o=0;o<=Wt.length;o+=1){const c=Wt[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Wt.length-1){a(this,vn).get(c).add(s);break}}for(let o=0;o<=Wt.length;o+=1){const c=Wt[o];if(((n=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Wt.length-1){a(this,Sn).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,Sn).forEach(t=>t.delete(s)),a(this,vn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Wt[0])&&this.disableWebcam(e)}))}},Cc=new WeakMap,Rc=new WeakMap,vt=new WeakMap,j=new WeakMap,Ka=new WeakMap,Rt=new WeakMap,gn=new WeakMap,mn=new WeakMap,fn=new WeakMap,kc=new WeakMap,fs=new WeakMap,Or=new WeakMap,Ic=new WeakMap,Sn=new WeakMap,vn=new WeakMap,kt=new WeakMap,xt=new WeakMap,hi=new WeakSet,Qa=function(){return this.context.getValue("connectionHandler")},iu=new WeakSet,Vv=async function(s,t,e,r){f(this,Rc,s);try{return a(this,fs)?await a(this,fs):await x(this,Ac,yp).call(this,s,t,e,r),x(this,au,xv).call(this,t),{roomJoined:await x(this,nu,Lv).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1,error:i}}finally{f(this,fs,null)}},nu=new WeakSet,Lv=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Cc,s.roomUuid),f(this,mn,!0),f(this,gn,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},au=new WeakSet,xv=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...ve.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(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},Ac=new WeakSet,yp=async function(s,t,e,r){var i,n;try{(n=a(this,Ic))!=null||f(this,Ic,x(i=gS,ou,Uv).call(i));const o=x(this,cu,Fv).call(this);await x(this,du,$v).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,lu,Bv).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},ou=new WeakSet,Uv=function(){const{ipInfo:s}=ht();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},cu=new WeakSet,Fv=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=t1(s);return f(this,Ka,t),t},du=new WeakSet,$v=async function(s,t,e,r){await oS(async(i,n)=>{if(!a(this,vt).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await a(this,j).socketHandler.joinRoom(t,s,r,e,a(this,Ic))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},lu=new WeakSet,Bv=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(_1(!1))),s.canProduceAudio===H.Allowed){const r=P1(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},at=new WeakSet,At=function(s){return a(this,kt).get(s)},Tn=new WeakSet,rd=function(s,t){return a(this,kt).set(s,t)},uu=new WeakSet,Hv=function(s){return a(this,kt).delete(s)},hu=new WeakSet,qv=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},pu=new WeakSet,jv=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(rp,ou),rp);let re=gS;ce([E.trace("MediaNodeClient.reset",{country:E.location.country})],re.prototype,"reset",1),ce([E.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([E.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([E.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([E.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([E.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([E.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([E.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([E.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([E.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([E.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([E.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([E.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([E.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([E.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([E.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([E.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([E.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([E.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([E.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([E.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([E.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([E.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([E.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([E.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([E.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([E.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([E.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function mS(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 re(s,t);return s.setValue("roomNodeClient",r),r}function fS(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 k1=Object.defineProperty,I1=Object.getOwnPropertyDescriptor,Ni=(s,t,e,r)=>{for(var i=r>1?void 0:r?I1(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&&k1(t,e,i),i};const SS=(iv=class{constructor(s,t,e,r){m(this,It);p(this,"self");p(this,"authToken");m(this,yn,void 0);p(this,"viewType");m(this,Vs,void 0);m(this,Z,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,Z,s),this.viewType=r,this.authToken=n,f(this,yn,i),f(this,Vs,e),this.setupEvents()}get peerId(){return a(this,Z).getValue("peerId")}get telemetry(){return a(this,Z).getValue("telemetry")}get logger(){return a(this,Z).getValue("logger")}get mediaJoined(){return a(this,Z).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=ht(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:ve.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:wm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new SS(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===H.Allowed&&r)try{await a(this,It,ts).shareMic(s),this.self.audioEnabled||a(this,It,ts).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,It,ts).shareWebcam(t);d&&d.id!==t.id&&a(this,Z).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await a(this,It,ts).shareWebcam(d),this.self.videoEnabled||a(this,It,ts).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,It,ts))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,Z).getValue("callstats").callEnded(),a(this,It,ts).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,Z).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,Z).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=fi()),a(this,yn).updateURL(t),a(this,Z).getValue("telemetry").resetPeerId(t),ht().setHeader("tracing-id",t),rr.remapContext(t,a(this,Z)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Vs).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Vs).on(jd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Z).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,Vs).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Vs).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Vs).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Z).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(_.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,Z).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,Z).getValue("callstats").audioOff())}),a(this,Z).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,Z).getValue("callstats").videoOff())}),a(this,Z).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Vs).joinRoom(this.self);a(this,Vs).socket.flush();const e=_h(t.stageType);if(a(this,Z).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,Z).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,Z).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,Z).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,Z).notify("stageStatus");try{(e=a(this,yn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}fS(a(this,Z)),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,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,Z).getAllValues();try{if(e===sr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}mS(a(this,Z),{socket:a(this,yn),peerId:t})}const{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u}=this.self.permissions,{roomJoined:h,error:g}=(o=await((n=a(this,It,ts))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:u})))!=null?o:{};if(!h)throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:g}),g;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(d){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:d}),new k(`${(c=d==null?void 0:d.message)!=null?c:"could not connect to media servers"}`,"0002")}}async leaveMediaRoom(s){const t=a(this,Z).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===sr.Webinar)&&a(this,It,ts)&&(a(this,It,ts).mediaJoined&&s!=="disconnected"&&await a(this,It,ts).leaveRoom(),!(s==="stageLeft"&&t===sr.Livestream)&&(a(this,It,ts).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()}},yn=new WeakMap,Vs=new WeakMap,Z=new WeakMap,It=new WeakSet,ts=function(){return a(this,Z).getValue("roomNodeClient")},iv);let Gr=SS;Ni([E.trace("SelfController.resetSelf")],Gr.prototype,"resetSelf",1),Ni([E.trace("SelfController.setupEvents")],Gr.prototype,"setupEvents",1),Ni([E.trace("SelfController.joinRoom")],Gr.prototype,"joinRoom",1),Ni([E.trace("SelfController.leaveRoom")],Gr.prototype,"leaveRoom",1),Ni([E.trace("SelfController.joinMediaRoom")],Gr.prototype,"joinMediaRoom",1),Ni([E.trace("SelfController.leaveMediaRoom")],Gr.prototype,"leaveMediaRoom",1),Ni([E.trace("SelfController.init")],Gr,"init",1);class A1{constructor(t){m(this,Mc,void 0);f(this,Mc,t)}on(t,e){let r;t===U.roomPeerCount?r=nf.fromBinary.bind(nf):r=bf.fromBinary.bind(bf),a(this,Mc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Mc=new WeakMap;class M1{constructor(t,e){m(this,Oc,void 0);m(this,Dc,void 0);f(this,Oc,e),f(this,Dc,t)}get logger(){return a(this,Dc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=oh.fromBinary.bind(oh),i=oh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Oc).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)})}}Oc=new WeakMap,Dc=new WeakMap;var O1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,Wh=(s,t,e,r)=>{for(var i=r>1?void 0:r?D1(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&&O1(t,e,i),i};class dl{constructor(t,e){m(this,Dr,void 0);m(this,za,void 0);f(this,Dr,e),f(this,za,t)}get logger(){return a(this,za).getValue("logger")}get telemetry(){return a(this,za).getValue("telemetry")}getPolls(){return a(this,Dr).sendMessagePromise(or.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Dr).sendMessage(or.createPoll,kM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Dr).sendMessage(or.votePoll,AM.toBinary(r))}on(t,e){let r,i;switch(t){case or.updatePoll:case or.createPoll:case or.votePoll:{r=yh.fromBinary.bind(yh),i=yh.create();break}}a(this,Dr).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,Dr).removeListeners(t)}}Dr=new WeakMap,za=new WeakMap,Wh([E.trace("PollSocketHandler.getPolls")],dl.prototype,"getPolls",1),Wh([E.trace("PollSocketHandler.createPoll")],dl.prototype,"createPoll",1),Wh([E.trace("PollSocketHandler.votePoll")],dl.prototype,"votePoll",1);var N1=Object.defineProperty,V1=Object.getOwnPropertyDescriptor,L1=(s,t,e,r)=>{for(var i=r>1?void 0:r?V1(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&&N1(t,e,i),i};class vS{constructor(t,e){p(this,"socket");m(this,Zt,void 0);f(this,Zt,t),this.socket=e,this.handleSocketEvents(),a(this,Zt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Zt).getValue("telemetry")}get logger(){return a(this,Zt).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(U.joinRoom,yI.toBinary(e));try{const{peer:n}=Nn.fromBinary((await r).payload);a(this,Zt).getValue("connectionHandler").socketJoined=!0,a(this,Zt).getValue("peerSessionStore").emit(_.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,Zt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,Zt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new k("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return iA.fromBinary((await this.socket.sendMessagePromise(U.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(U.getRoomPeersInfo,lI.toBinary(n));i=lh.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(U.getRoomPeersInfo);t=lh.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(U.getRoomPeersInfo);t=lh.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(U.getPeerInfo,cf.toBinary({peerId:t}));e=Nn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=of.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=of.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=gf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=gf.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(U.broadcastMessage,go.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(U.broadcastToEntity,go.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(U.broadcastToEntity,go.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,bI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,hf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Ym.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,lA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,hA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(jd.updateUserPreset,BA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=go.fromBinary(t);a(this,Zt).getValue("peerSessionStore").emit(_.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(U.broadcastToEntity,({payload:t})=>{try{const e=go.fromBinary(t);a(this,Zt).getValue("peerSessionStore").emit(_.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 U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=Nn.fromBinary.bind(Nn),i=Nn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?pf.fromBinary(n,o):{requests:[]},i=pf.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Cf.fromBinary.bind(Cf);break}case jd.updateUserPreset:{r=ff.fromBinary.bind(ff);break}case bs.peerJoinedBroadcast:case $r.peerJoinedBroadcast:{r=Zm.fromBinary.bind(Zm);break}case bs.selfJoinComplete:case $r.selfJoinComplete:{r=nh.fromBinary.bind(nh);break}case bs.globalPeerPinBroadcast:case $r.globalPeerPinBroadcast:{r=sf.fromBinary.bind(sf);break}case bs.selectedPeer:case $r.selectedPeer:{r=ih.fromBinary.bind(ih);break}case bs.selectedPeerDiff:case $r.selectedPeerDiff:{r=Xm.fromBinary.bind(Xm);break}case bs.leaveRoom:case $r.leaveRoom:{r=ah.fromBinary.bind(ah);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(jd.getUserPresets,NA.toBinary(e)),i=UA.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}}}Zt=new WeakMap,L1([E.trace("RoomSocketHandler.joinRoom")],vS.prototype,"joinRoom",1);class x1{constructor(t){m(this,Ut,void 0);f(this,Ut,t)}async getStageRequests(){const{payload:t}=await a(this,Ut).sendMessagePromise(U.getStageRequests);return t?Th.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Ut).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Ut).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.grantStageAccess,vM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.denyStageAccess,yM.toBinary(e))}joinStage(){return a(this,Ut).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Ut).sendMessagePromise(U.leaveStage,Pf.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Ut).sendMessagePromise(U.leaveStage,Pf.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=wf.fromBinary.bind(wf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=Th.fromBinary.bind(Th);break}case U.peerStageStatusUpdate:{r=rf.fromBinary.bind(rf);break}}a(this,Ut).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,Ut).sendMessagePromise(U.getPeerInfo,cf.toBinary({peerId:t}));return Nn.fromBinary(e.payload)}}Ut=new WeakMap;class U1{constructor(t,e){m(this,Ye,void 0);m(this,Nc,void 0);f(this,Ye,e),f(this,Nc,t)}get logger(){return a(this,Nc).getValue("logger")}addPlugin(t,e){a(this,Ye).sendMessage(G.addPlugin,V0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Ye).sendMessage(G.removePlugin,x0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Ye).sendMessagePromise(G.getPlugins);return t?aM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Ye).sendMessage(G.customPluginEventToRoom,J0.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Ye).sendMessage(G.customPluginEventToPeers,z0.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Ye).sendMessage(G.enablePluginForRoom,F0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.enablePluginForPeers,q0.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Ye).sendMessage(G.disablePluginForRoom,B0.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.disablePluginForPeers,G0.toBinary({pluginId:t,peerIds:e}),r)}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,Ye).sendMessage(G.storeInsertKeys,vf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeGetKeys,Z0.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Ye).sendMessage(G.storeDeleteKeys,tM.toBinary(n),i)}storeDelete(t,e,r){a(this,Ye).sendMessage(G.storeDelete,rM.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,Ye).sendMessage(G.storeInsertKeys,vf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=vh.fromBinary.bind(vh);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Tf.fromBinary.bind(Tf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=Ef.fromBinary.bind(Ef);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=yf.fromBinary.bind(yf);break}}a(this,Ye).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Ye=new WeakMap,Nc=new WeakMap;var F1=Object.defineProperty,$1=(s,t,e)=>t in s?F1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,B1=(s,t,e)=>($1(s,typeof t!="symbol"?t+"":t,e),e),Jh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(Jh(s,t,"read from private field"),e?e.call(s):t.get(s)),Ee=(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)},ie=(s,t,e,r)=>(Jh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(Jh(s,t,"access private method"),e),ll={},H1={get exports(){return ll},set exports(s){ll=s}},Hn=typeof Reflect=="object"?Reflect:null,TS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ul;Hn&&typeof Hn.ownKeys=="function"?ul=Hn.ownKeys:Object.getOwnPropertySymbols?ul=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ul=function(s){return Object.getOwnPropertyNames(s)};function q1(s){console&&console.warn&&console.warn(s)}var yS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}H1.exports=de,ll.once=J1,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var ES=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(de,"defaultMaxListeners",{enumerable:!0,get:function(){return ES},set:function(s){if(typeof s!="number"||s<0||yS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");ES=s}}),de.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},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||yS(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 bS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return bS(this)},de.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")TS(c,this,t);else for(var d=c.length,l=RS(c,d),e=0;e<d;++e)TS(l[e],this,t);return!0};function wS(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=bS(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,q1(c)}return s}de.prototype.addListener=function(s,t){return wS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return wS(this,s,t,!0)};function j1(){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 PS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=j1.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return hl(t),this.on(s,PS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return hl(t),this.prependListener(s,PS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(hl(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():G1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.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 _S(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?W1(i):RS(i,i.length)}de.prototype.listeners=function(s){return _S(this,s,!0)},de.prototype.rawListeners=function(s){return _S(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):CS.call(s,t)},de.prototype.listenerCount=CS;function CS(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}de.prototype.eventNames=function(){return this._eventsCount>0?ul(this._events):[]};function RS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function G1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function W1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function J1(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))}kS(s,t,n,{once:!0}),t!=="error"&&K1(s,i,{once:!0})})}function K1(s,t,e){typeof s.on=="function"&&kS(s,"error",t,e)}function kS(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 z1 extends v{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 IS=new z1;class AS{static encode(t){return IS.toBinary(t)}static decode(t){return IS.fromBinary(new Uint8Array(t))}}function Y1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Wr;class Q1{constructor(t={}){B1(this,"opts"),Ee(this,Wr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Wr,0)}async wait(){ie(this,Wr,O(this,Wr)+1);const t=Y1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Wr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Wr)}reset(){ie(this,Wr,0)}}Wr=new WeakMap;const Jr={debug:0,info:1,warn:2,error:3};var Vi,Li;class X1{constructor(t){Ee(this,Vi,void 0),Ee(this,Li,void 0),ie(this,Vi,console),ie(this,Li,t)}debug(...t){Jr[O(this,Li)]>Jr.debug||O(this,Vi).debug("[Sockrates]:",...t)}info(...t){Jr[O(this,Li)]>Jr.info||O(this,Vi).info("[Sockrates]:",...t)}warn(...t){Jr[O(this,Li)]>Jr.warn||O(this,Vi).warn("[Sockrates]:",...t)}error(...t){Jr[O(this,Li)]>Jr.error||O(this,Vi).error("[Sockrates]:",...t)}}Vi=new WeakMap,Li=new WeakMap;var MS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(MS||{});const Z1="2",eN="3";var De,qn,_e,Ue,Kr,et,hr,zr,Cs,jn,pr,Kh,OS,Co,pl,zh,DS,Yh,NS,gl,Qh,Xh,VS,Ro,ml,ko,fl,Sl,Zh,Gn,Io,Ao,vl;class tN{constructor(t,e){var g,S,y,P,b,R,D,F,L,B;Ee(this,Kh),Ee(this,Co),Ee(this,zh),Ee(this,Yh),Ee(this,gl),Ee(this,Xh),Ee(this,Ro),Ee(this,ko),Ee(this,Sl),Ee(this,Gn),Ee(this,Ao),Ee(this,De,void 0),Ee(this,qn,void 0),Ee(this,_e,void 0),Ee(this,Ue,void 0),Ee(this,Kr,void 0),Ee(this,et,void 0),Ee(this,hr,void 0),Ee(this,zr,void 0),Ee(this,Cs,void 0),Ee(this,jn,void 0),Ee(this,pr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,qn,t),ie(this,Kr,[]),ie(this,et,new ll),ie(this,hr,!0),ie(this,Cs,!1),ie(this,_e,e!=null?e:{}),(g=(r=O(this,_e)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,_e)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=O(this,_e)).pingTimeout)!=null||(n.pingTimeout=3e4),(P=(o=O(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=O(this,_e)).debug)!=null||(c.debug=!0),(R=(d=O(this,_e)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(D=(l=O(this,_e)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(u=O(this,_e)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=O(this,_e)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,zr,{code:void 0,reason:void 0}),ie(this,Ue,(B=O(this,_e).logger)!=null?B:new X1(O(this,_e).debug?"debug":"info")),ie(this,pr,new Q1)}get readyState(){var t;return(t=O(this,De))==null?void 0:t.readyState}get url(){return O(this,qn)}updateURL(t){ie(this,qn,t),Pe(this,Xh,VS).call(this)}get config(){return O(this,_e)}get sendQueue(){return O(this,Kr)}flush(){if(!O(this,_e).queueOnDisconnect)return!1;const t=[];return O(this,Kr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Kr,t),O(this,Kr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Ue).debug("Websocket was already connecting or connected.");return}if(O(this,hr)!==!1)return new Promise((e,r)=>{Pe(this,Gn,Io).call(this),Pe(this,Ao,vl).call(this);try{ie(this,De,new WebSocket(Pe(this,Kh,OS).call(this,O(this,qn)))),O(this,De).binaryType="arraybuffer",O(this,Ue).debug("Connecting");const i=setTimeout(()=>{O(this,Ue).debug("Connection timeout. Closing socket"),ie(this,hr,!0),Pe(this,Ao,vl).call(this),O(this,De).close(3001,"Connection Timeout"),O(this,_e).autoReconnect&&!O(this,Cs)&&(O(this,et).emit("reconnecting"),Pe(this,Ro,ml).call(this)),r(new Error("Connection timed out!"))},O(this,_e).connectionTimeout);O(this,De).onopen=()=>{O(this,Ue).debug(`Ready State: ${MS[O(this,De).readyState]}`),i&&clearTimeout(i),Pe(this,Sl,Zh).call(this),ie(this,zr,{code:void 0,reason:void 0}),O(this,et).emit("connected"),O(this,_e).flushOnReconnect&&this.flush(),e()},O(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Ue).debug("Socket closed. Close event:",{event:n}),O(this,Ue).debug(`Connection closed code: ${o}`),O(this,Ue).debug(`Connection closed reason: ${c}`),O(this,Cs)||Pe(this,gl,Qh).call(this,o,c)}catch(o){Pe(this,Co,pl).call(this,o)}},O(this,De).onerror=n=>{Pe(this,Co,pl).call(this,n)},O(this,De).onmessage=n=>Pe(this,zh,DS).call(this,n)}catch(i){Pe(this,Co,pl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,_e).queueOnDisconnect&&(!O(this,De)||O(this,De).readyState!==1))return O(this,Ue).debug("Queuing message since socket is not connected!",n),O(this,Kr).push(n),!1;const o=AS.encode(n);return Pe(this,ko,fl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,ko,fl).call(this,t)}receive(t,e){return O(this,et).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")){O(this,et).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,et).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,et).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,et).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,hr,!1),Pe(this,Gn,Io).call(this),this.removeAllListeners(),ie(this,zr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,qn=new WeakMap,_e=new WeakMap,Ue=new WeakMap,Kr=new WeakMap,et=new WeakMap,hr=new WeakMap,zr=new WeakMap,Cs=new WeakMap,jn=new WeakMap,pr=new WeakMap,Kh=new WeakSet,OS=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)://.")},Co=new WeakSet,pl=function(s,t){O(this,Ue).error("Error:",{error:s}),O(this,et).emit("errored",{error:s}),t==null||t(s)},zh=new WeakSet,DS=function(s){if(Pe(this,Sl,Zh).call(this),s.data===Z1){O(this,Ue).debug("Received ping from server"),Pe(this,ko,fl).call(this,eN);return}const t=AS.decode(s.data),{id:e,payload:r}=t;O(this,Ue).debug("Received message",{event:t.event,messageID:e}),O(this,et).emit(t.event.toString(),{id:e,payload:r})},Yh=new WeakSet,NS=function(){return O(this,De).readyState===1},gl=new WeakSet,Qh=function(s,t){ie(this,zr,{reason:t,code:s}),O(this,et).emit("disconnected",{code:s,reason:t})},Xh=new WeakSet,VS=function(){const{reason:s,code:t}=O(this,zr);t&&t!==1e3&&O(this,hr)&&O(this,_e).autoReconnect&&!O(this,Cs)&&(O(this,Ue).debug(`Triggering reconnection due to ${s}.`),O(this,et).emit("reconnecting"),Pe(this,Ro,ml).call(this))},Ro=new WeakSet,ml=async function(s=!0){if(s&&O(this,Cs)){O(this,Ue).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Cs)||O(this,pr).reset(),O(this,_e).maxReconnectionAttempts!==null&&O(this,pr).getAttempts()>=O(this,_e).maxReconnectionAttempts){O(this,et).emit("failed"),ie(this,Cs,!1);return}ie(this,Cs,!0),Pe(this,Ao,vl).call(this),Pe(this,Gn,Io).call(this);try{if(await O(this,pr).wait(),O(this,hr)===!1)return;if(O(this,Ue).debug(`Reconnection attempt ${O(this,pr).getAttempts()}`),O(this,et).emit("reconnectAttempt",{attempt:O(this,pr).getAttempts()}),await this.connect(),!Pe(this,Yh,NS).call(this))throw Error("Reconnect Failed");ie(this,Cs,!1),ie(this,zr,{code:void 0,reason:void 0}),O(this,et).emit("reconnected")}catch(t){O(this,Ue).debug("Failed to reconnect."),O(this,et).emit("reconnectFailure",{attempt:O(this,pr).getAttempts()}),Pe(this,Ro,ml).call(this,!1)}},ko=new WeakSet,fl=function(s){try{return O(this,De).send(s),!0}catch(t){return O(this,Ue).error(t.message),!1}},Sl=new WeakSet,Zh=function(){this.config.disconnectOnPingTimeout&&(O(this,Ue).debug("Resetting ping timeout"),Pe(this,Gn,Io).call(this),ie(this,jn,setTimeout(()=>{var s;O(this,Ue).debug("Disconnecting the socket due to ping timeout"),ie(this,hr,!0);const t=3002,e="Ping timeout";(s=O(this,De))==null||s.close(t,e),Pe(this,gl,Qh).call(this,t,e)},O(this,_e).pingTimeout)))},Gn=new WeakSet,Io=function(){O(this,jn)&&(clearTimeout(O(this,jn)),ie(this,jn,void 0))},Ao=new WeakSet,vl=function(){O(this,De)&&(O(this,De).onopen=void 0,O(this,De).onerror=void 0,O(this,De).onmessage=void 0,O(this,De).onclose=void 0)};var sN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,Tl=(s,t,e,r)=>{for(var i=r>1?void 0:r?rN(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&&sN(t,e,i),i};const LS=65535,iN=3e3,xS=(nv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Me);m(this,Vc);m(this,Lc);m(this,pi,void 0);m(this,Ae,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ss,void 0);m(this,ot,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,Ss,void 0),f(this,ot,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,pi,x(this,Vc,Ep).call(this,t)),f(this,Ae,new tN(a(this,pi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Me,je).socketJoinAttempted}set joinAttempted(s){a(this,Me,je).socketJoinAttempted=s}get telemetry(){return a(this,ot).getValue("telemetry")}get logger(){return a(this,ot).getValue("logger")}get peerId(){return a(this,ot).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,pi,x(this,Vc,Ep).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ae).updateURL(a(this,pi))}static getSocketEdgeDomain(s){return bi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,pi)}async connect(){a(this,Me,je).socketJoinAttempted=!0,await a(this,Ae).connect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Me,je).socketJoinAttempted=!1,a(this,Ae).disconnect(),a(this,Me,je).socketJoinAttempted=!0,a(this,Me,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ae).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ot).getValue("telemetry").injectContext(r),a(this,Ae).send(s,e!=null?e:x(this,Lc,bp).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,Ae).removeListener(n,y),a(this,Ae).removeListener(LS,P),a(this,Ae).removeListener($r.errorResponse,P),a(this,Ae).removeListener(bs.errorResponse,P)},l=r!=null?r:x(this,Lc,bp).call(this),u={};a(this,ot).getValue("telemetry").injectContext(u);const g=({id:y,payload:P})=>{if(l===y){let b;try{const R=sk.fromBinary(P);b=new Error(R.errorMessage)}catch(R){b=new Error("failed to parse error message",{cause:R});try{const D=rI.fromBinary(P);b=new Error(D.message)}catch(D){b=new Error("failed to parse error message",{cause:D})}}c(b),d(S,g)}},S=({id:y,payload:P})=>{l===y&&(o({id:y,payload:P}),d(S,g))};a(this,Ae).on(n,S),a(this,Ae).on(LS,g),a(this,Ae).on($r.errorResponse,g),a(this,Ae).on(bs.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ae).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ae).on(s,t)}onStateEvent(s,t){a(this,Ae).on(s,t)}removeListener(s,t){a(this,Ae).removeListener(s,t)}removeListeners(s){a(this,Ae).removeListeners(s)}flush(){return a(this,Ae).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ss)&&(clearTimeout(a(this,Ss)),f(this,Ss,void 0)),a(this,Me,je).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:E.location.country});const{recv:e,send:r}=(i=a(this,Me,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Bn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Bn.CONNECTED?a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}):f(this,Ss,setTimeout(()=>{a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Me,je).joinAttempted}),f(this,Ss,void 0)},iN)),a(this,Me,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),a(this,Me,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Me,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Me,je).mediaJoinAttempted}}),a(this,Ss)&&(clearTimeout(a(this,Ss)),f(this,Ss,void 0)),a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Me,je).mediaJoinAttempted}),a(this,Me,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),a(this,ot).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED),a(this,Me,je).updateSocketConnectionState("failed")})}},pi=new WeakMap,Ae=new WeakMap,Me=new WeakSet,je=function(){return a(this,ot).getValue("connectionHandler")},Ss=new WeakMap,ot=new WeakMap,Vc=new WeakSet,Ep=function(s){let t=xS.getSocketEdgeDomain(a(this,ot).getValue("baseURI"));typeof On(a(this,ot),"socket_server_base")=="string"&&(t=On(a(this,ot),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Fd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Lc=new WeakSet,bp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},nv);let Mo=xS;Tl([E.trace("SocketService.connect")],Mo.prototype,"connect",1),Tl([E.trace("SocketService.disconnect")],Mo.prototype,"disconnect",1),Tl([E.trace("SocketService.sendMessagePromise")],Mo.prototype,"sendMessagePromise",1),Tl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Mo.prototype,"sendMessagePromiseWithTimeout",1);class nN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=AI.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=sA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=uf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return lf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return WI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,NI.toBinary({payloads:t}));return lf.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(U.deleteConnectedRooms,jI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,XI.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 aN=Object.defineProperty,oN=Object.getOwnPropertyDescriptor,cN=(s,t,e,r)=>{for(var i=r>1?void 0:r?oN(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&&aN(t,e,i),i};class US extends $t{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Ls,void 0);f(this,Ls,e)}get supportsConnectedMeetings(){return a(this,Ls).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
19
19
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,Ls).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Ls).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Ls).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(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,Ls).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ls).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.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ls).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})}}Ls=new WeakMap,cN([Mt({maxInvocations:60,period:60})],US.prototype,"getConnectedMeetings",1);var dN=Object.defineProperty,lN=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?lN(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&&dN(t,e,i),i};const FS=(av=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new US(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new FS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).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;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
20
20
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).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 BS.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).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,Se).getValue("self");r.self.setName(a(this,Se).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,Se).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,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).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,Se).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})}},Se=new WeakMap,av);let yl=FS;ep([E.trace("ConnectedMeetingsController.getConnectedMeetings")],yl.prototype,"getConnectedMeetings",1),ep([E.trace("ConnectedMeetingsController.setupEvents")],yl.prototype,"setupEvents",1),ep([E.trace("ConnectedMeetingsController.switchMeeting")],yl.prototype,"switchMeeting",1);var uN=Object.defineProperty,hN=Object.getOwnPropertyDescriptor,El=(s,t,e,r)=>{for(var i=r>1?void 0:r?hN(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&&uN(t,e,i),i};const Wn=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(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 L,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(fS(s),ve.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=nO(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 $O(s);s.setValue("connectionHandler",l);const u=Wn.createSocketService(s),h=u.connect(),g=d.getUserDetails(),S=d.getPlugins();let y,P="";try{await Wn.setupFlagsmith(s)}catch(W){c.error("Failed to setup flagsmith",{error:W})}try{await h}catch(W){c.error("[Controller]: Failed to connect to socket server:",{error:W})}try{({meetingTitle:P}=await d.getRoomNodeData()),y=await g,c.info("CF SFU is being used."),s.setValue("presetName",y.preset.name)}catch(W){c.error("Failed to get room metadata",{error:W})}const b=Dh.init(y.preset,!s.getValue("modules").theme),R=Vh.init(s,b.viewType,y.preset.permissions),D=Wn.setupControllers(u,s,y,S,P,b,R);IO(b)&&((L=Wn.createRoomNodeClient(s,u).initializeConnection(y.participant.name,i,!1,R))==null||L.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),E.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:F}=await D;return lC(),new Wn(e,F,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=dC(i),d={entity:Yu.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...ve.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?bi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${Yu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var V,C,Je;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(V=g.enableHighBitrate)!=null?V:!1,enableStereo:(C=g.enableStereo)!=null?C:!1}},...l}),t.setValue("maxPreferredStreams",ve.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,P,b,R,D,F,L,B;const W=new M1(t,s),ae=new nN(s);t.setValue("connectedMeetingsSocketHandler",ae);const Tt=new dl(t,s),xs=new cr(t,s),_n=new x1(s),Us=new vS(t,s),I=new U1(t,s),T=new A1(s),w=await Gr.init(t,Us,d,o,n);t.setValue("selfController",w);const $=await Vf.init(t,w.self,Us,W,i);if(c.participant&&(L=new ur(t,w.self,Us)),(Je=c.e2ee)!=null&&Je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await as.init(t,xs,w.self,L.participants)),c.internals&&(R=await kh.init(t)),c.livestream&&n.viewType===sr.Livestream&&t.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&(F=new sS(t,w.self,T)),c.poll&&(S=await Mf.init(t,w.self,Tt)),c.recording&&(D=new $f(t,w.self,Us)),c.stage&&(P=new Lf(t,_n,Us,w.self,L.participants)),c.plugin){if(!L)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Nr=await r;b=await So.init(t,Nr,I,xs,y==null?void 0:y.chat,w.self,L.participants,i)}if(c.connectedMeetings&&(B=await yl.init(t)),c.pip){const Nr=await Qu._init(t,w.self);t.setValue("pip",Nr)}const qe={storesManager:new xD(t,I),pollController:S,selfController:w,metaController:$,chatController:y,stageController:P,pluginController:b,recordingController:D,internalsController:R,livestreamController:F,participantController:L,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:qe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return mS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Mo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Oo=Wn;El([E.trace("Controller.init")],Oo,"init",1),El([E.trace("setupFlagsmith")],Oo,"setupFlagsmith",1),El([E.trace("Controller.createRoomNodeClient")],Oo,"createRoomNodeClient",1),El([E.trace("Controller.createSocketService")],Oo,"createSocketService",1);class pN{constructor(){p(this,"battery");p(this,"logger");p(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)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(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 $S=new pN;function gN(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=wi.baseURI.prod;t&&(n=t);const o=`https://${bi({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}class mN{constructor(){m(this,gu);m(this,gi,new Audio);m(this,En,new MediaStream);m(this,bn,new Map);m(this,xc,void 0);a(this,gi).srcObject=a(this,En),a(this,gi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,bn).has(e.id)||(a(this,En).addTrack(e),a(this,bn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,gi).setSinkId(t)}removeTrack(t){const e=a(this,bn).get(t);e&&(a(this,En).removeTrack(e),a(this,bn).delete(t))}async play(){return a(this,gi).srcObject=a(this,En),a(this,gi).play().catch(t=>{x(this,gu,Gv).call(this,t)})}onError(t){f(this,xc,t)}}gi=new WeakMap,En=new WeakMap,bn=new WeakMap,xc=new WeakMap,gu=new WeakSet,Gv=function(t){var e;(e=a(this,xc))==null||e.call(this,t)};class fN extends mN{constructor(){super();m(this,wn,void 0);f(this,wn,new Map)}addParticipantTrack(e,r){a(this,wn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,wn).get(e);r&&this.removeTrack(r),a(this,wn).delete(e)}}wn=new WeakMap;var SN=Object.defineProperty,vN=Object.getOwnPropertyDescriptor,bl=(s,t,e,r)=>{for(var i=r>1?void 0:r?vN(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&&SN(t,e,i),i};let Yr=(ov=class{constructor(t,e){m(this,Qe,void 0);m(this,Pn,void 0);f(this,Pn,t),f(this,Qe,e)}get peerId(){return a(this,Pn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:fi(),n=rr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new nS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var g,S,y,P,b,R;ve.init();const e=(S=(g=t==null?void 0:t.cachedUserDetails)==null?void 0:g.peerId)!=null?S:fi(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=gN(r,i);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Yr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");zv(l),$S.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(P=(y=t.modules)==null?void 0:y.tracing)!=null?P:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(b=t.authToken)==null?void 0:b.slice(0,10)}...
21
- ${(R=t.authToken)==null?void 0:R.slice(-10)}`}});const u=await Oo.init(c),h=new Yr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=rr.createContext(t,e),o={...Z_,...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",eC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",ws(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.5-staging.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new fN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){$S.cleanup(),a(this,Pn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Qe).stageController)==null?void 0:t.stage}get stores(){return a(this,Qe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Qe=new WeakMap,Pn=new WeakMap,ov);bl([lt("0002"),dr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Yr.prototype,"join",1),bl([lt("0003")],Yr.prototype,"leave",1),bl([lt("0001"),dr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Yr,"init",1),Yr=bl([lt("0000")],Yr);const BS=Yr;return BS}();
21
+ ${(R=t.authToken)==null?void 0:R.slice(-10)}`}});const u=await Oo.init(c),h=new Yr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=rr.createContext(t,e),o={...Z_,...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",eC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",ws(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.5-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new fN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){$S.cleanup(),a(this,Pn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Qe).stageController)==null?void 0:t.stage}get stores(){return a(this,Qe).storesManager}get audio(){return a(this,Pn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Qe=new WeakMap,Pn=new WeakMap,ov);bl([lt("0002"),dr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Yr.prototype,"join",1),bl([lt("0003")],Yr.prototype,"leave",1),bl([lt("0001"),dr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Yr,"init",1),Yr=bl([lt("0000")],Yr);const BS=Yr;return BS}();