@cloudflare/realtimekit 1.3.0-staging.2 → 1.3.0
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 +1 -1
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +1 -1
- package/dist/index.rn.js +1 -1
- package/package.json +3 -2
package/dist/browser.js
CHANGED
|
@@ -18,4 +18,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,kr)},
|
|
|
18
18
|
maxEnergy: ${a(this,ui)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,kr)||i<a(this,kr))&&f(this,kr,i),(!a(this,ui)||i>a(this,ui))&&f(this,ui,i),{energy:(i-a(this,kr))/(a(this,ui)-a(this,kr))*10||0,isVoice:r})},Pc=new WeakSet,Tp=function(t){return t<5},su=new WeakSet,Ov=function(t=a(this,pn)){var r;if(!a(this,Ns)||!t){a(this,Ir).getValue("flagsmith").hasFeature(Z.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,Dv=function(t){const e=Math.log10(t);return Math.round(e)},m(Ro,Pc),m(Ro,ru);const E1=(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}},w1=(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 b1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?P1(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&&b1(t,e,i),i};const Wt=["video/VP9","video/VP8"],pS=(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,Rc,void 0);m(this,Cc,void 0);m(this,vt,void 0);m(this,j,void 0);m(this,Ka,void 0);m(this,kt,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,Mr,void 0);m(this,Ic,void 0);m(this,Sn,void 0);m(this,vn,void 0);m(this,It,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 S1(s,e)),f(this,kt,a(this,j).events),f(this,Mr,new Set),f(this,It,new Map),f(this,mn,!1),f(this,fn,new Uh(s.getValue("logger"))),f(this,xt,new Ro(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,Cc),a(this,Rc),!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,It).clear(),a(this,Mr).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,Nv).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,kt).leaveRoom,yC.toBinary(s)).then(e=>{var r;(r=ck.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,S,y;const e=t==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,r=x(this,at,Mt).call(this,e);if(r){const w=await r;if(a(this,j).producers.has(w)){const b=a(this,j).producers.get(w);if(!b.closed)return await b.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Wt.filter(w=>w!==t)),n=x(this,pu,qv).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||!((y=(S=this.context)==null?void 0:S.getValue("theme"))!=null&&y.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=sD(this.context,s)),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,It).delete(e)},u=a(this,j).createProducer(n,l);return x(this,Tn,rd).call(this,e,u.then(w=>w.id)),u.then(w=>w.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(Z.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:be.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).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:be.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 Nt("track undefined");const t=x(this,at,Mt).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,Hv).call(this,s),r=()=>{a(this,It).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,Mt).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,kt).toggleProducer,xd.toBinary(e))}async pauseWebcam(){const s=await x(this,at,Mt).call(this,me.WEBCAM),t=await x(this,at,Mt).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,kt).toggleProducer,xd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await x(this,at,Mt).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,kt).toggleProducer,xd.toBinary(e))}async resumeWebcam(s=me.WEBCAM){const t=await x(this,at,Mt).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,kt).toggleProducer,xd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?me.WEBCAM:me.WEBCAM_BACKUP,e=await x(this,at,Mt).call(this,t);x(this,uu,Bv).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await x(this,at,Mt).call(this,me.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,xt))==null||t.stop(),a(this,It).delete(me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await x(this,at,Mt).call(this,me.SCREENSHARE_VIDEO),t=await x(this,at,Mt).call(this,me.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Mr).clear(),a(this,It).delete(me.SCREENSHARE_VIDEO),a(this,It).delete(me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await x(this,at,Mt).call(this,me.WEBCAM),r=await x(this,at,Mt).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,Mt).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,kt).globalPinPeer,NC.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,Mr).add(s.consumerPeerId),a(this,Mr).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,kt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Uk.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,kt).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,kt).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,Mr).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,kt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=Bk.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,kt).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(Z.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)}))}},Rc=new WeakMap,Cc=new WeakMap,vt=new WeakMap,j=new WeakMap,Ka=new WeakMap,kt=new WeakMap,gn=new WeakMap,mn=new WeakMap,fn=new WeakMap,kc=new WeakMap,fs=new WeakMap,Mr=new WeakMap,Ic=new WeakMap,Sn=new WeakMap,vn=new WeakMap,It=new WeakMap,xt=new WeakMap,hi=new WeakSet,Qa=function(){return this.context.getValue("connectionHandler")},iu=new WeakSet,Nv=async function(s,t,e,r){f(this,Cc,s);try{return a(this,fs)?await a(this,fs):await x(this,Ac,yp).call(this,s,t,e,r),x(this,au,Lv).call(this,t),{roomJoined:await x(this,nu,Vv).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,Vv=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Rc,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,Lv=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...be.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=pS,ou,xv).call(i));const o=x(this,cu,Uv).call(this);await x(this,du,Fv).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,lu,$v).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},ou=new WeakSet,xv=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,Uv=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=XD(s);return f(this,Ka,t),t},du=new WeakSet,Fv=async function(s,t,e,r){await aS(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,$v=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(w1(!1))),s.canProduceAudio===H.Allowed){const r=E1(!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,Mt=function(s){return a(this,It).get(s)},Tn=new WeakSet,rd=function(s,t){return a(this,It).set(s,t)},uu=new WeakSet,Bv=function(s){return a(this,It).delete(s)},hu=new WeakSet,Hv=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},pu=new WeakSet,qv=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=pS;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 gS(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 mS(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 _1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,Ni=(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&&_1(t,e,i),i};const fS=(rv=class{constructor(s,t,e,r){m(this,At);p(this,"self");p(this,"authToken");m(this,yn,void 0);p(this,"viewType");m(this,Vs,void 0);m(this,X,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,X,s),this.viewType=r,this.authToken=n,f(this,yn,i),f(this,Vs,e),this.setupEvents()}get peerId(){return a(this,X).getValue("peerId")}get telemetry(){return a(this,X).getValue("telemetry")}get logger(){return a(this,X).getValue("logger")}get mediaJoined(){return a(this,X).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(Z.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:be.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:bm(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 fS(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,At,ts).shareMic(s),this.self.audioEnabled||a(this,At,ts).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,At,ts).shareWebcam(t);d&&d.id!==t.id&&a(this,X).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&await a(this,At,ts).shareWebcam(d),this.self.videoEnabled||a(this,At,ts).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,At,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,X).getValue("callstats").callEnded(),a(this,At,ts).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,X).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,X).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,X).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,X).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(t=fi()),a(this,yn).updateURL(t),a(this,X).getValue("telemetry").resetPeerId(t),ht().setHeader("tracing-id",t),sr.remapContext(t,a(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,X).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(qd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,X).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,X).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,X).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,X).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,X).getValue("callstats").audioOff())}),a(this,X).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,X).getValue("callstats").videoOff())}),a(this,X).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,X).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,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,X).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,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,X).notify("stageStatus");try{(e=a(this,yn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}mS(a(this,X)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,X).getAllValues();try{if(e===tr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}gS(a(this,X),{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,At,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,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===tr.Webinar)&&a(this,At,ts)&&(a(this,At,ts).mediaJoined&&s!=="disconnected"&&await a(this,At,ts).leaveRoom(),!(s==="stageLeft"&&t===tr.Livestream)&&(a(this,At,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,X=new WeakMap,At=new WeakSet,ts=function(){return a(this,X).getValue("roomNodeClient")},rv);let jr=fS;Ni([E.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Ni([E.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Ni([E.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Ni([E.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Ni([E.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Ni([E.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Ni([E.trace("SelfController.init")],jr,"init",1);class C1{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=wf.fromBinary.bind(wf),a(this,Mc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Mc=new WeakMap;class k1{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 I1=Object.defineProperty,A1=Object.getOwnPropertyDescriptor,Wh=(s,t,e,r)=>{for(var i=r>1?void 0:r?A1(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&&I1(t,e,i),i};class cl{constructor(t,e){m(this,Or,void 0);m(this,za,void 0);f(this,Or,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,Or).sendMessagePromise(ar.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Or).sendMessage(ar.createPoll,PM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Or).sendMessage(ar.votePoll,RM.toBinary(r))}on(t,e){let r,i;switch(t){case ar.updatePoll:case ar.createPoll:case ar.votePoll:{r=yh.fromBinary.bind(yh),i=yh.create();break}}a(this,Or).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,Or).removeListeners(t)}}Or=new WeakMap,za=new WeakMap,Wh([E.trace("PollSocketHandler.getPolls")],cl.prototype,"getPolls",1),Wh([E.trace("PollSocketHandler.createPoll")],cl.prototype,"createPoll",1),Wh([E.trace("PollSocketHandler.votePoll")],cl.prototype,"votePoll",1);var M1=Object.defineProperty,O1=Object.getOwnPropertyDescriptor,D1=(s,t,e,r)=>{for(var i=r>1?void 0:r?O1(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&&M1(t,e,i),i};class SS{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,fI.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 eA.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,aI.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,mo.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,mo.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,mo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,vI.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,aA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,cA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(qd.updateUserPreset,xA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=mo.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=mo.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=Rf.fromBinary.bind(Rf);break}case qd.updateUserPreset:{r=ff.fromBinary.bind(ff);break}case ws.peerJoinedBroadcast:case Fr.peerJoinedBroadcast:{r=Zm.fromBinary.bind(Zm);break}case ws.selfJoinComplete:case Fr.selfJoinComplete:{r=nh.fromBinary.bind(nh);break}case ws.globalPeerPinBroadcast:case Fr.globalPeerPinBroadcast:{r=sf.fromBinary.bind(sf);break}case ws.selectedPeer:case Fr.selectedPeer:{r=ih.fromBinary.bind(ih);break}case ws.selectedPeerDiff:case Fr.selectedPeerDiff:{r=Xm.fromBinary.bind(Xm);break}case ws.leaveRoom:case Fr.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(qd.getUserPresets,AA.toBinary(e)),i=NA.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,D1([E.trace("RoomSocketHandler.joinRoom")],SS.prototype,"joinRoom",1);class N1{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,gM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Ut).sendMessage(U.denyStageAccess,fM.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=bf.fromBinary.bind(bf);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 V1{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,M0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Ye).sendMessage(G.removePlugin,D0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Ye).sendMessagePromise(G.getPlugins);return t?sM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Ye).sendMessage(G.customPluginEventToRoom,q0.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,G0.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Ye).sendMessage(G.enablePluginForRoom,V0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.enablePluginForPeers,F0.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Ye).sendMessage(G.disablePluginForRoom,x0.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Ye).sendMessage(G.disablePluginForPeers,B0.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,Q0.toBinary(n),i)}storeDelete(t,e,r){a(this,Ye).sendMessage(G.storeDelete,Z0.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 L1=Object.defineProperty,x1=(s,t,e)=>t in s?L1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,U1=(s,t,e)=>(x1(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)),ye=(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),dl={},F1={get exports(){return dl},set exports(s){dl=s}},Hn=typeof Reflect=="object"?Reflect:null,vS=Hn&&typeof Hn.apply=="function"?Hn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ll;Hn&&typeof Hn.ownKeys=="function"?ll=Hn.ownKeys:Object.getOwnPropertySymbols?ll=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ll=function(s){return Object.getOwnPropertyNames(s)};function $1(s){console&&console.warn&&console.warn(s)}var TS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}F1.exports=de,dl.once=j1,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var yS=10;function ul(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return yS},set:function(s){if(typeof s!="number"||s<0||TS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");yS=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||TS(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 ES(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return ES(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")vS(c,this,t);else for(var d=c.length,l=RS(c,d),e=0;e<d;++e)vS(l[e],this,t);return!0};function wS(s,t,e,r){var i,n,o;if(ul(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=ES(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,$1(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 B1(){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 bS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=B1.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return ul(t),this.on(s,bS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return ul(t),this.prependListener(s,bS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(ul(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():H1(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 PS(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?q1(i):RS(i,i.length)}de.prototype.listeners=function(s){return PS(this,s,!0)},de.prototype.rawListeners=function(s){return PS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):_S.call(s,t)},de.prototype.listenerCount=_S;function _S(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?ll(this._events):[]};function RS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function H1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function q1(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))}CS(s,t,n,{once:!0}),t!=="error"&&G1(s,i,{once:!0})})}function G1(s,t,e){typeof s.on=="function"&&CS(s,"error",t,e)}function CS(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 W1 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 kS=new W1;class IS{static encode(t){return kS.toBinary(t)}static decode(t){return kS.fromBinary(new Uint8Array(t))}}function J1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class K1{constructor(t={}){U1(this,"opts"),ye(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Gr,0)}async wait(){ie(this,Gr,O(this,Gr)+1);const t=J1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ie(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Vi,Li;class z1{constructor(t){ye(this,Vi,void 0),ye(this,Li,void 0),ie(this,Vi,console),ie(this,Li,t)}debug(...t){Wr[O(this,Li)]>Wr.debug||O(this,Vi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,Li)]>Wr.info||O(this,Vi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,Li)]>Wr.warn||O(this,Vi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,Li)]>Wr.error||O(this,Vi).error("[Sockrates]:",...t)}}Vi=new WeakMap,Li=new WeakMap;var AS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(AS||{});const Y1="2",Q1="3";var De,qn,_e,Ue,Jr,et,ur,Kr,Rs,jn,hr,Kh,MS,Co,hl,zh,OS,Yh,DS,pl,Qh,Xh,NS,ko,gl,Io,ml,fl,Zh,Gn,Ao,Mo,Sl;class X1{constructor(t,e){var g,S,y,w,b,C,D,F,L,B;ye(this,Kh),ye(this,Co),ye(this,zh),ye(this,Yh),ye(this,pl),ye(this,Xh),ye(this,ko),ye(this,Io),ye(this,fl),ye(this,Gn),ye(this,Mo),ye(this,De,void 0),ye(this,qn,void 0),ye(this,_e,void 0),ye(this,Ue,void 0),ye(this,Jr,void 0),ye(this,et,void 0),ye(this,ur,void 0),ye(this,Kr,void 0),ye(this,Rs,void 0),ye(this,jn,void 0),ye(this,hr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,qn,t),ie(this,Jr,[]),ie(this,et,new dl),ie(this,ur,!0),ie(this,Rs,!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),(w=(o=O(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=O(this,_e)).debug)!=null||(c.debug=!0),(C=(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,Kr,{code:void 0,reason:void 0}),ie(this,Ue,(B=O(this,_e).logger)!=null?B:new z1(O(this,_e).debug?"debug":"info")),ie(this,hr,new K1)}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,NS).call(this)}get config(){return O(this,_e)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,_e).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Jr,t),O(this,Jr)}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,ur)!==!1)return new Promise((e,r)=>{Pe(this,Gn,Ao).call(this),Pe(this,Mo,Sl).call(this);try{ie(this,De,new WebSocket(Pe(this,Kh,MS).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,ur,!0),Pe(this,Mo,Sl).call(this),O(this,De).close(3001,"Connection Timeout"),O(this,_e).autoReconnect&&!O(this,Rs)&&(O(this,et).emit("reconnecting"),Pe(this,ko,gl).call(this)),r(new Error("Connection timed out!"))},O(this,_e).connectionTimeout);O(this,De).onopen=()=>{O(this,Ue).debug(`Ready State: ${AS[O(this,De).readyState]}`),i&&clearTimeout(i),Pe(this,fl,Zh).call(this),ie(this,Kr,{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,Rs)||Pe(this,pl,Qh).call(this,o,c)}catch(o){Pe(this,Co,hl).call(this,o)}},O(this,De).onerror=n=>{Pe(this,Co,hl).call(this,n)},O(this,De).onmessage=n=>Pe(this,zh,OS).call(this,n)}catch(i){Pe(this,Co,hl).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,Jr).push(n),!1;const o=IS.encode(n);return Pe(this,Io,ml).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Io,ml).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,ur,!1),Pe(this,Gn,Ao).call(this),this.removeAllListeners(),ie(this,Kr,{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,Jr=new WeakMap,et=new WeakMap,ur=new WeakMap,Kr=new WeakMap,Rs=new WeakMap,jn=new WeakMap,hr=new WeakMap,Kh=new WeakSet,MS=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,hl=function(s,t){O(this,Ue).error("Error:",{error:s}),O(this,et).emit("errored",{error:s}),t==null||t(s)},zh=new WeakSet,OS=function(s){if(Pe(this,fl,Zh).call(this),s.data===Y1){O(this,Ue).debug("Received ping from server"),Pe(this,Io,ml).call(this,Q1);return}const t=IS.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,DS=function(){return O(this,De).readyState===1},pl=new WeakSet,Qh=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,et).emit("disconnected",{code:s,reason:t})},Xh=new WeakSet,NS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,ur)&&O(this,_e).autoReconnect&&!O(this,Rs)&&(O(this,Ue).debug(`Triggering reconnection due to ${s}.`),O(this,et).emit("reconnecting"),Pe(this,ko,gl).call(this))},ko=new WeakSet,gl=async function(s=!0){if(s&&O(this,Rs)){O(this,Ue).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Rs)||O(this,hr).reset(),O(this,_e).maxReconnectionAttempts!==null&&O(this,hr).getAttempts()>=O(this,_e).maxReconnectionAttempts){O(this,et).emit("failed"),ie(this,Rs,!1);return}ie(this,Rs,!0),Pe(this,Mo,Sl).call(this),Pe(this,Gn,Ao).call(this);try{if(await O(this,hr).wait(),O(this,ur)===!1)return;if(O(this,Ue).debug(`Reconnection attempt ${O(this,hr).getAttempts()}`),O(this,et).emit("reconnectAttempt",{attempt:O(this,hr).getAttempts()}),await this.connect(),!Pe(this,Yh,DS).call(this))throw Error("Reconnect Failed");ie(this,Rs,!1),ie(this,Kr,{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,hr).getAttempts()}),Pe(this,ko,gl).call(this,!1)}},Io=new WeakSet,ml=function(s){try{return O(this,De).send(s),!0}catch(t){return O(this,Ue).error(t.message),!1}},fl=new WeakSet,Zh=function(){this.config.disconnectOnPingTimeout&&(O(this,Ue).debug("Resetting ping timeout"),Pe(this,Gn,Ao).call(this),ie(this,jn,setTimeout(()=>{var s;O(this,Ue).debug("Disconnecting the socket due to ping timeout"),ie(this,ur,!0);const t=3002,e="Ping timeout";(s=O(this,De))==null||s.close(t,e),Pe(this,pl,Qh).call(this,t,e)},O(this,_e).pingTimeout)))},Gn=new WeakSet,Ao=function(){O(this,jn)&&(clearTimeout(O(this,jn)),ie(this,jn,void 0))},Mo=new WeakSet,Sl=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 Z1=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,vl=(s,t,e,r)=>{for(var i=r>1?void 0:r?eN(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&&Z1(t,e,i),i};const VS=65535,tN=3e3,LS=(iv=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 X1(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 wi({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,wp).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,w)=>{a(this,Ae).removeListener(n,y),a(this,Ae).removeListener(VS,w),a(this,Ae).removeListener(Fr.errorResponse,w),a(this,Ae).removeListener(ws.errorResponse,w)},l=r!=null?r:x(this,Lc,wp).call(this),u={};a(this,ot).getValue("telemetry").injectContext(u);const g=({id:y,payload:w})=>{if(l===y){let b;try{const C=XC.fromBinary(w);b=new Error(C.errorMessage)}catch(C){b=new Error("failed to parse error message",{cause:C});try{const D=Zk.fromBinary(w);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:w})=>{l===y&&(o({id:y,payload:w}),d(S,g))};a(this,Ae).on(n,S),a(this,Ae).on(VS,g),a(this,Ae).on(Fr.errorResponse,g),a(this,Ae).on(ws.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)},tN)),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=LS.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=>Ud[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,wp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},iv);let Oo=LS;vl([E.trace("SocketService.connect")],Oo.prototype,"connect",1),vl([E.trace("SocketService.disconnect")],Oo.prototype,"disconnect",1),vl([E.trace("SocketService.sendMessagePromise")],Oo.prototype,"sendMessagePromise",1),vl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Oo.prototype,"sendMessagePromiseWithTimeout",1);class sN{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=RI.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=XI.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 HI.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,AI.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,$I.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,KI.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 rN=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,nN=(s,t,e,r)=>{for(var i=r>1?void 0:r?iN(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&&rN(t,e,i),i};class xS 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,nN([Ot({maxInvocations:60,period:60})],xS.prototype,"getConnectedMeetings",1);var aN=Object.defineProperty,oN=Object.getOwnPropertyDescriptor,ep=(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};const US=(nv=class{constructor(s){p(this,"connectedMeetings");m(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new xS(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new US(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 $S.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,nv);let Tl=US;ep([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Tl.prototype,"getConnectedMeetings",1),ep([E.trace("ConnectedMeetingsController.setupEvents")],Tl.prototype,"setupEvents",1),ep([E.trace("ConnectedMeetingsController.switchMeeting")],Tl.prototype,"switchMeeting",1);var cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,yl=(s,t,e,r)=>{for(var i=r>1?void 0:r?dN(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&&cN(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(mS(s),be.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=tO(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 LO(s);s.setValue("connectionHandler",l);const u=Wn.createSocketService(s),h=u.connect(),g=d.getUserDetails(),S=d.getPlugins();let y,w="";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:w}=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);s.setValue("theme",b);const C=Vh.init(s,b.viewType,y.preset.permissions),D=Wn.setupControllers(u,s,y,S,w,b,C);_O(b)&&((L=Wn.createRoomNodeClient(s,u).initializeConnection(y.participant.name,i,!1,C))==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 aR(),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=nR(i),d={entity:Yu.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...be.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?wi({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,R,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:(R=g.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",be.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,w,b,C,D,F,L,B;const W=new k1(t,s),ae=new sN(s);t.setValue("connectedMeetingsSocketHandler",ae);const Tt=new cl(t,s),xs=new or(t,s),_n=new N1(s),Us=new SS(t,s),I=new V1(t,s),T=new C1(s),P=await jr.init(t,Us,d,o,n);t.setValue("selfController",P);const $=await Vf.init(t,P.self,Us,W,i);if(c.participant&&(L=new lr(t,P.self,Us)),(Je=c.e2ee)!=null&&Je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await as.init(t,xs,P.self,L.participants)),c.internals&&(C=await kh.init(t)),c.livestream&&n.viewType===tr.Livestream&&t.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(F=new tS(t,P.self,T)),c.poll&&(S=await Mf.init(t,P.self,Tt)),c.recording&&(D=new $f(t,P.self,Us)),c.stage&&(w=new Lf(t,_n,Us,P.self,L.participants)),c.plugin){if(!L)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Dr=await r;b=await vo.init(t,Dr,I,xs,y==null?void 0:y.chat,P.self,L.participants,i)}if(c.connectedMeetings&&(B=await Tl.init(t)),c.pip){const Dr=await Qu._init(t,P.self);t.setValue("pip",Dr)}const qe={storesManager:new ND(t,I),pollController:S,selfController:P,metaController:$,chatController:y,stageController:w,pluginController:b,recordingController:D,internalsController:C,livestreamController:F,participantController:L,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:qe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return gS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Oo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Do=Wn;yl([E.trace("Controller.init")],Do,"init",1),yl([E.trace("setupFlagsmith")],Do,"setupFlagsmith",1),yl([E.trace("Controller.createRoomNodeClient")],Do,"createRoomNodeClient",1),yl([E.trace("Controller.createSocketService")],Do,"createSocketService",1);class lN{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 FS=new lN;function uN(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=bi.baseURI.prod;t&&(n=t);const o=`https://${wi({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 hN{constructor(){m(this,gu);m(this,gi,new Audio);m(this,En,new MediaStream);m(this,wn,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,wn).has(e.id)||(a(this,En).addTrack(e),a(this,wn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,gi).setSinkId(t)}removeTrack(t){const e=a(this,wn).get(t);e&&(a(this,En).removeTrack(e),a(this,wn).delete(t))}async play(){return a(this,gi).srcObject=a(this,En),a(this,gi).play().catch(t=>{x(this,gu,jv).call(this,t)})}onError(t){f(this,xc,t)}}gi=new WeakMap,En=new WeakMap,wn=new WeakMap,xc=new WeakMap,gu=new WeakSet,jv=function(t){var e;(e=a(this,xc))==null||e.call(this,t)};class pN extends hN{constructor(){super();m(this,bn,void 0);f(this,bn,new Map)}addParticipantTrack(e,r){a(this,bn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,bn).get(e);r&&this.removeTrack(r),a(this,bn).delete(e)}}bn=new WeakMap;var gN=Object.defineProperty,mN=Object.getOwnPropertyDescriptor,El=(s,t,e,r)=>{for(var i=r>1?void 0:r?mN(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&&gN(t,e,i),i};let zr=(av=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=sr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new iS(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var g,S,y,w,b,C;be.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}=uN(r,i);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=zr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");Kv(l),FS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(w=(y=t.modules)==null?void 0:y.tracing)!=null?w:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(b=t.authToken)==null?void 0:b.slice(0,10)}...
|
|
21
|
-
${(C=t.authToken)==null?void 0:C.slice(-10)}`}});const u=await Do.init(c),h=new zr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=sr.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",Y_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",bs(e.cachedUserDetails)),n.setValue("sdkVersion","1.3.0
|
|
21
|
+
${(C=t.authToken)==null?void 0:C.slice(-10)}`}});const u=await Do.init(c),h=new zr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=sr.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",Y_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",bs(e.cachedUserDetails)),n.setValue("sdkVersion","1.3.0"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new pN),n}async join(){const{selfController:t}=a(this,Qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){FS.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,av);El([lt("0002"),cr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),El([lt("0003")],zr.prototype,"leave",1),El([lt("0001"),cr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=El([lt("0000")],zr);const $S=zr;return $S}();
|
package/dist/dependencies.txt
CHANGED
package/dist/index.cjs.js
CHANGED
|
@@ -10,4 +10,4 @@ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
|
|
|
10
10
|
maxEnergy: ${a(this,jr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,rr)||i<a(this,rr))&&T(this,rr,i),(!a(this,jr)||i>a(this,jr))&&T(this,jr,i),{energy:(i-a(this,rr))/(a(this,jr)-a(this,rr))*10||0,isVoice:r})},mc=new WeakSet,Ku=function(t){return t<5},dl=new WeakSet,lT=function(t=a(this,Bi)){var r;if(!a(this,vs)||!t){a(this,ir).getValue("flagsmith").hasFeature(te.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,vs)}`);return}const e={producerId:a(this,vs),energy:Math.round(t),silent:L(r=vo,mc,Ku).call(r,t)};T(this,Ca,e.silent),this.reportRequest(e)},ll=new WeakSet,uT=function(t){const e=Math.log10(t);return Math.round(e)},m(oo,mc),m(oo,ll);const xD=(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=()=>u(exports,null,function*(){try{const f=new Float32Array(n*o),v=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:f});c+=n/i*1e6,yield r.ready,yield r.write(v)}catch(f){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}});d=window.setInterval(l,100);const g=new MediaStream([e]).getAudioTracks()[0];return g.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(g,{fakeTracks:"fakeTracks:fakeAudioTrack"}),g.enabled=s,g}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}},UD=(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 $D=Object.defineProperty,FD=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?FD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$D(t,e,i),i};const kt=["video/VP9","video/VP8"];var fc,Tc,at,W,wa,ft,Hi,qi,ji,vc,ts,ar,Sc,Gi,Wi,Tt,_t,Gr,mn,ul,pT,hl,gT,pl,mT,yc,zu,gl,du,fT,ml,TT,fl,vT,Tl,ST,Xe,lt,Ji,co,vl,yT,Sl,ET,yl,PT;const hT=(du=class{constructor(s,t){m(this,Gr);m(this,ul);m(this,hl);m(this,pl);m(this,yc);m(this,ml);m(this,fl);m(this,Tl);m(this,Xe);m(this,Ji);m(this,vl);m(this,Sl);m(this,yl);h(this,"context");h(this,"authToken");h(this,"e2ee");m(this,fc,void 0);m(this,Tc,void 0);m(this,at,void 0);m(this,W,void 0);m(this,wa,void 0);m(this,ft,void 0);m(this,Hi,void 0);m(this,qi,void 0);m(this,ji,void 0);m(this,vc,void 0);m(this,ts,null);m(this,ar,void 0);m(this,Sc,void 0);m(this,Gi,void 0);m(this,Wi,void 0);m(this,Tt,void 0);m(this,_t,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,T(this,Gi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),T(this,Wi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),T(this,at,e),T(this,Hi,!1),T(this,W,new OD(s,e)),T(this,ft,a(this,W).events),T(this,ar,new Set),T(this,Tt,new Map),T(this,qi,!1),T(this,ji,new Fu(s.getValue("logger"))),T(this,_t,new oo(this.context,a(this,W).socketHandler.audioActivity.bind(a(this,W).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),T(this,vc,Eh(()=>u(this,null,function*(){if(!a(this,Gr,mn).mediaJoinAttempted)return;const{roomJoined:n}=yield this.joinRoom(a(this,Tc),a(this,fc),!0,!0);n&&(this.context.getValue("peerSessionStore").emit(R.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(R.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,Gr,mn).mediaJoined}set mediaJoined(s){a(this,Gr,mn).mediaJoined=s}reset(){a(this,W).closeAllProducers(),a(this,W).closeAllConsumers(),a(this,Tt).clear(),a(this,ar).clear(),T(this,ts,null),a(this,ji).stop(),a(this,W).stopAllTransports(),a(this,W).reset(),T(this,ji,new Fu)}joinRoom(n,o){return u(this,arguments,function*(s,t,e=!1,r=!1,i={}){a(this,Gr,mn).mediaJoinAttempted=!0,T(this,Hi,!0),e&&this.reset();try{return yield a(this,ji).push(()=>L(this,ul,pT).call(this,s,t,r,i),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1,error:c}}})}initializeConnection(i,n){return u(this,arguments,function*(s,t,e=!1,r={}){return a(this,ts)?a(this,ts):(T(this,ts,(()=>u(this,null,function*(){try{yield L(this,yc,zu).call(this,s,t,e,r)}catch(o){throw T(this,ts,null),o}}))()),a(this,ts))})}getConsumers(){return a(this,W).consumers}getProducers(){return a(this,W).producers}leaveRoom(){return u(this,null,function*(){a(this,W).stopAllTransports(),T(this,qi,!1),a(this,Gr,mn).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,at).sendMessagePromise(a(this,ft).leaveRoom,zw.toBinary(s)).then(e=>{var r;(r=xR.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()})}activatePeers(s){return u(this,null,function*(){return this.createConsumers(s)})}createConsumers(s){return u(this,null,function*(){return s.length===0?Promise.resolve():a(this,W).createConsumers(s)})}closeConsumers(s){return u(this,null,function*(){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,W).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);yield a(this,W).closeConsumers(t)})}_shareWebcam(s,t){return u(this,null,function*(){var g,f,v,E;const e=t==="video/VP9"?ue.WEBCAM:ue.WEBCAM_BACKUP,r=L(this,Xe,lt).call(this,e);if(r){const _=yield r;if(a(this,W).producers.has(_)){const C=a(this,W).producers.get(_);if(!C.closed)return yield C.replaceTrack({track:s}),yield this.resumeWebcam(e),s;yield this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(kt.filter(_=>_!==t)),n=L(this,yl,PT).call(this,s,i),o=Ia(this.context,"disableSimulcast"),c=(f=(g=this.context)==null?void 0:g.getValue("overrides"))==null?void 0:f.simulcastConfig;o||c&&c.disable||!((E=(v=this.context)==null?void 0:v.getValue("theme"))!=null&&E.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=w0(this.context,s)),this.context.getValue("flagsmith").hasFeature(te.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(te.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Tt).delete(e)},p=a(this,W).createProducer(n,l);return L(this,Ji,co).call(this,e,p.then(_=>_.id)),p.then(_=>_.track)})}shareWebcam(s){return u(this,null,function*(){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(te.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=kt.filter(i=>{var n,o;return((o=(n=a(this,wa).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,Wi).get(i).size>0});return e.length===0&&e.push(kt[0]),yield Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s})}shareScreen(s){return u(this,null,function*(){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:_e.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Tt).delete(ue.SCREENSHARE_VIDEO),a(this,Tt).delete(ue.SCREENSHARE_AUDIO)},n=a(this,W).createProducer(r,i);L(this,Ji,co).call(this,ue.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:_e.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,W).createProducer(c,d),L(this,Ji,co).call(this,ue.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(s){return u(this,null,function*(){try{if(s===void 0)throw new wt("track undefined");const t=L(this,Xe,lt).call(this,ue.MIC);if(t){const n=yield t;if(a(this,W).producers.has(n)){const o=a(this,W).producers.get(n);if(!o.closed){yield o.replaceTrack({track:s}),yield this.resumeMic(),a(this,_t)&&(a(this,_t).audioTrack=s,a(this,_t).producerId=n,a(this,_t).start());return}yield a(this,W).closeProducer(n,{stopTrack:!1})}yield this.shareMic(s);return}const e=L(this,Sl,ET).call(this,s),r=()=>{a(this,Tt).delete(ue.MIC)},i=a(this,W).createProducer(e,r);L(this,Ji,co).call(this,ue.MIC,i.then(n=>n.id)),yield i.then(n=>{a(this,_t)&&(a(this,_t).audioTrack=n.track,a(this,_t).producerId=n.id,a(this,_t).start())})}catch(t){throw new k(t)}})}pauseMic(){return u(this,null,function*(){var r;const s=yield L(this,Xe,lt).call(this,ue.MIC),t=a(this,W).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,_t))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,at).sendMessage(a(this,ft).toggleProducer,Gc.toBinary(e))})}pauseWebcam(){return u(this,null,function*(){const s=yield L(this,Xe,lt).call(this,ue.WEBCAM),t=yield L(this,Xe,lt).call(this,ue.WEBCAM_BACKUP),e=a(this,W).producers.get(s),r=a(this,W).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,at).sendMessage(a(this,ft).toggleProducer,Gc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))})}resumeMic(){return u(this,null,function*(){const s=yield L(this,Xe,lt).call(this,ue.MIC),t=a(this,W).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(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,at).sendMessage(a(this,ft).toggleProducer,Gc.toBinary(e))})}resumeWebcam(){return u(this,arguments,function*(s=ue.WEBCAM){const t=yield L(this,Xe,lt).call(this,s),e=a(this,W).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(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,at).sendMessage(a(this,ft).toggleProducer,Gc.toBinary(r))})}disableWebcam(s){return u(this,null,function*(){const t=s==="video/VP9"?ue.WEBCAM:ue.WEBCAM_BACKUP,e=yield L(this,Xe,lt).call(this,t);L(this,vl,yT).call(this,t),e&&(yield a(this,W).closeProducer(e))})}disableMic(){return u(this,null,function*(){var t;const s=yield L(this,Xe,lt).call(this,ue.MIC);s&&(yield a(this,W).closeProducer(s)),(t=a(this,_t))==null||t.stop(),a(this,Tt).delete(ue.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=yield L(this,Xe,lt).call(this,ue.SCREENSHARE_VIDEO),t=yield L(this,Xe,lt).call(this,ue.SCREENSHARE_AUDIO);s&&(yield a(this,W).closeProducer(s)),t&&(yield a(this,W).closeProducer(t)),a(this,ar).clear(),a(this,Tt).delete(ue.SCREENSHARE_VIDEO),a(this,Tt).delete(ue.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}resetVideoProducers(s,t){return u(this,null,function*(){if(s){const e=yield L(this,Xe,lt).call(this,ue.WEBCAM),r=yield L(this,Xe,lt).call(this,ue.WEBCAM_BACKUP);yield a(this,W).closeProducer(e,{stopTrack:!1}),yield a(this,W).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=yield L(this,Xe,lt).call(this,ue.SCREENSHARE_VIDEO);yield a(this,W).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}})}changeDisplayName(s,t){return u(this,null,function*(){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!(yield a(this,W).socketHandler.changeDisplayName(e)))throw new Error("failed to change display name!")})}kick(s){const t={peerIds:[s]};a(this,W).socketHandler.kickPeer(t)}kickAll(){a(this,W).socketHandler.kickAll()}muteAll(s){return u(this,null,function*(){if(!(yield a(this,W).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,W).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(s){return u(this,null,function*(){if(!(yield a(this,W).socketHandler.hostControlForPeer(s,"audio")))throw new Error("failed to mute given participant")})}disableVideo(s){return u(this,null,function*(){if(!(yield a(this,W).socketHandler.hostControlForPeer(s,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(s){return u(this,null,function*(){const t={participantId:s!=null?s:""};try{yield a(this,at).sendMessagePromise(a(this,ft).globalPinPeer,dR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}})}validateScreenShare(s){return this.peerId===s.peerId&&a(this,W).producers.get(s.producerId)&&a(this,ar).add(s.consumerPeerId),a(this,ar).size}switchConsumersToLayer(s,t){return u(this,null,function*(){const e=s.map(r=>this.getConsumers().get(r));a(this,W).switchConsumersToLayer(e,t)})}handleSocketEvents(){return u(this,null,function*(){a(this,at).on(a(this,ft).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=pb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ls.AUDIO?"audio/opus":"video/VP8"),i.kind===Ls.VIDEO&&!i.screenShare&&((e=(t=a(this,wa).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===kt[0]))>=0&&a(this,Gi).get(kt[0]).has(r)&&i.mimeType!==kt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:G(O({},i),{kind:i.kind===Ls.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,at).on(a(this,ft).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=$p.fromBinary(s);if(o)return;const c=r===Ls.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify($p.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.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(R.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,at).on(a(this,ft).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=Eu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,ar).delete(t),a(this,W).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,at).on(a(this,ft).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=fb.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,W).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,W).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,W).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(R.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,at).on(a(this,ft).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Hi)&&!a(this,qi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,vc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,W).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(R.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,W).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(R.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<=kt.length;o+=1){const c=kt[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===kt.length-1){a(this,Wi).get(c).add(s);break}}for(let o=0;o<=kt.length;o+=1){const c=kt[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===kt.length-1){a(this,Gi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(te.FORCE_VIDEO_CODEC)||(a(this,Gi).forEach(t=>t.delete(s)),a(this,Wi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===kt[0])&&this.disableWebcam(e)}))}},fc=new WeakMap,Tc=new WeakMap,at=new WeakMap,W=new WeakMap,wa=new WeakMap,ft=new WeakMap,Hi=new WeakMap,qi=new WeakMap,ji=new WeakMap,vc=new WeakMap,ts=new WeakMap,ar=new WeakMap,Sc=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Tt=new WeakMap,_t=new WeakMap,Gr=new WeakSet,mn=function(){return this.context.getValue("connectionHandler")},ul=new WeakSet,pT=function(s,t,e,r){return u(this,null,function*(){T(this,Tc,s);try{return a(this,ts)?yield a(this,ts):yield L(this,yc,zu).call(this,s,t,e,r),L(this,pl,mT).call(this,t),{roomJoined:yield L(this,hl,gT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1,error:i}}finally{T(this,ts,null)}})},hl=new WeakSet,gT=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:s}=yield a(this,W).socketHandler.notifySelfJoinComplete();return T(this,fc,s.roomUuid),T(this,qi,!0),T(this,Hi,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}})},pl=new WeakSet,mT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:G(O({},_e.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)},yc=new WeakSet,zu=function(s,t,e,r){return u(this,null,function*(){var i,n;try{(n=a(this,Sc))!=null||T(this,Sc,L(i=hT,gl,fT).call(i));const o=L(this,ml,TT).call(this);yield L(this,fl,vT).call(this,s,t,e,o),yield a(this,W).setupTransports({send:!0,recv:!0}),yield L(this,Tl,ST).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},gl=new WeakSet,fT=function(){const{ipInfo:s}=ot();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},ml=new WeakSet,TT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(te.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=ED(s);return T(this,wa,t),t},fl=new WeakSet,vT=function(s,t,e,r){return u(this,null,function*(){yield Gf((i,n)=>u(this,null,function*(){if(!a(this,at).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{yield a(this,W).socketHandler.joinRoom(t,s,r,e,a(this,Sc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:15})})},Tl=new WeakSet,ST=function(s){return u(this,null,function*(){if(!(!this.context.getValue("flagsmith").hasFeature(te.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===q.Allowed&&e.push(this.shareWebcam(UD(!1))),s.canProduceAudio===q.Allowed){const r=xD(!1);r&&e.push(this.shareMic(r))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},Xe=new WeakSet,lt=function(s){return a(this,Tt).get(s)},Ji=new WeakSet,co=function(s,t){return a(this,Tt).set(s,t)},vl=new WeakSet,yT=function(s){return a(this,Tt).delete(s)},Sl=new WeakSet,ET=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},yl=new WeakSet,PT=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(du,gl),du);let ae=hT;de([P.trace("MediaNodeClient.reset",{country:P.location.country})],ae.prototype,"reset",1);de([P.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1);de([P.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1);de([P.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1);de([P.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1);de([P.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1);de([P.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1);de([P.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1);de([P.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1);de([P.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1);de([P.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1);de([P.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1);de([P.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1);de([P.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1);de([P.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1);de([P.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1);de([P.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1);de([P.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1);de([P.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1);de([P.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1);de([P.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1);de([P.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1);de([P.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1);de([P.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1);de([P.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1);de([P.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1);de([P.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1);de([P.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function _T(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 ae(s,t);return s.setValue("roomNodeClient",r),r}function CT(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 BD=Object.defineProperty,HD=Object.getOwnPropertyDescriptor,ln=(s,t,e,r)=>{for(var i=r>1?void 0:r?HD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BD(t,e,i),i},Ki,Ss,Z,vt,It,Ng;const wT=(Ng=class{constructor(s,t,e,r){m(this,vt);h(this,"self");h(this,"authToken");m(this,Ki,void 0);h(this,"viewType");m(this,Ss,void 0);m(this,Z,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,T(this,Z,s),this.viewType=r,this.authToken=n,T(this,Ki,i),T(this,Ss,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 init(s,t,e,r,i){return u(this,null,function*(){const n=ot(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=yield ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const p=!s.getValue("flagsmith").hasFeature(te.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const g=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(g)}),s.getValue("callstats").devices("AUDIO",g==null?void 0:g.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",g==null?void 0:g.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",g==null?void 0:g.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield s.getValue("callstats").initialize({peerId:o,engineName:_e.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:yield n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:ef(s),skipConnectivityChecks:p}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new wT(s,d,t,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===q.Allowed&&r)try{yield a(this,vt,It).shareMic(s),this.self.audioEnabled||a(this,vt,It).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===q.Allowed&&i)try{const d=yield a(this,vt,It).shareWebcam(t);d&&d.id!==t.id&&a(this,Z).getValue("flagsmith").hasFeature(te.EXP_RESHARE)&&(yield a(this,vt,It).shareWebcam(d)),this.self.videoEnabled||a(this,vt,It).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===q.Allowed&&n)try{yield(c=a(this,vt,It))==null?void 0:c.shareScreen({video:o.video,audio:o.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(s){return u(this,null,function*(){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")}resetSelf(s){return u(this,null,function*(){a(this,Z).getValue("callstats").callEnded(),a(this,vt,It).reset(),s&&(yield this.joinRoom(s))})}setupEvents(){a(this,Z).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,Z).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Z).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Z).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Z).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Z).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,Z).getValue("flagsmith").hasFeature(te.REFRESH_ID_ON_DISCONNECTION)&&(t=pr.v4()),a(this,Ki).updateURL(t),a(this,Z).getValue("telemetry").resetPeerId(t),ot().setHeader("tracing-id",t),lr.remapContext(t,a(this,Z)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Z).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ss).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ss).on(sd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Z).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),a(this,Ss).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ss).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ss).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Z).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(R.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(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,Z).getValue("callstats").audioOff())})),a(this,Z).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,Z).getValue("callstats").videoOff())})),a(this,Z).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(s=!1){return u(this,null,function*(){try{const{peer:t}=yield a(this,Ss).joinRoom(this.self);a(this,Ss).socket.flush();const e=wh(t.stageType);if(a(this,Z).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(s),a(this,Z).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}})}leaveRoom(s="left"){return u(this,null,function*(){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),yield this.leaveMediaRoom(s),a(this,Z).notify("stageStatus");try{(e=a(this,Ki))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}CT(a(this,Z)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)})}joinMediaRoom(s=!1){return u(this,null,function*(){var n,o,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,Z).getAllValues();try{if(e===hr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}_T(a(this,Z),{socket:a(this,Ki),peerId:t})}const{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:p}=this.self.permissions,{roomJoined:g,error:f}=(o=yield(n=a(this,vt,It))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:p}))!=null?o:{};if(!g)throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:f}),f;i==="ON_STAGE"&&(yield 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")}})}leaveMediaRoom(s){return u(this,null,function*(){const t=a(this,Z).getValue("viewType");s!=="connected-meeting"&&(yield this.cleanupSelf()),!(s==="stageLeft"&&t===hr.Webinar)&&a(this,vt,It)&&(a(this,vt,It).mediaJoined&&s!=="disconnected"&&(yield a(this,vt,It).leaveRoom()),!(s==="stageLeft"&&t===hr.Livestream)&&(a(this,vt,It).mediaJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},Ki=new WeakMap,Ss=new WeakMap,Z=new WeakMap,vt=new WeakSet,It=function(){return a(this,Z).getValue("roomNodeClient")},Ng);let si=wT;ln([P.trace("SelfController.resetSelf")],si.prototype,"resetSelf",1);ln([P.trace("SelfController.setupEvents")],si.prototype,"setupEvents",1);ln([P.trace("SelfController.joinRoom")],si.prototype,"joinRoom",1);ln([P.trace("SelfController.leaveRoom")],si.prototype,"leaveRoom",1);ln([P.trace("SelfController.joinMediaRoom")],si.prototype,"joinMediaRoom",1);ln([P.trace("SelfController.leaveMediaRoom")],si.prototype,"leaveMediaRoom",1);ln([P.trace("SelfController.init")],si,"init",1);var Ec;class qD{constructor(t){m(this,Ec,void 0);T(this,Ec,t)}on(t,e){let r;t===U.roomPeerCount?r=Hp.fromBinary.bind(Hp):r=Zp.fromBinary.bind(Zp),a(this,Ec).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Ec=new WeakMap;var Pc,_c;class jD{constructor(t,e){m(this,Pc,void 0);m(this,_c,void 0);T(this,Pc,e),T(this,_c,t)}get logger(){return a(this,_c).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=Zl.fromBinary.bind(Zl),i=Zl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Pc).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)})}}Pc=new WeakMap,_c=new WeakMap;var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,xh=(s,t,e,r)=>{for(var i=r>1?void 0:r?WD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GD(t,e,i),i},or,Ra;class Fl{constructor(t,e){m(this,or,void 0);m(this,Ra,void 0);T(this,or,e),T(this,Ra,t)}get logger(){return a(this,Ra).getValue("logger")}get telemetry(){return a(this,Ra).getValue("telemetry")}getPolls(){return a(this,or).sendMessagePromise(Bs.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,or).sendMessage(Bs.createPoll,ZI.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,or).sendMessage(Bs.votePoll,tM.toBinary(r))}on(t,e){let r,i;switch(t){case Bs.updatePoll:case Bs.createPoll:case Bs.votePoll:{r=nu.fromBinary.bind(nu),i=nu.create();break}}a(this,or).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,or).removeListeners(t)}}or=new WeakMap,Ra=new WeakMap;xh([P.trace("PollSocketHandler.getPolls")],Fl.prototype,"getPolls",1);xh([P.trace("PollSocketHandler.createPoll")],Fl.prototype,"createPoll",1);xh([P.trace("PollSocketHandler.votePoll")],Fl.prototype,"votePoll",1);var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,zD=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&JD(t,e,i),i},xt;class RT{constructor(t,e){h(this,"socket");m(this,xt,void 0);T(this,xt,t),this.socket=e,this.handleSocketEvents(),a(this,xt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,xt).getValue("telemetry")}get logger(){return a(this,xt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}joinRoom(t){return u(this,null,function*(){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,Gb.toBinary(e));try{const{peer:n}=hn.fromBinary((yield r).payload);a(this,xt).getValue("connectionHandler").socketJoined=!0,a(this,xt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,xt).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,xt).getValue("peerSessionStore").emit(R.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)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return Ak.fromBinary((yield this.socket.sendMessagePromise(U.getAllAddedParticipants)).payload).participants.map(i=>{var n=i,{id:e}=n,r=Bc(n,["id"]);return G(O({},r),{userId:e})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let i;try{const n={seachQuery:t,limit:e,offset:r},o=yield this.socket.sendMessagePromise(U.getRoomPeersInfo,Vb.toBinary(n));i=eu.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(U.getRoomPeersInfo);t=eu.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(U.getRoomPeersInfo);t=eu.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(U.getPeerInfo,uf.toBinary({peerId:t}));e=hn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=qp.create();try{const e=yield this.socket.sendMessagePromise(U.getRoomInfo);t=qp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=Jp.create();try{const e=yield this.socket.sendMessagePromise(U.getRoomStageState);t=Jp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(U.broadcastMessage,Za.toBinary(r))})}broadcastToMeetings(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(U.broadcastToEntity,Za.toBinary(i))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(U.broadcastToEntity,Za.toBinary(i))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,Jb.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(U.kick,pf.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,cf.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,Vk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,xk.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(sd.updateUserPreset,hA.toBinary(r))})}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Za.fromBinary(t);a(this,xt).getValue("peerSessionStore").emit(R.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=Za.fromBinary(t);a(this,xt).getValue("peerSessionStore").emit(R.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=hn.fromBinary.bind(hn),i=hn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?Wp.fromBinary(n,o):{requests:[]},i=Wp.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=sg.fromBinary.bind(sg);break}case sd.updateUserPreset:{r=Kp.fromBinary.bind(Kp);break}case Ps.peerJoinedBroadcast:case kr.peerJoinedBroadcast:{r=xp.fromBinary.bind(xp);break}case Ps.selfJoinComplete:case kr.selfJoinComplete:{r=yu.fromBinary.bind(yu);break}case Ps.globalPeerPinBroadcast:case kr.globalPeerPinBroadcast:{r=Fp.fromBinary.bind(Fp);break}case Ps.selectedPeer:case kr.selectedPeer:{r=Su.fromBinary.bind(Su);break}case Ps.selectedPeerDiff:case kr.selectedPeerDiff:{r=Lp.fromBinary.bind(Lp);break}case Ps.leaveRoom:case kr.leaveRoom:{r=Eu.fromBinary.bind(Eu);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)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(sd.getUserPresets,nA.toBinary(e)),i=dA.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}})}}xt=new WeakMap;zD([P.trace("RoomSocketHandler.joinRoom")],RT.prototype,"joinRoom",1);var Ct;class YD{constructor(t){m(this,Ct,void 0);T(this,Ct,t)}getStageRequests(){return u(this,null,function*(){const{payload:t}=yield a(this,Ct).sendMessagePromise(U.getStageRequests);return t?iu.fromBinary(t):{stageRequests:[]}})}requestAccess(){a(this,Ct).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Ct).sendMessage(U.cancelStageRequest)}grantAccess(t){return u(this,null,function*(){const e={userIds:t};a(this,Ct).sendMessage(U.grantStageAccess,qI.toBinary(e))})}denyAccess(t){return u(this,null,function*(){const e={userIds:t};a(this,Ct).sendMessage(U.denyStageAccess,GI.toBinary(e))})}joinStage(){return a(this,Ct).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Ct).sendMessagePromise(U.leaveStage,tg.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Ct).sendMessagePromise(U.leaveStage,tg.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=eg.fromBinary.bind(eg);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=iu.fromBinary.bind(iu);break}case U.peerStageStatusUpdate:{r=Bp.fromBinary.bind(Bp);break}}a(this,Ct).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}getPeerInfo(t){return u(this,null,function*(){const e=yield a(this,Ct).sendMessagePromise(U.getPeerInfo,uf.toBinary({peerId:t}));return hn.fromBinary(e.payload)})}}Ct=new WeakMap;var qe,Cc;class QD{constructor(t,e){m(this,qe,void 0);m(this,Cc,void 0);T(this,qe,e),T(this,Cc,t)}get logger(){return a(this,Cc).getValue("logger")}addPlugin(t,e){a(this,qe).sendMessage(J.addPlugin,aI.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,qe).sendMessage(J.removePlugin,cI.toBinary({pluginId:t,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:t}=yield a(this,qe).sendMessagePromise(J.getPlugins);return t?MI.fromBinary(t):{plugins:[]}})}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,qe).sendMessage(J.customPluginEventToRoom,vI.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,qe).sendMessage(J.customPluginEventToPeers,yI.toBinary(n),i)}enablePluginForRoom(t,e){a(this,qe).sendMessage(J.enablePluginForRoom,lI.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,qe).sendMessage(J.enablePluginForPeers,gI.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,qe).sendMessage(J.disablePluginForRoom,hI.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,qe).sendMessage(J.disablePluginForPeers,fI.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,qe).sendMessage(J.storeInsertKeys,zp.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,qe).sendMessage(J.storeGetKeys,CI.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,qe).sendMessage(J.storeDeleteKeys,RI.toBinary(n),i)}storeDelete(t,e,r){a(this,qe).sendMessage(J.storeDelete,kI.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,qe).sendMessage(J.storeInsertKeys,zp.toBinary(i))}on(t,e){let r;switch(t){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{r=wu.fromBinary.bind(wu);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{r=Yp.fromBinary.bind(Yp);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{r=Xp.fromBinary.bind(Xp);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{r=Qp.fromBinary.bind(Qp);break}}a(this,qe).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}qe=new WeakMap,Cc=new WeakMap;var XD=Object.defineProperty,ZD=(s,t,e)=>t in s?XD(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,eO=(s,t,e)=>(ZD(s,typeof t!="symbol"?t+"":t,e),e),Uh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},D=(s,t,e)=>(Uh(s,t,"read from private field"),e?e.call(s):t.get(s)),fe=(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)},ne=(s,t,e,r)=>(Uh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(Uh(s,t,"access private method"),e),Cd={},tO={get exports(){return Cd},set exports(s){Cd=s}},Rn=typeof Reflect=="object"?Reflect:null,hg=Rn&&typeof Rn.apply=="function"?Rn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},dd;Rn&&typeof Rn.ownKeys=="function"?dd=Rn.ownKeys:Object.getOwnPropertySymbols?dd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:dd=function(s){return Object.getOwnPropertyNames(s)};function sO(s){console&&console.warn&&console.warn(s)}var bT=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}tO.exports=ce;Cd.once=aO;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var pg=10;function Bl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return pg},set:function(s){if(typeof s!="number"||s<0||bT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");pg=s}});ce.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};ce.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||bT(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 kT(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return kT(this)};ce.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")hg(c,this,t);else for(var d=c.length,l=OT(c,d),e=0;e<d;++e)hg(l[e],this,t);return!0};function AT(s,t,e,r){var i,n,o;if(Bl(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=kT(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,sO(c)}return s}ce.prototype.addListener=function(s,t){return AT(this,s,t,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(s,t){return AT(this,s,t,!0)};function rO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function IT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=rO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return Bl(t),this.on(s,IT(this,s,t)),this};ce.prototype.prependOnceListener=function(s,t){return Bl(t),this.prependListener(s,IT(this,s,t)),this};ce.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Bl(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():iO(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ce.prototype.off=ce.prototype.removeListener;ce.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 MT(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?nO(i):OT(i,i.length)}ce.prototype.listeners=function(s){return MT(this,s,!0)};ce.prototype.rawListeners=function(s){return MT(this,s,!1)};ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):DT.call(s,t)};ce.prototype.listenerCount=DT;function DT(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}ce.prototype.eventNames=function(){return this._eventsCount>0?dd(this._events):[]};function OT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function iO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function nO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function aO(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))}NT(s,t,n,{once:!0}),t!=="error"&&oO(s,i,{once:!0})})}function oO(s,t,e){typeof s.on=="function"&&NT(s,"error",t,e)}function NT(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 cO extends S.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const gg=new cO;class VT{static encode(t){return gg.toBinary(t)}static decode(t){return gg.fromBinary(new Uint8Array(t))}}function dO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Rr;class lO{constructor(t={}){eO(this,"opts"),fe(this,Rr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,Rr,0)}wait(){return u(this,null,function*(){ne(this,Rr,D(this,Rr)+1);const t=dO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Gh(2,D(this,Rr))));yield new Promise(e=>{setTimeout(e,t)})})}getAttempts(){return D(this,Rr)}reset(){ne(this,Rr,0)}}Rr=new WeakMap;const Pr={debug:0,info:1,warn:2,error:3};var oi,ci;class uO{constructor(t){fe(this,oi,void 0),fe(this,ci,void 0),ne(this,oi,console),ne(this,ci,t)}debug(...t){Pr[D(this,ci)]>Pr.debug||D(this,oi).debug("[Sockrates]:",...t)}info(...t){Pr[D(this,ci)]>Pr.info||D(this,oi).info("[Sockrates]:",...t)}warn(...t){Pr[D(this,ci)]>Pr.warn||D(this,oi).warn("[Sockrates]:",...t)}error(...t){Pr[D(this,ci)]>Pr.error||D(this,oi).error("[Sockrates]:",...t)}}oi=new WeakMap,ci=new WeakMap;var LT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(LT||{});const hO="2",pO="3";var Ae,fn,Ee,Le,br,Ke,dr,zr,Es,Tn,Fs,Yu,xT,lo,ld,Qu,UT,Xu,mg,wd,Zu,eh,$T,go,ud,mo,Rd,bd,th,bn,fo,To,kd;class gO{constructor(t,e){var f,v,E,_,C,I,M,$,x,B;fe(this,Yu),fe(this,lo),fe(this,Qu),fe(this,Xu),fe(this,wd),fe(this,eh),fe(this,go),fe(this,mo),fe(this,bd),fe(this,bn),fe(this,To),fe(this,Ae,void 0),fe(this,fn,void 0),fe(this,Ee,void 0),fe(this,Le,void 0),fe(this,br,void 0),fe(this,Ke,void 0),fe(this,dr,void 0),fe(this,zr,void 0),fe(this,Es,void 0),fe(this,Tn,void 0),fe(this,Fs,void 0);var r,i,n,o,c,d,l,p,g;ne(this,fn,t),ne(this,br,[]),ne(this,Ke,new Cd),ne(this,dr,!0),ne(this,Es,!1),ne(this,Ee,e!=null?e:{}),(f=(r=D(this,Ee)).autoReconnect)!=null||(r.autoReconnect=!0),(v=(i=D(this,Ee)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=D(this,Ee)).pingTimeout)!=null||(n.pingTimeout=3e4),(_=(o=D(this,Ee)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(C=(c=D(this,Ee)).debug)!=null||(c.debug=!0),(I=(d=D(this,Ee)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(M=(l=D(this,Ee)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),($=(p=D(this,Ee)).queueOnDisconnect)!=null||(p.queueOnDisconnect=!1),(x=(g=D(this,Ee)).flushOnReconnect)!=null||(g.flushOnReconnect=!1),ne(this,zr,{code:void 0,reason:void 0}),ne(this,Le,(B=D(this,Ee).logger)!=null?B:new uO(D(this,Ee).debug?"debug":"info")),ne(this,Fs,new lO)}get readyState(){var t;return(t=D(this,Ae))==null?void 0:t.readyState}get url(){return D(this,fn)}updateURL(t){ne(this,fn,t),Pe(this,eh,$T).call(this)}get config(){return D(this,Ee)}get sendQueue(){return D(this,br)}flush(){if(!D(this,Ee).queueOnDisconnect)return!1;const t=[];return D(this,br).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,br,t),D(this,br)}connect(t=!1){return u(this,null,function*(){if(!t&&[0,1].includes(this.readyState)){D(this,Le).debug("Websocket was already connecting or connected.");return}if(D(this,dr)!==!1)return new Promise((e,r)=>{Pe(this,bn,fo).call(this),Pe(this,To,kd).call(this);try{ne(this,Ae,new WebSocket(Pe(this,Yu,xT).call(this,D(this,fn)))),D(this,Ae).binaryType="arraybuffer",D(this,Le).debug("Connecting");const i=setTimeout(()=>{D(this,Le).debug("Connection timeout. Closing socket"),ne(this,dr,!0),Pe(this,To,kd).call(this),D(this,Ae).close(3001,"Connection Timeout"),D(this,Ee).autoReconnect&&!D(this,Es)&&(D(this,Ke).emit("reconnecting"),Pe(this,go,ud).call(this)),r(new Error("Connection timed out!"))},D(this,Ee).connectionTimeout);D(this,Ae).onopen=()=>{D(this,Le).debug(`Ready State: ${LT[D(this,Ae).readyState]}`),i&&clearTimeout(i),Pe(this,bd,th).call(this),ne(this,zr,{code:void 0,reason:void 0}),D(this,Ke).emit("connected"),D(this,Ee).flushOnReconnect&&this.flush(),e()},D(this,Ae).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),D(this,Le).debug("Socket closed. Close event:",{event:n}),D(this,Le).debug(`Connection closed code: ${o}`),D(this,Le).debug(`Connection closed reason: ${c}`),D(this,Es)||Pe(this,wd,Zu).call(this,o,c)}catch(o){Pe(this,lo,ld).call(this,o)}},D(this,Ae).onerror=n=>{Pe(this,lo,ld).call(this,n)},D(this,Ae).onmessage=n=>Pe(this,Qu,UT).call(this,n)}catch(i){Pe(this,lo,ld).call(this,i,r)}})})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(D(this,Ee).queueOnDisconnect&&(!D(this,Ae)||D(this,Ae).readyState!==1))return D(this,Le).debug("Queuing message since socket is not connected!",n),D(this,br).push(n),!1;const o=VT.encode(n);return Pe(this,mo,Rd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,mo,Rd).call(this,t)}receive(t,e){return D(this,Ke).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")){D(this,Ke).on(t,e);return}this.receive(t,e)}removeAllListeners(){D(this,Ke).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){D(this,Ke).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){D(this,Ke).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,dr,!1),Pe(this,bn,fo).call(this),this.removeAllListeners(),ne(this,zr,{code:1e3,reason:"Sockrates disconnect method called"}),D(this,Ae).close(1e3,"Sockrates disconnect method called.")}}Ae=new WeakMap,fn=new WeakMap,Ee=new WeakMap,Le=new WeakMap,br=new WeakMap,Ke=new WeakMap,dr=new WeakMap,zr=new WeakMap,Es=new WeakMap,Tn=new WeakMap,Fs=new WeakMap,Yu=new WeakSet,xT=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)://.")},lo=new WeakSet,ld=function(s,t){D(this,Le).error("Error:",{error:s}),D(this,Ke).emit("errored",{error:s}),t==null||t(s)},Qu=new WeakSet,UT=function(s){if(Pe(this,bd,th).call(this),s.data===hO){D(this,Le).debug("Received ping from server"),Pe(this,mo,Rd).call(this,pO);return}const t=VT.decode(s.data),{id:e,payload:r}=t;D(this,Le).debug("Received message",{event:t.event,messageID:e}),D(this,Ke).emit(t.event.toString(),{id:e,payload:r})},Xu=new WeakSet,mg=function(){return D(this,Ae).readyState===1},wd=new WeakSet,Zu=function(s,t){ne(this,zr,{reason:t,code:s}),D(this,Ke).emit("disconnected",{code:s,reason:t})},eh=new WeakSet,$T=function(){const{reason:s,code:t}=D(this,zr);t&&t!==1e3&&D(this,dr)&&D(this,Ee).autoReconnect&&!D(this,Es)&&(D(this,Le).debug(`Triggering reconnection due to ${s}.`),D(this,Ke).emit("reconnecting"),Pe(this,go,ud).call(this))},go=new WeakSet,ud=function(s=!0){return u(this,null,function*(){if(s&&D(this,Es)){D(this,Le).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(D(this,Es)||D(this,Fs).reset(),D(this,Ee).maxReconnectionAttempts!==null&&D(this,Fs).getAttempts()>=D(this,Ee).maxReconnectionAttempts){D(this,Ke).emit("failed"),ne(this,Es,!1);return}ne(this,Es,!0),Pe(this,To,kd).call(this),Pe(this,bn,fo).call(this);try{if(yield D(this,Fs).wait(),D(this,dr)===!1)return;if(D(this,Le).debug(`Reconnection attempt ${D(this,Fs).getAttempts()}`),D(this,Ke).emit("reconnectAttempt",{attempt:D(this,Fs).getAttempts()}),yield this.connect(),!Pe(this,Xu,mg).call(this))throw Error("Reconnect Failed");ne(this,Es,!1),ne(this,zr,{code:void 0,reason:void 0}),D(this,Ke).emit("reconnected")}catch(t){D(this,Le).debug("Failed to reconnect."),D(this,Ke).emit("reconnectFailure",{attempt:D(this,Fs).getAttempts()}),Pe(this,go,ud).call(this,!1)}})},mo=new WeakSet,Rd=function(s){try{return D(this,Ae).send(s),!0}catch(t){return D(this,Le).error(t.message),!1}},bd=new WeakSet,th=function(){this.config.disconnectOnPingTimeout&&(D(this,Le).debug("Resetting ping timeout"),Pe(this,bn,fo).call(this),ne(this,Tn,setTimeout(()=>{var s;D(this,Le).debug("Disconnecting the socket due to ping timeout"),ne(this,dr,!0);const t=3002,e="Ping timeout";(s=D(this,Ae))==null||s.close(t,e),Pe(this,wd,Zu).call(this,t,e)},D(this,Ee).pingTimeout)))},bn=new WeakSet,fo=function(){D(this,Tn)&&(clearTimeout(D(this,Tn)),ne(this,Tn,void 0))},To=new WeakSet,kd=function(){D(this,Ae)&&(D(this,Ae).onopen=void 0,D(this,Ae).onerror=void 0,D(this,Ae).onmessage=void 0,D(this,Ae).onclose=void 0)};var mO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,Hl=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(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&&mO(t,e,i),i};const fg=65535,TO=3e3;var Wr,Ce,we,Me,ss,Ze,wc,sh,Rc,rh,Vg;const FT=(Vg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,we);m(this,wc);m(this,Rc);m(this,Wr,void 0);m(this,Ce,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");m(this,ss,void 0);m(this,Ze,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");T(this,ss,void 0),T(this,Ze,s),this.capabilities=i,this.roomName=e,this.authToken=r,T(this,Wr,L(this,wc,sh).call(this,t)),T(this,Ce,new gO(a(this,Wr),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,we,Me).socketJoinAttempted}set joinAttempted(s){a(this,we,Me).socketJoinAttempted=s}get telemetry(){return a(this,Ze).getValue("telemetry")}get logger(){return a(this,Ze).getValue("logger")}get peerId(){return a(this,Ze).getValue("peerId")}updateURL(s){s!==this.peerId&&(T(this,Wr,L(this,wc,sh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ce).updateURL(a(this,Wr))}static getSocketEdgeDomain(s){return Zi({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,Wr)}connect(){return u(this,null,function*(){a(this,we,Me).socketJoinAttempted=!0,yield a(this,Ce).connect(),a(this,we,Me).socketJoinAttempted=!0,a(this,we,Me).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){a(this,we,Me).socketJoinAttempted=!1,a(this,Ce).disconnect(),a(this,we,Me).socketJoinAttempted=!0,a(this,we,Me).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,Ze).getValue("telemetry").injectContext(r),a(this,Ce).send(s,e!=null?e:L(this,Rc,rh).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(E,_)=>{a(this,Ce).removeListener(n,E),a(this,Ce).removeListener(fg,_),a(this,Ce).removeListener(kr.errorResponse,_),a(this,Ce).removeListener(Ps.errorResponse,_)},l=r!=null?r:L(this,Rc,rh).call(this),p={};a(this,Ze).getValue("telemetry").injectContext(p);const f=({id:E,payload:_})=>{if(l===E){let C;try{const I=bR.fromBinary(_);C=new Error(I.errorMessage)}catch(I){C=new Error("failed to parse error message",{cause:I});try{const M=kb.fromBinary(_);C=new Error(M.message)}catch(M){C=new Error("failed to parse error message",{cause:M})}}c(C),d(v,f)}},v=({id:E,payload:_})=>{l===E&&(o({id:E,payload:_}),d(v,f))};a(this,Ce).on(n,v),a(this,Ce).on(fg,f),a(this,Ce).on(kr.errorResponse,f),a(this,Ce).on(Ps.errorResponse,f),setTimeout(()=>{d(v,f),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(p)))})}on(s,t){a(this,Ce).on(s,t)}onStateEvent(s,t){a(this,Ce).on(s,t)}removeListener(s,t){a(this,Ce).removeListener(s,t)}removeListeners(s){a(this,Ce).removeListeners(s)}flush(){return a(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,ss)&&(clearTimeout(a(this,ss)),T(this,ss,void 0)),a(this,we,Me).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:P.location.country});const{recv:e,send:r}=(i=a(this,we,Me).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==wn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==wn.CONNECTED?a(this,Ze).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,we,Me).joinAttempted}):T(this,ss,setTimeout(()=>{a(this,Ze).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,we,Me).joinAttempted}),T(this,ss,void 0)},TO)),a(this,we,Me).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:P.location.country}),a(this,we,Me).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:s}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,we,Me).updateSocketConnectionState("reconnectAttempt",s)})),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,we,Me).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,we,Me).mediaJoinAttempted}}),a(this,ss)&&(clearTimeout(a(this,ss)),T(this,ss,void 0)),a(this,Ze).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,we,Me).mediaJoinAttempted}),a(this,we,Me).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:P.location.country}),a(this,Ze).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,we,Me).updateSocketConnectionState("failed")}))}},Wr=new WeakMap,Ce=new WeakMap,we=new WeakSet,Me=function(){return a(this,Ze).getValue("connectionHandler")},ss=new WeakMap,Ze=new WeakMap,wc=new WeakSet,sh=function(s){let t=FT.getSocketEdgeDomain(a(this,Ze).getValue("baseURI"));typeof Ia(a(this,Ze),"socket_server_base")=="string"&&(t=Ia(a(this,Ze),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n=G(O({roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0},i!==s&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>vd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Rc=new WeakSet,rh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Vg);let Uc=FT;Hl([P.trace("SocketService.connect")],Uc.prototype,"connect",1);Hl([P.trace("SocketService.disconnect")],Uc.prototype,"disconnect",1);Hl([P.trace("SocketService.sendMessagePromise")],Uc.prototype,"sendMessagePromise",1);Hl([P.trace("SocketService.sendMessagePromiseWithTimeout")],Uc.prototype,"sendMessagePromiseWithTimeout",1);class vO{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=tk.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=bk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=hf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Gp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Tk.fromBinary(t).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const t=yield this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)})}createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield this.socketService.sendMessagePromise(U.createConnectedRooms,nk.toBinary({payloads:t}));return Gp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}updateConnectedRooms(t){return u(this,null,function*(){})}disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(i=>({id:i})),r=yield this.socketService.sendMessagePromise(U.deleteConnectedRooms,mk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield this.socketService.sendMessagePromise(U.movePeers,_k.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 SO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,EO=(s,t,e,r)=>{for(var i=r>1?void 0:r?yO(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&&SO(t,e,i),i},ys;class BT extends Bt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);m(this,ys,void 0);T(this,ys,e)}get supportsConnectedMeetings(){return a(this,ys).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.
|
|
11
11
|
Please connect with our support team to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=yield a(this,ys).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e})}createMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=yield a(this,ys).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),yield a(this,ys).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)})}deleteMeetings(e){return u(this,null,function*(){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.`),yield Promise.all(r);const i=yield a(this,ys).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=yield a(this,ys).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})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=yield a(this,ys).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 G(O({},o),{participants:c})}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return G(O({},o),{participants:c})}return o})}}ys=new WeakMap;EO([Rt({maxInvocations:60,period:60})],BT.prototype,"getConnectedMeetings",1);var PO=Object.defineProperty,_O=Object.getOwnPropertyDescriptor,$h=(s,t,e,r)=>{for(var i=r>1?void 0:r?_O(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&&PO(t,e,i),i},pe,Lg;const HT=(Lg=class{constructor(s){h(this,"connectedMeetings");m(this,pe,void 0);T(this,pe,s),this.connectedMeetings=new BT(s)}get telemetry(){return a(this,pe).getValue("telemetry")}get logger(){return a(this,pe).getValue("logger")}static init(s){const t=new HT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,pe).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,pe).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,pe).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)}switchMeeting(e){return u(this,arguments,function*({authToken:s,meetingId:t}){var n,o,c,d;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
12
12
|
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 r={video:a(this,pe).getValue("self").videoEnabled,audio:a(this,pe).getValue("self").audioEnabled};try{a(this,pe).getValue("self").cleanupEvents(),yield a(this,pe).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(o=(n=a(this,pe).getValue("meeting"))==null?void 0:n.meta)==null?void 0:o.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const i=yield jT.init(G(O({},a(this,pe).getValue("options")),{cachedUserDetails:null,defaults:G(O(O({},a(this,pe).getValue("options").defaults),r),{mediaHandler:a(this,pe).getValue("self")}),authToken:s}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(c=i==null?void 0:i.meta)==null?void 0:c.meetingId}`);try{const{hidden:l}=a(this,pe).getValue("self");i.self.setName(a(this,pe).getValue("self").name),yield i.join(),l&&i.self.hide()}catch(l){this.logger.error("ConnectedMeetingsController.joinRoom",{error:l})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(d=i==null?void 0:i.meta)==null?void 0:d.meetingId}`),this.connectedMeetings.emit("meetingChanged",i),i})}handleConnectedRoomsDump(s){const t=a(this,pe).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,pe).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,pe).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,G(O({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,pe).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})}},pe=new WeakMap,Lg);let ql=HT;$h([P.trace("ConnectedMeetingsController.getConnectedMeetings")],ql.prototype,"getConnectedMeetings",1);$h([P.trace("ConnectedMeetingsController.setupEvents")],ql.prototype,"setupEvents",1);$h([P.trace("ConnectedMeetingsController.switchMeeting")],ql.prototype,"switchMeeting",1);var CO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,jl=(s,t,e,r)=>{for(var i=r>1?void 0:r?wO(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&&CO(t,e,i),i};const vn=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static init(s){return u(this,null,function*(){var x,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(CT(s),_e.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=IM(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 u0(s);s.setValue("connectionHandler",l);const p=vn.createSocketService(s),g=p.connect(),f=d.getUserDetails(),v=d.getPlugins();let E,_="";try{yield vn.setupFlagsmith(s)}catch(H){c.error("Failed to setup flagsmith",{error:H})}try{yield g}catch(H){c.error("[Controller]: Failed to connect to socket server:",{error:H})}try{({meetingTitle:_}=yield d.getRoomNodeData()),E=yield f,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(H){c.error("Failed to get room metadata",{error:H})}const C=Nu.init(E.preset,!s.getValue("modules").theme);s.setValue("theme",C);const I=Uu.init(s,C.viewType,E.preset.permissions),M=vn.setupControllers(p,s,E,v,_,C,I);e0(C)&&((x=vn.createRoomNodeClient(s,p).initializeConnection(E.participant.name,i,!1,I))==null||x.catch(re=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:re})})),P.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:$}=yield M;return cw(),new vn(e,$,s)})}static setupFlagsmith(s){return u(this,null,function*(){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=ow(i),d=G(O({entity:Tu.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i},_e.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const p=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?Zi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";yield s.getValue("flagsmith").identify(`${Tu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,p,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(p){o.error("Failed to fetch flagsmith flags")}})}static setupControllers(s,t,e,r,i,n,o){return u(this,null,function*(){var V,b,xe;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),p=t.getValue("logger"),{viewType:g,mediaConstraints:{audio:f}}=n;t.setValue("viewType",g),t.setValue("defaults",O({mediaConfiguration:{audio:{enableHighBitrate:(V=f.enableHighBitrate)!=null?V:!1,enableStereo:(b=f.enableStereo)!=null?b:!1}}},l)),t.setValue("maxPreferredStreams",_e.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let v,E,_,C,I,M,$,x,B;const H=new jD(t,s),re=new vO(s);t.setValue("connectedMeetingsSocketHandler",re);const et=new Fl(t,s),os=new Sr(t,s),ri=new YD(s),cs=new RT(t,s),A=new QD(t,s),y=new qD(s),w=yield si.init(t,cs,d,o,n);t.setValue("selfController",w);const F=yield bf.init(t,w.self,cs,H,i);if(c.participant&&(x=new Er(t,w.self,cs)),(xe=c.e2ee)!=null&&xe.enabled&&c.e2ee.manager.init(p,t.getValue("peerSessionStore")),c.chat&&(E=yield is.init(t,os,w.self,x.participants)),c.internals&&(I=yield bh.init(t)),c.livestream&&n.viewType===hr.Livestream&&t.getValue("flagsmith").hasFeature(te.LIVESTREAM)&&($=new Lf(t,w.self,y)),c.poll&&(v=yield _f.init(t,w.self,et)),c.recording&&(M=new Mf(t,w.self,cs)),c.stage&&(_=new kf(t,ri,cs,w.self,x.participants)),c.plugin){if(!x)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const $s=yield r;C=yield Nc.init(t,$s,A,os,E==null?void 0:E.chat,w.self,x.participants,i)}if(c.connectedMeetings&&(B=yield ql.init(t)),c.pip){const $s=yield vu._init(t,w.self);t.setValue("pip",$s)}const Ie={storesManager:new rD(t,A),pollController:v,selfController:w,metaController:F,chatController:E,stageController:_,pluginController:C,recordingController:M,internalsController:I,livestreamController:$,participantController:x,connectedMeetingsController:B};return{theme:n,permissions:o,controllers:Ie}})}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return _T(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Uc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let $c=vn;jl([P.trace("Controller.init")],$c,"init",1);jl([P.trace("setupFlagsmith")],$c,"setupFlagsmith",1);jl([P.trace("Controller.createRoomNodeClient")],$c,"createRoomNodeClient",1);jl([P.trace("Controller.createSocketService")],$c,"createSocketService",1);class RO{constructor(){h(this,"battery");h(this,"logger");h(this,"init",t=>u(this,null,function*(){this.logger=t;try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}}));h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Tg=new RO;function bO(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=ui.baseURI.prod;t&&(n=t);const o=`https://${Zi({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}var Jr,zi,Yi,bc,El,qT;class kO{constructor(){m(this,El);m(this,Jr,new Audio);m(this,zi,new MediaStream);m(this,Yi,new Map);m(this,bc,void 0);a(this,Jr).srcObject=a(this,zi),a(this,Jr).autoplay=!0}playTracks(t){return u(this,null,function*(){return t.forEach(e=>{a(this,Yi).has(e.id)||(a(this,zi).addTrack(e),a(this,Yi).set(e.id,e))}),this.play()})}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Jr).setSinkId(t)}removeTrack(t){const e=a(this,Yi).get(t);e&&(a(this,zi).removeTrack(e),a(this,Yi).delete(t))}play(){return u(this,null,function*(){return a(this,Jr).srcObject=a(this,zi),a(this,Jr).play().catch(t=>{L(this,El,qT).call(this,t)})})}onError(t){T(this,bc,t)}}Jr=new WeakMap,zi=new WeakMap,Yi=new WeakMap,bc=new WeakMap,El=new WeakSet,qT=function(t){var e;(e=a(this,bc))==null||e.call(this,t)};var Qi;class AO extends kO{constructor(){super();m(this,Qi,void 0);T(this,Qi,new Map)}addParticipantTrack(e,r){a(this,Qi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,Qi).get(e);r&&this.removeTrack(r),a(this,Qi).delete(e)}}Qi=new WeakMap;var IO=Object.defineProperty,MO=Object.getOwnPropertyDescriptor,Gl=(s,t,e,r)=>{for(var i=r>1?void 0:r?MO(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&&IO(t,e,i),i},je,Xi,xg;let Xr=(xg=class{constructor(t,e){m(this,je,void 0);m(this,Xi,void 0);T(this,Xi,t),T(this,je,e)}get peerId(){return a(this,Xi).getValue("peerId")}static initMedia(){return u(this,arguments,function*(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:pr.v4(),n=lr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new jf(n,o);return yield c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c})}static init(t){return u(this,null,function*(){var f,v,_,C,I,M;_e.init();const e=(v=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?v:pr.v4(),{authToken:r,baseURI:i}=t,E=bO(r,i),{meetingId:n}=E,o=Bc(E,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Xr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");ev(l),Tg.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(C=(_=t.modules)==null?void 0:_.tracing)!=null?C:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:G(O({},t),{authToken:`${(I=t.authToken)==null?void 0:I.slice(0,10)}...
|
|
13
|
-
${(M=t.authToken)==null?void 0:M.slice(-10)}`})});const p=yield $c.init(c),g=new Xr(c,p);return c.setValue("meeting",g),g})}static setupContext(t,e,r,i){var d,l;const n=lr.createContext(t,e),o=O(O({},QC),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",XC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",_s(e.cachedUserDetails)),n.setValue("sdkVersion","1.3.0
|
|
13
|
+
${(M=t.authToken)==null?void 0:M.slice(-10)}`})});const p=yield $c.init(c),g=new Xr(c,p);return c.setValue("meeting",g),g})}static setupContext(t,e,r,i){var d,l;const n=lr.createContext(t,e),o=O(O({},QC),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",XC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",_s(e.cachedUserDetails)),n.setValue("sdkVersion","1.3.0"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new AO),n}join(){return u(this,null,function*(){const{selfController:t}=a(this,je);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Tg.cleanup(),a(this,Xi).getValue("peerSessionStore").reset();const{selfController:e}=a(this,je);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,je).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,je).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,je).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,je).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,je).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,je).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,je).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,je).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,je).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,je).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,je).stageController)==null?void 0:t.stage}get stores(){return a(this,je).storesManager}get audio(){return a(this,Xi).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,je).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},je=new WeakMap,Xi=new WeakMap,xg);Gl([dt("0002"),yr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Xr.prototype,"join",1);Gl([dt("0003")],Xr.prototype,"leave",1);Gl([dt("0001"),yr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Xr,"init",1);Xr=Gl([dt("0000")],Xr);const jT=Xr;module.exports=jT;
|
package/dist/index.es.js
CHANGED
|
@@ -28297,7 +28297,7 @@ let Qr = (Ug = class {
|
|
|
28297
28297
|
video: !0
|
|
28298
28298
|
};
|
|
28299
28299
|
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", QC({ baseURI: i.baseURI })), n.setValue("defaults", c), n.setValue("onError", e.onError || (() => {
|
|
28300
|
-
})), n.setValue("cachedUserDetails", _s(e.cachedUserDetails)), n.setValue("sdkVersion", "1.3.0
|
|
28300
|
+
})), n.setValue("cachedUserDetails", _s(e.cachedUserDetails)), n.setValue("sdkVersion", "1.3.0"), (l = e.modules) != null && l.experimentalAudioPlayback && n.setValue("audioPlayback", new kO()), n;
|
|
28301
28301
|
}
|
|
28302
28302
|
join() {
|
|
28303
28303
|
return u(this, null, function* () {
|
package/dist/index.rn.js
CHANGED
|
@@ -10,4 +10,4 @@ ${this.message}`;try{let d=a&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
|
|
|
10
10
|
maxEnergy: ${n(this,Br)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,er)||i<n(this,er))&&m(this,er,i),(!n(this,Br)||i>n(this,Br))&&m(this,Br,i),{energy:(i-n(this,er))/(n(this,Br)-n(this,er))*10||0,isVoice:r})},hc=new WeakSet,Bu=function(t){return t<5},il=new WeakSet,Xf=function(t=n(this,Ui)){var r;if(!n(this,ms)||!t){n(this,tr).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,ms)}`);return}const e={producerId:n(this,ms),energy:Math.round(t),silent:V(r=mo,hc,Bu).call(r,t)};m(this,Ea,e.silent),this.reportRequest(e)},nl=new WeakSet,Zf=function(t){const e=Math.log10(t);return Math.round(e)},g(io,hc),g(io,nl);const _D=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,a=128,o=1;let c=0,d=null;const l=async()=>{try{const f=new Float32Array(a*o),T=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:a,numberOfChannels:o,timestamp:c,data:f});c+=a/i*1e6,await r.ready,await r.write(T)}catch(f){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const p=new MediaStream([e]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(p,{fakeTracks:"fakeTracks:fakeAudioTrack"}),p.enabled=s,p}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 a=e.createMediaStreamDestination();i.connect(a),r.start();const o=a.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},CD=(s=!1)=>{var a,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(a=t==null?void 0:t.getSettings().height)!=null?a: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 wD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,ae=(s,t,e,r)=>{for(var i=r>1?void 0:r?RD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&wD(t,e,i),i};const wt=["video/VP9","video/VP8"];var pc,gc,rt,H,Pa,pt,$i,Fi,Bi,mc,Xt,rr,fc,Hi,qi,gt,yt,Hr,hn,al,tT,ol,sT,cl,rT,Tc,Hu,dl,ru,iT,ll,nT,ul,aT,hl,oT,ze,ot,ji,no,pl,cT,gl,dT,ml,lT;const eT=(ru=class{constructor(s,t){g(this,Hr);g(this,al);g(this,ol);g(this,cl);g(this,Tc);g(this,ll);g(this,ul);g(this,hl);g(this,ze);g(this,ji);g(this,pl);g(this,gl);g(this,ml);u(this,"context");u(this,"authToken");u(this,"e2ee");g(this,pc,void 0);g(this,gc,void 0);g(this,rt,void 0);g(this,H,void 0);g(this,Pa,void 0);g(this,pt,void 0);g(this,$i,void 0);g(this,Fi,void 0);g(this,Bi,void 0);g(this,mc,void 0);g(this,Xt,null);g(this,rr,void 0);g(this,fc,void 0);g(this,Hi,void 0);g(this,qi,void 0);g(this,gt,void 0);g(this,yt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,m(this,Hi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,qi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,rt,e),m(this,$i,!1),m(this,H,new vD(s,e)),m(this,pt,n(this,H).events),m(this,rr,new Set),m(this,gt,new Map),m(this,Fi,!1),m(this,Bi,new Ou(s.getValue("logger"))),m(this,yt,new io(this.context,n(this,H).socketHandler.audioActivity.bind(n(this,H).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,mc,gh(async()=>{if(!n(this,Hr,hn).mediaJoinAttempted)return;const{roomJoined:a}=await this.joinRoom(n(this,gc),n(this,pc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,Hr,hn).mediaJoined}set mediaJoined(s){n(this,Hr,hn).mediaJoined=s}reset(){n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,gt).clear(),n(this,rr).clear(),m(this,Xt,null),n(this,Bi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),m(this,Bi,new Ou)}async joinRoom(s,t,e=!1,r=!1,i={}){n(this,Hr,hn).mediaJoinAttempted=!0,m(this,$i,!0),e&&this.reset();try{return await n(this,Bi).push(()=>V(this,al,tT).call(this,s,t,r,i),"joinRoom")}catch(a){return this.logger.error("Error in room joining process",{error:a}),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:a}}}async initializeConnection(s,t,e=!1,r={}){return n(this,Xt)?n(this,Xt):(m(this,Xt,(async()=>{try{await V(this,Tc,Hu).call(this,s,t,e,r)}catch(i){throw m(this,Xt,null),i}})()),n(this,Xt))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}async leaveRoom(){n(this,H).stopAllTransports(),m(this,Fi,!1),n(this,Hr,hn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,rt).sendMessagePromise(n(this,pt).leaveRoom,Vw.toBinary(s)).then(e=>{var r;(r=_R.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():n(this,H).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=n(this,H).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await n(this,H).closeConsumers(t)}async _shareWebcam(s,t){var p,f,T,E;const e=t==="video/VP9"?ce.WEBCAM:ce.WEBCAM_BACKUP,r=V(this,ze,ot).call(this,e);if(r){const P=await r;if(n(this,H).producers.has(P)){const _=n(this,H).producers.get(P);if(!_.closed)return await _.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(wt.filter(P=>P!==t)),a=V(this,ml,lT).call(this,s,i),o=ba(this.context,"disableSimulcast"),c=(f=(p=this.context)==null?void 0:p.getValue("overrides"))==null?void 0:f.simulcastConfig;o||c&&c.disable||!((E=(T=this.context)==null?void 0:T.getValue("theme"))!=null&&E.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=u0(this.context,s)),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,gt).delete(e)},h=n(this,H).createProducer(a,l);return V(this,ji,no).call(this,e,h.then(P=>P.id)),h.then(P=>P.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 a,o;return((o=(a=n(this,Pa).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,qi).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:ye.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,gt).delete(ce.SCREENSHARE_VIDEO),n(this,gt).delete(ce.SCREENSHARE_AUDIO)},a=n(this,H).createProducer(r,i);V(this,ji,no).call(this,ce.SCREENSHARE_VIDEO,a.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,H).createProducer(c,d),V(this,ji,no).call(this,ce.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([a,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Pt("track undefined");const t=V(this,ze,ot).call(this,ce.MIC);if(t){const a=await t;if(n(this,H).producers.has(a)){const o=n(this,H).producers.get(a);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),n(this,yt)&&(n(this,yt).audioTrack=s,n(this,yt).producerId=a,n(this,yt).start());return}await n(this,H).closeProducer(a,{stopTrack:!1})}await this.shareMic(s);return}const e=V(this,gl,dT).call(this,s),r=()=>{n(this,gt).delete(ce.MIC)},i=n(this,H).createProducer(e,r);V(this,ji,no).call(this,ce.MIC,i.then(a=>a.id)),await i.then(a=>{n(this,yt)&&(n(this,yt).audioTrack=a.track,n(this,yt).producerId=a.id,n(this,yt).start())})}catch(t){throw new b(t)}}async pauseMic(){var r;const s=await V(this,ze,ot).call(this,ce.MIC),t=n(this,H).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=n(this,yt))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,rt).sendMessage(n(this,pt).toggleProducer,Fc.toBinary(e))}async pauseWebcam(){const s=await V(this,ze,ot).call(this,ce.WEBCAM),t=await V(this,ze,ot).call(this,ce.WEBCAM_BACKUP),e=n(this,H).producers.get(s),r=n(this,H).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=a=>{const o={producerId:a.id,pause:!0};n(this,rt).sendMessage(n(this,pt).toggleProducer,Fc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await V(this,ze,ot).call(this,ce.MIC),t=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,rt).sendMessage(n(this,pt).toggleProducer,Fc.toBinary(e))}async resumeWebcam(s=ce.WEBCAM){const t=await V(this,ze,ot).call(this,s),e=n(this,H).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(w.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,rt).sendMessage(n(this,pt).toggleProducer,Fc.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?ce.WEBCAM:ce.WEBCAM_BACKUP,e=await V(this,ze,ot).call(this,t);V(this,pl,cT).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var t;const s=await V(this,ze,ot).call(this,ce.MIC);s&&await n(this,H).closeProducer(s),(t=n(this,yt))==null||t.stop(),n(this,gt).delete(ce.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await V(this,ze,ot).call(this,ce.SCREENSHARE_VIDEO),t=await V(this,ze,ot).call(this,ce.SCREENSHARE_AUDIO);s&&await n(this,H).closeProducer(s),t&&await n(this,H).closeProducer(t),n(this,rr).clear(),n(this,gt).delete(ce.SCREENSHARE_VIDEO),n(this,gt).delete(ce.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await V(this,ze,ot).call(this,ce.WEBCAM),r=await V(this,ze,ot).call(this,ce.WEBCAM_BACKUP);await n(this,H).closeProducer(e,{stopTrack:!1}),await n(this,H).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await V(this,ze,ot).call(this,ce.SCREENSHARE_VIDEO);await n(this,H).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await n(this,H).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};n(this,H).socketHandler.kickPeer(t)}kickAll(){n(this,H).socketHandler.kickAll()}async muteAll(s){if(!await n(this,H).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,H).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await n(this,H).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await n(this,H).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 n(this,rt).sendMessagePromise(n(this,pt).globalPinPeer,zw.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&n(this,H).producers.get(s.producerId)&&n(this,rr).add(s.consumerPeerId),n(this,rr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));n(this,H).switchConsumersToLayer(e,t)}async handleSocketEvents(){n(this,rt).on(n(this,pt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=ZR.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Os.AUDIO?"audio/opus":"video/VP8"),i.kind===Os.VIDEO&&!i.screenShare&&((e=(t=n(this,Pa).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===wt[0]))>=0&&n(this,Hi).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(w.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===Os.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,rt).on(n(this,pt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=bp.fromBinary(s);if(o)return;const c=r===Os.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(bp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?w.MUTE_SELF:w.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(w.PRODUCER_TOGGLE,{peerId:t,producerId:a,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===a).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(w.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,rt).on(n(this,pt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=gu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,rr).delete(t),n(this,H).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(w.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,rt).on(n(this,pt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=sb.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=n(this,H).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),n(this,H).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),n(this,H).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(w.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})}}),n(this,rt).on(n(this,pt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,$i)&&!n(this,Fi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),n(this,mc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=n(this,H).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(w.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(n(this,H).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(w.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,a;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){n(this,qi).get(c).add(s);break}}for(let o=0;o<=wt.length;o+=1){const c=wt[o];if(((a=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:a.codecs.findIndex(d=>d.mimeType===c))>=0||o===wt.length-1){n(this,Hi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(n(this,Hi).forEach(t=>t.delete(s)),n(this,qi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===wt[0])&&this.disableWebcam(e)}))}},pc=new WeakMap,gc=new WeakMap,rt=new WeakMap,H=new WeakMap,Pa=new WeakMap,pt=new WeakMap,$i=new WeakMap,Fi=new WeakMap,Bi=new WeakMap,mc=new WeakMap,Xt=new WeakMap,rr=new WeakMap,fc=new WeakMap,Hi=new WeakMap,qi=new WeakMap,gt=new WeakMap,yt=new WeakMap,Hr=new WeakSet,hn=function(){return this.context.getValue("connectionHandler")},al=new WeakSet,tT=async function(s,t,e,r){m(this,gc,s);try{return n(this,Xt)?await n(this,Xt):await V(this,Tc,Hu).call(this,s,t,e,r),V(this,cl,rT).call(this,t),{roomJoined:await V(this,ol,sT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1,error:i}}finally{m(this,Xt,null)}},ol=new WeakSet,sT=async function(){try{this.mediaJoined=!0;const{roomState:s}=await n(this,H).socketHandler.notifySelfJoinComplete();return m(this,pc,s.roomUuid),m(this,Fi,!0),m(this,$i,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},cl=new WeakSet,rT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...ye.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)},Tc=new WeakSet,Hu=async function(s,t,e,r){var i,a;try{(a=n(this,fc))!=null||m(this,fc,V(i=eT,dl,iT).call(i));const o=V(this,ll,nT).call(this);await V(this,ul,aT).call(this,s,t,e,o),await n(this,H).setupTransports({send:!0,recv:!0}),await V(this,hl,oT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},dl=new WeakSet,iT=function(){const{ipInfo:s}=it();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},ll=new WeakSet,nT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=oD(s);return m(this,Pa,t),t},ul=new WeakSet,aT=async function(s,t,e,r){await Of(async(i,a)=>{if(!n(this,rt).isConnected){a(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await n(this,H).socketHandler.joinRoom(t,s,r,e,n(this,fc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},hl=new WeakSet,oT=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===F.Allowed&&e.push(this.shareWebcam(CD(!1))),s.canProduceAudio===F.Allowed){const r=_D(!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})}},ze=new WeakSet,ot=function(s){return n(this,gt).get(s)},ji=new WeakSet,no=function(s,t){return n(this,gt).set(s,t)},pl=new WeakSet,cT=function(s){return n(this,gt).delete(s)},gl=new WeakSet,dT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},ml=new WeakSet,lT=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}},g(ru,dl),ru);let re=eT;ae([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1);ae([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1);ae([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1);ae([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1);ae([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1);ae([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1);ae([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1);ae([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1);ae([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1);ae([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1);ae([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1);ae([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1);ae([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1);ae([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1);ae([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1);ae([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1);ae([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1);ae([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1);ae([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1);ae([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1);ae([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1);ae([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1);ae([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1);ae([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1);ae([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1);ae([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1);ae([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1);ae([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function uT(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 hT(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 bD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,on=(s,t,e,r)=>{for(var i=r>1?void 0:r?kD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bD(t,e,i),i},Gi,fs,Y,mt,bt,Pg;const pT=(Pg=class{constructor(s,t,e,r){g(this,mt);u(this,"self");u(this,"authToken");g(this,Gi,void 0);u(this,"viewType");g(this,fs,void 0);g(this,Y,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,Y,s),this.viewType=r,this.authToken=a,m(this,Gi,i),m(this,fs,e),this.setupEvents()}get peerId(){return n(this,Y).getValue("peerId")}get telemetry(){return n(this,Y).getValue("telemetry")}get logger(){return n(this,Y).getValue("logger")}get mediaJoined(){return n(this,Y).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=it(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await We.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const h=!s.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const p=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),s.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:ye.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Hm(s),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new pT(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===F.Allowed&&r)try{await n(this,mt,bt).shareMic(s),this.self.audioEnabled||n(this,mt,bt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===F.Allowed&&i)try{const d=await n(this,mt,bt).shareWebcam(t);d&&d.id!==t.id&&n(this,Y).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await n(this,mt,bt).shareWebcam(d),this.self.videoEnabled||n(this,mt,bt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===F.Allowed&&a)try{await((c=n(this,mt,bt))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){n(this,Y).getValue("callstats").callEnded(),n(this,mt,bt).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,Y).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,Y).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,Y).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,Y).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Y).getValue("peerSessionStore").on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,Y).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,Y).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=lr.v4()),n(this,Gi).updateURL(t),n(this,Y).getValue("telemetry").resetPeerId(t),it().setHeader("tracing-id",t),or.remapContext(t,n(this,Y)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,Y).getValue("peerSessionStore").on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,fs).on(L.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,fs).on(Qc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,Y).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),n(this,fs).on(L.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,fs).on(L.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,fs).on(L.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,Y).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,Y).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,Y).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,Y).getValue("callstats").audioOff())}),n(this,Y).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,Y).getValue("callstats").videoOff())}),n(this,Y).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,Y).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,fs).joinRoom(this.self);n(this,fs).socket.flush();const e=Sh(t.stageType);if(n(this,Y).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),n(this,Y).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=n(this,Y).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,Y).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,Y).notify("stageStatus");try{(e=n(this,Gi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}hT(n(this,Y)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o,c;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,Y).getAllValues();try{if(e===dr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}uT(n(this,Y),{socket:n(this,Gi),peerId:t})}const{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:h}=this.self.permissions,{roomJoined:p,error:f}=(o=await((a=n(this,mt,bt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:d,canProduceVideo:l,canProduceScreenshare:h})))!=null?o:{};if(!p)throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:f}),f;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 b(`${(c=d==null?void 0:d.message)!=null?c:"could not connect to media servers"}`,"0002")}}async leaveMediaRoom(s){const t=n(this,Y).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===dr.Webinar)&&n(this,mt,bt)&&(n(this,mt,bt).mediaJoined&&s!=="disconnected"&&await n(this,mt,bt).leaveRoom(),!(s==="stageLeft"&&t===dr.Livestream)&&(n(this,mt,bt).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()}},Gi=new WeakMap,fs=new WeakMap,Y=new WeakMap,mt=new WeakSet,bt=function(){return n(this,Y).getValue("roomNodeClient")},Pg);let Zr=pT;on([y.trace("SelfController.resetSelf")],Zr.prototype,"resetSelf",1);on([y.trace("SelfController.setupEvents")],Zr.prototype,"setupEvents",1);on([y.trace("SelfController.joinRoom")],Zr.prototype,"joinRoom",1);on([y.trace("SelfController.leaveRoom")],Zr.prototype,"leaveRoom",1);on([y.trace("SelfController.joinMediaRoom")],Zr.prototype,"joinMediaRoom",1);on([y.trace("SelfController.leaveMediaRoom")],Zr.prototype,"leaveMediaRoom",1);on([y.trace("SelfController.init")],Zr,"init",1);var Sc;class AD{constructor(t){g(this,Sc,void 0);m(this,Sc,t)}on(t,e){let r;t===L.roomPeerCount?r=Ip.fromBinary.bind(Ip):r=Bp.fromBinary.bind(Bp),n(this,Sc).on(t,({payload:i})=>{if(t===L.roomPeerCount&&!i)return;const a=r(i);e(a)})}}Sc=new WeakMap;var vc,yc;class ID{constructor(t,e){g(this,vc,void 0);g(this,yc,void 0);m(this,vc,e),m(this,yc,t)}get logger(){return n(this,yc).getValue("logger")}on(t,e){let r,i;switch(t){case L.transcript:{r=Jl.fromBinary.bind(Jl),i=Jl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,vc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}vc=new WeakMap,yc=new WeakMap;var MD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,Ih=(s,t,e,r)=>{for(var i=r>1?void 0:r?DD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&MD(t,e,i),i},ir,_a;class Vl{constructor(t,e){g(this,ir,void 0);g(this,_a,void 0);m(this,ir,e),m(this,_a,t)}get logger(){return n(this,_a).getValue("logger")}get telemetry(){return n(this,_a).getValue("telemetry")}getPolls(){return n(this,ir).sendMessagePromise(Us.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,ir).sendMessage(Us.createPoll,$I.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,ir).sendMessage(Us.votePoll,BI.toBinary(r))}on(t,e){let r,i;switch(t){case Us.updatePoll:case Us.createPoll:case Us.votePoll:{r=Zl.fromBinary.bind(Zl),i=Zl.create();break}}n(this,ir).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,ir).removeListeners(t)}}ir=new WeakMap,_a=new WeakMap;Ih([y.trace("PollSocketHandler.getPolls")],Vl.prototype,"getPolls",1);Ih([y.trace("PollSocketHandler.createPoll")],Vl.prototype,"createPoll",1);Ih([y.trace("PollSocketHandler.votePoll")],Vl.prototype,"votePoll",1);var OD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,VD=(s,t,e,r)=>{for(var i=r>1?void 0:r?ND(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&OD(t,e,i),i},Nt;class gT{constructor(t,e){u(this,"socket");g(this,Nt,void 0);m(this,Nt,t),this.socket=e,this.handleSocketEvents(),n(this,Nt).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Nt).getValue("telemetry")}get logger(){return n(this,Nt).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(L.joinRoom,Mb.toBinary(e));try{const{peer:a}=dn.fromBinary((await r).payload);n(this,Nt).getValue("connectionHandler").socketJoined=!0,n(this,Nt).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,Nt).getValue("peerSessionStore").emit(w.ROOM_STATE,d),n(this,Nt).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new b("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}}async getAllAddedParticipants(){try{return mk.fromBinary((await this.socket.sendMessagePromise(L.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(L.getRoomPeersInfo,Eb.toBinary(a));i=Kl.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(L.getRoomPeersInfo);t=Kl.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(L.getRoomPeersInfo);t=Kl.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(L.getPeerInfo,Xm.toBinary({peerId:t}));e=dn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Mp.create();try{const e=await this.socket.sendMessagePromise(L.getRoomInfo);t=Mp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Vp.create();try{const e=await this.socket.sendMessagePromise(L.getRoomStageState);t=Vp.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(L.broadcastMessage,Ya.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(L.broadcastToEntity,Ya.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(L.broadcastToEntity,Ya.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(L.leaveRoom,Ob.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(L.kick,ef.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(L.kickAll,zm.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(L.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.acceptWaitingRoomRequests,Ek.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.denyWaitingRoomRequests,_k.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Qc.updateUserPreset,Xk.toBinary(r))}handleSocketEvents(){this.socket.on(L.broadcastMessage,({payload:t})=>{try{const e=Ya.fromBinary(t);n(this,Nt).getValue("peerSessionStore").emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(L.broadcastToEntity,({payload:t})=>{try{const e=Ya.fromBinary(t);n(this,Nt).getValue("peerSessionStore").emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case L.joinRoom:case L.leaveRoom:case L.kick:case L.kickAll:{r=dn.fromBinary.bind(dn),i=dn.create();break}case L.getWaitingRoomRequests:{r=(a,o)=>a?Np.fromBinary(a,o):{requests:[]},i=Np.create();break}case L.recordingPaused:case L.recordingStarted:case L.recordingStopped:{r=jp.fromBinary.bind(jp);break}case Qc.updateUserPreset:{r=Lp.fromBinary.bind(Lp);break}case vs.peerJoinedBroadcast:case wr.peerJoinedBroadcast:{r=wp.fromBinary.bind(wp);break}case vs.selfJoinComplete:case wr.selfJoinComplete:{r=pu.fromBinary.bind(pu);break}case vs.globalPeerPinBroadcast:case wr.globalPeerPinBroadcast:{r=kp.fromBinary.bind(kp);break}case vs.selectedPeer:case wr.selectedPeer:{r=hu.fromBinary.bind(hu);break}case vs.selectedPeerDiff:case wr.selectedPeerDiff:{r=Cp.fromBinary.bind(Cp);break}case vs.leaveRoom:case wr.leaveRoom:{r=gu.fromBinary.bind(gu);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Qc.getUserPresets,Gk.toBinary(e)),i=zk.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Nt=new WeakMap;VD([y.trace("RoomSocketHandler.joinRoom")],gT.prototype,"joinRoom",1);var Et;class LD{constructor(t){g(this,Et,void 0);m(this,Et,t)}async getStageRequests(){const{payload:t}=await n(this,Et).sendMessagePromise(L.getStageRequests);return t?Xl.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,Et).sendMessage(L.requestStageAccess)}cancelRequestAccess(){n(this,Et).sendMessage(L.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,Et).sendMessage(L.grantStageAccess,AI.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,Et).sendMessage(L.denyStageAccess,MI.toBinary(e))}joinStage(){return n(this,Et).sendMessagePromise(L.joinStage,void 0,void 0,L.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,Et).sendMessagePromise(L.leaveStage,qp.toBinary(e),void 0,L.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,Et).sendMessagePromise(L.leaveStage,qp.toBinary(e))}on(t,e){let r;switch(t){case L.grantStageAccess:case L.denyStageAccess:{r=void 0;break}case L.getStagePeers:{r=Hp.fromBinary.bind(Hp);break}case L.getStageRequests:case L.requestStageAccess:case L.cancelStageRequest:{r=Xl.fromBinary.bind(Xl);break}case L.peerStageStatusUpdate:{r=Ap.fromBinary.bind(Ap);break}}n(this,Et).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,Et).sendMessagePromise(L.getPeerInfo,Xm.toBinary({peerId:t}));return dn.fromBinary(e.payload)}}Et=new WeakMap;var Fe,Ec;class xD{constructor(t,e){g(this,Fe,void 0);g(this,Ec,void 0);m(this,Fe,e),m(this,Ec,t)}get logger(){return n(this,Ec).getValue("logger")}addPlugin(t,e){n(this,Fe).sendMessage(j.addPlugin,WA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Fe).sendMessage(j.removePlugin,KA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Fe).sendMessagePromise(j.getPlugins);return t?TI.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Fe).sendMessage(j.customPluginEventToRoom,iI.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Fe).sendMessage(j.customPluginEventToPeers,aI.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Fe).sendMessage(j.enablePluginForRoom,YA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Fe).sendMessage(j.enablePluginForPeers,eI.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Fe).sendMessage(j.disablePluginForRoom,XA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Fe).sendMessage(j.disablePluginForPeers,sI.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Fe).sendMessage(j.storeInsertKeys,xp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Fe).sendMessage(j.storeGetKeys,lI.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Fe).sendMessage(j.storeDeleteKeys,hI.toBinary(a),i)}storeDelete(t,e,r){n(this,Fe).sendMessage(j.storeDelete,gI.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};n(this,Fe).sendMessage(j.storeInsertKeys,xp.toBinary(i))}on(t,e){let r;switch(t){case j.addPlugin:case j.enablePluginForPeers:case j.enablePluginForRoom:{r=Su.fromBinary.bind(Su);break}case j.removePlugin:case j.disablePluginForPeers:case j.disablePluginForRoom:{r=Up.fromBinary.bind(Up);break}case j.customPluginEventToPeers:case j.customPluginEventToRoom:{r=Fp.fromBinary.bind(Fp);break}case j.storeInsertKeys:case j.storeGetKeys:case j.storeDeleteKeys:case j.storeDelete:{r=$p.fromBinary.bind($p);break}}n(this,Fe).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Fe=new WeakMap,Ec=new WeakMap;var UD=Object.defineProperty,$D=(s,t,e)=>t in s?UD(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,FD=(s,t,e)=>($D(s,typeof t!="symbol"?t+"":t,e),e),Mh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},I=(s,t,e)=>(Mh(s,t,"read from private field"),e?e.call(s):t.get(s)),pe=(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)},se=(s,t,e,r)=>(Mh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ve=(s,t,e)=>(Mh(s,t,"access private method"),e),vd={},BD={get exports(){return vd},set exports(s){vd=s}},_n=typeof Reflect=="object"?Reflect:null,eg=_n&&typeof _n.apply=="function"?_n.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},id;_n&&typeof _n.ownKeys=="function"?id=_n.ownKeys:Object.getOwnPropertySymbols?id=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:id=function(s){return Object.getOwnPropertyNames(s)};function HD(s){console&&console.warn&&console.warn(s)}var mT=Number.isNaN||function(s){return s!==s};function ne(){ne.init.call(this)}BD.exports=ne;vd.once=WD;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var tg=10;function Ll(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return tg},set:function(s){if(typeof s!="number"||s<0||mT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");tg=s}});ne.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ne.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||mT(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 fT(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return fT(this)};ne.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")eg(c,this,t);else for(var d=c.length,l=ET(c,d),e=0;e<d;++e)eg(l[e],this,t);return!0};function TT(s,t,e,r){var i,a,o;if(Ll(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=fT(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,HD(c)}return s}ne.prototype.addListener=function(s,t){return TT(this,s,t,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(s,t){return TT(this,s,t,!0)};function qD(){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 ST(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=qD.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(s,t){return Ll(t),this.on(s,ST(this,s,t)),this};ne.prototype.prependOnceListener=function(s,t){return Ll(t),this.prependListener(s,ST(this,s,t)),this};ne.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Ll(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():jD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ne.prototype.off=ne.prototype.removeListener;ne.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function vT(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?GD(i):ET(i,i.length)}ne.prototype.listeners=function(s){return vT(this,s,!0)};ne.prototype.rawListeners=function(s){return vT(this,s,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):yT.call(s,t)};ne.prototype.listenerCount=yT;function yT(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ne.prototype.eventNames=function(){return this._eventsCount>0?id(this._events):[]};function ET(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function jD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function GD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function WD(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}PT(s,t,a,{once:!0}),t!=="error"&&JD(s,i,{once:!0})})}function JD(s,t,e){typeof s.on=="function"&&PT(s,"error",t,e)}function PT(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class KD extends S.MessageType{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const sg=new KD;class _T{static encode(t){return sg.toBinary(t)}static decode(t){return sg.fromBinary(new Uint8Array(t))}}function zD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var _r;class YD{constructor(t={}){FD(this,"opts"),pe(this,_r,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},se(this,_r,0)}async wait(){se(this,_r,I(this,_r)+1);const t=zD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**I(this,_r)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return I(this,_r)}reset(){se(this,_r,0)}}_r=new WeakMap;const vr={debug:0,info:1,warn:2,error:3};var ii,ni;class QD{constructor(t){pe(this,ii,void 0),pe(this,ni,void 0),se(this,ii,console),se(this,ni,t)}debug(...t){vr[I(this,ni)]>vr.debug||I(this,ii).debug("[Sockrates]:",...t)}info(...t){vr[I(this,ni)]>vr.info||I(this,ii).info("[Sockrates]:",...t)}warn(...t){vr[I(this,ni)]>vr.warn||I(this,ii).warn("[Sockrates]:",...t)}error(...t){vr[I(this,ni)]>vr.error||I(this,ii).error("[Sockrates]:",...t)}}ii=new WeakMap,ni=new WeakMap;var CT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(CT||{});const XD="2",ZD="3";var Re,pn,Se,Oe,Cr,Ge,ar,Wr,Ss,gn,xs,qu,wT,ao,nd,ju,RT,Gu,rg,yd,Wu,Ju,bT,uo,ad,ho,Ed,Pd,Ku,Cn,po,go,_d;class eO{constructor(t,e){var f,T,E,P,_,A,M,x,N,$;pe(this,qu),pe(this,ao),pe(this,ju),pe(this,Gu),pe(this,yd),pe(this,Ju),pe(this,uo),pe(this,ho),pe(this,Pd),pe(this,Cn),pe(this,go),pe(this,Re,void 0),pe(this,pn,void 0),pe(this,Se,void 0),pe(this,Oe,void 0),pe(this,Cr,void 0),pe(this,Ge,void 0),pe(this,ar,void 0),pe(this,Wr,void 0),pe(this,Ss,void 0),pe(this,gn,void 0),pe(this,xs,void 0);var r,i,a,o,c,d,l,h,p;se(this,pn,t),se(this,Cr,[]),se(this,Ge,new vd),se(this,ar,!0),se(this,Ss,!1),se(this,Se,e!=null?e:{}),(f=(r=I(this,Se)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=I(this,Se)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=I(this,Se)).pingTimeout)!=null||(a.pingTimeout=3e4),(P=(o=I(this,Se)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=I(this,Se)).debug)!=null||(c.debug=!0),(A=(d=I(this,Se)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(M=(l=I(this,Se)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(x=(h=I(this,Se)).queueOnDisconnect)!=null||(h.queueOnDisconnect=!1),(N=(p=I(this,Se)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),se(this,Wr,{code:void 0,reason:void 0}),se(this,Oe,($=I(this,Se).logger)!=null?$:new QD(I(this,Se).debug?"debug":"info")),se(this,xs,new YD)}get readyState(){var t;return(t=I(this,Re))==null?void 0:t.readyState}get url(){return I(this,pn)}updateURL(t){se(this,pn,t),ve(this,Ju,bT).call(this)}get config(){return I(this,Se)}get sendQueue(){return I(this,Cr)}flush(){if(!I(this,Se).queueOnDisconnect)return!1;const t=[];return I(this,Cr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),se(this,Cr,t),I(this,Cr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){I(this,Oe).debug("Websocket was already connecting or connected.");return}if(I(this,ar)!==!1)return new Promise((e,r)=>{ve(this,Cn,po).call(this),ve(this,go,_d).call(this);try{se(this,Re,new WebSocket(ve(this,qu,wT).call(this,I(this,pn)))),I(this,Re).binaryType="arraybuffer",I(this,Oe).debug("Connecting");const i=setTimeout(()=>{I(this,Oe).debug("Connection timeout. Closing socket"),se(this,ar,!0),ve(this,go,_d).call(this),I(this,Re).close(3001,"Connection Timeout"),I(this,Se).autoReconnect&&!I(this,Ss)&&(I(this,Ge).emit("reconnecting"),ve(this,uo,ad).call(this)),r(new Error("Connection timed out!"))},I(this,Se).connectionTimeout);I(this,Re).onopen=()=>{I(this,Oe).debug(`Ready State: ${CT[I(this,Re).readyState]}`),i&&clearTimeout(i),ve(this,Pd,Ku).call(this),se(this,Wr,{code:void 0,reason:void 0}),I(this,Ge).emit("connected"),I(this,Se).flushOnReconnect&&this.flush(),e()},I(this,Re).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),I(this,Oe).debug("Socket closed. Close event:",{event:a}),I(this,Oe).debug(`Connection closed code: ${o}`),I(this,Oe).debug(`Connection closed reason: ${c}`),I(this,Ss)||ve(this,yd,Wu).call(this,o,c)}catch(o){ve(this,ao,nd).call(this,o)}},I(this,Re).onerror=a=>{ve(this,ao,nd).call(this,a)},I(this,Re).onmessage=a=>ve(this,ju,RT).call(this,a)}catch(i){ve(this,ao,nd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(I(this,Se).queueOnDisconnect&&(!I(this,Re)||I(this,Re).readyState!==1))return I(this,Oe).debug("Queuing message since socket is not connected!",a),I(this,Cr).push(a),!1;const o=_T.encode(a);return ve(this,ho,Ed).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ve(this,ho,Ed).call(this,t)}receive(t,e){return I(this,Ge).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){I(this,Ge).on(t,e);return}this.receive(t,e)}removeAllListeners(){I(this,Ge).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){I(this,Ge).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){I(this,Ge).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){se(this,ar,!1),ve(this,Cn,po).call(this),this.removeAllListeners(),se(this,Wr,{code:1e3,reason:"Sockrates disconnect method called"}),I(this,Re).close(1e3,"Sockrates disconnect method called.")}}Re=new WeakMap,pn=new WeakMap,Se=new WeakMap,Oe=new WeakMap,Cr=new WeakMap,Ge=new WeakMap,ar=new WeakMap,Wr=new WeakMap,Ss=new WeakMap,gn=new WeakMap,xs=new WeakMap,qu=new WeakSet,wT=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)://.")},ao=new WeakSet,nd=function(s,t){I(this,Oe).error("Error:",{error:s}),I(this,Ge).emit("errored",{error:s}),t==null||t(s)},ju=new WeakSet,RT=function(s){if(ve(this,Pd,Ku).call(this),s.data===XD){I(this,Oe).debug("Received ping from server"),ve(this,ho,Ed).call(this,ZD);return}const t=_T.decode(s.data),{id:e,payload:r}=t;I(this,Oe).debug("Received message",{event:t.event,messageID:e}),I(this,Ge).emit(t.event.toString(),{id:e,payload:r})},Gu=new WeakSet,rg=function(){return I(this,Re).readyState===1},yd=new WeakSet,Wu=function(s,t){se(this,Wr,{reason:t,code:s}),I(this,Ge).emit("disconnected",{code:s,reason:t})},Ju=new WeakSet,bT=function(){const{reason:s,code:t}=I(this,Wr);t&&t!==1e3&&I(this,ar)&&I(this,Se).autoReconnect&&!I(this,Ss)&&(I(this,Oe).debug(`Triggering reconnection due to ${s}.`),I(this,Ge).emit("reconnecting"),ve(this,uo,ad).call(this))},uo=new WeakSet,ad=async function(s=!0){if(s&&I(this,Ss)){I(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(I(this,Ss)||I(this,xs).reset(),I(this,Se).maxReconnectionAttempts!==null&&I(this,xs).getAttempts()>=I(this,Se).maxReconnectionAttempts){I(this,Ge).emit("failed"),se(this,Ss,!1);return}se(this,Ss,!0),ve(this,go,_d).call(this),ve(this,Cn,po).call(this);try{if(await I(this,xs).wait(),I(this,ar)===!1)return;if(I(this,Oe).debug(`Reconnection attempt ${I(this,xs).getAttempts()}`),I(this,Ge).emit("reconnectAttempt",{attempt:I(this,xs).getAttempts()}),await this.connect(),!ve(this,Gu,rg).call(this))throw Error("Reconnect Failed");se(this,Ss,!1),se(this,Wr,{code:void 0,reason:void 0}),I(this,Ge).emit("reconnected")}catch(t){I(this,Oe).debug("Failed to reconnect."),I(this,Ge).emit("reconnectFailure",{attempt:I(this,xs).getAttempts()}),ve(this,uo,ad).call(this,!1)}},ho=new WeakSet,Ed=function(s){try{return I(this,Re).send(s),!0}catch(t){return I(this,Oe).error(t.message),!1}},Pd=new WeakSet,Ku=function(){this.config.disconnectOnPingTimeout&&(I(this,Oe).debug("Resetting ping timeout"),ve(this,Cn,po).call(this),se(this,gn,setTimeout(()=>{var s;I(this,Oe).debug("Disconnecting the socket due to ping timeout"),se(this,ar,!0);const t=3002,e="Ping timeout";(s=I(this,Re))==null||s.close(t,e),ve(this,yd,Wu).call(this,t,e)},I(this,Se).pingTimeout)))},Cn=new WeakSet,po=function(){I(this,gn)&&(clearTimeout(I(this,gn)),se(this,gn,void 0))},go=new WeakSet,_d=function(){I(this,Re)&&(I(this,Re).onopen=void 0,I(this,Re).onerror=void 0,I(this,Re).onmessage=void 0,I(this,Re).onclose=void 0)};var tO=Object.defineProperty,sO=Object.getOwnPropertyDescriptor,xl=(s,t,e,r)=>{for(var i=r>1?void 0:r?sO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tO(t,e,i),i};const ig=65535,rO=3e3;var qr,Ee,Pe,ke,Zt,Ye,Pc,zu,_c,Yu,_g;const kT=(_g=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Pe);g(this,Pc);g(this,_c);g(this,qr,void 0);g(this,Ee,void 0);u(this,"roomName");u(this,"authToken");u(this,"capabilities");g(this,Zt,void 0);g(this,Ye,void 0);var a;if(!t||!e||!r)throw new b("peerId, meetingId, or authToken can not be empty","0404");m(this,Zt,void 0),m(this,Ye,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,qr,V(this,Pc,zu).call(this,t)),m(this,Ee,new eO(n(this,qr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,Pe,ke).socketJoinAttempted}set joinAttempted(s){n(this,Pe,ke).socketJoinAttempted=s}get telemetry(){return n(this,Ye).getValue("telemetry")}get logger(){return n(this,Ye).getValue("logger")}get peerId(){return n(this,Ye).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,qr,V(this,Pc,zu).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ee).updateURL(n(this,qr))}static getSocketEdgeDomain(s){return Yi({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,qr)}async connect(){n(this,Pe,ke).socketJoinAttempted=!0,await n(this,Ee).connect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,Pe,ke).socketJoinAttempted=!1,n(this,Ee).disconnect(),n(this,Pe,ke).socketJoinAttempted=!0,n(this,Pe,ke).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ee).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,Ye).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:V(this,_c,Yu).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const a=i!=null?i:s;return new Promise((o,c)=>{const d=(E,P)=>{n(this,Ee).removeListener(a,E),n(this,Ee).removeListener(ig,P),n(this,Ee).removeListener(wr.errorResponse,P),n(this,Ee).removeListener(vs.errorResponse,P)},l=r!=null?r:V(this,_c,Yu).call(this),h={};n(this,Ye).getValue("telemetry").injectContext(h);const f=({id:E,payload:P})=>{if(l===E){let _;try{const A=pR.fromBinary(P);_=new Error(A.errorMessage)}catch(A){_=new Error("failed to parse error message",{cause:A});try{const M=gb.fromBinary(P);_=new Error(M.message)}catch(M){_=new Error("failed to parse error message",{cause:M})}}c(_),d(T,f)}},T=({id:E,payload:P})=>{l===E&&(o({id:E,payload:P}),d(T,f))};n(this,Ee).on(a,T),n(this,Ee).on(ig,f),n(this,Ee).on(wr.errorResponse,f),n(this,Ee).on(vs.errorResponse,f),setTimeout(()=>{d(T,f),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ee).send(s,l,e,new TextEncoder().encode(JSON.stringify(h)))})}on(s,t){n(this,Ee).on(s,t)}onStateEvent(s,t){n(this,Ee).on(s,t)}removeListener(s,t){n(this,Ee).removeListener(s,t)}removeListeners(s){n(this,Ee).removeListeners(s)}flush(){return n(this,Ee).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),n(this,Zt)&&(clearTimeout(n(this,Zt)),m(this,Zt,void 0)),n(this,Pe,ke).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:y.location.country});const{recv:e,send:r}=(i=n(this,Pe,ke).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Pn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Pn.CONNECTED?n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}):m(this,Zt,setTimeout(()=>{n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,Pe,ke).joinAttempted}),m(this,Zt,void 0)},rO)),n(this,Pe,ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),n(this,Pe,ke).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,Pe,ke).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,Pe,ke).mediaJoinAttempted}}),n(this,Zt)&&(clearTimeout(n(this,Zt)),m(this,Zt,void 0)),n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,Pe,ke).mediaJoinAttempted}),n(this,Pe,ke).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),n(this,Ye).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED),n(this,Pe,ke).updateSocketConnectionState("failed")})}},qr=new WeakMap,Ee=new WeakMap,Pe=new WeakSet,ke=function(){return n(this,Ye).getValue("connectionHandler")},Zt=new WeakMap,Ye=new WeakMap,Pc=new WeakSet,zu=function(s){let t=kT.getSocketEdgeDomain(n(this,Ye).getValue("baseURI"));typeof ba(n(this,Ye),"socket_server_base")=="string"&&(t=ba(n(this,Ye),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>pd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},_c=new WeakSet,Yu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},_g);let Vc=kT;xl([y.trace("SocketService.connect")],Vc.prototype,"connect",1);xl([y.trace("SocketService.disconnect")],Vc.prototype,"disconnect",1);xl([y.trace("SocketService.sendMessagePromise")],Vc.prototype,"sendMessagePromise",1);xl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Vc.prototype,"sendMessagePromiseWithTimeout",1);class iO{constructor(t){u(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=Bb.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=pk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Zm.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Op.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return rk.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(L.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(L.createConnectedRooms,Gb.toBinary({payloads:t}));return Op.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(L.deleteConnectedRooms,tk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(L.movePeers,dk.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 nO=Object.defineProperty,aO=Object.getOwnPropertyDescriptor,oO=(s,t,e,r)=>{for(var i=r>1?void 0:r?aO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&nO(t,e,i),i},Ts;class AT extends Ut{constructor(e){const r=e.getValue("logger");super(r);u(this,"meetings",[]);u(this,"parentMeeting",null);g(this,Ts,void 0);m(this,Ts,e)}get supportsConnectedMeetings(){return n(this,Ts).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.
|
|
11
11
|
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await n(this,Ts).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,Ts).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,Ts).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,Ts).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Ts).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,Ts).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Ts=new WeakMap;oO([_t({maxInvocations:60,period:60})],AT.prototype,"getConnectedMeetings",1);var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,Dh=(s,t,e,r)=>{for(var i=r>1?void 0:r?dO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cO(t,e,i),i},le,Cg;const IT=(Cg=class{constructor(s){u(this,"connectedMeetings");g(this,le,void 0);m(this,le,s),this.connectedMeetings=new AT(s)}get telemetry(){return n(this,le).getValue("telemetry")}get logger(){return n(this,le).getValue("logger")}static init(s){const t=new IT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.transferPeer,this.handleTransferPeer.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.movedPeer,this.handleMovedPeer.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,le).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,le).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
12
12
|
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,le).getValue("self").videoEnabled,audio:n(this,le).getValue("self").audioEnabled};try{n(this,le).getValue("self").cleanupEvents(),await n(this,le).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,le).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await DT.init({...n(this,le).getValue("options"),cachedUserDetails:null,defaults:{...n(this,le).getValue("options").defaults,...e,mediaHandler:n(this,le).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,le).getValue("self");r.self.setName(n(this,le).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,le).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,le).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,le).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,le).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},le=new WeakMap,Cg);let Ul=IT;Dh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ul.prototype,"getConnectedMeetings",1);Dh([y.trace("ConnectedMeetingsController.setupEvents")],Ul.prototype,"setupEvents",1);Dh([y.trace("ConnectedMeetingsController.switchMeeting")],Ul.prototype,"switchMeeting",1);var lO=Object.defineProperty,uO=Object.getOwnPropertyDescriptor,$l=(s,t,e,r)=>{for(var i=r>1?void 0:r?uO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lO(t,e,i),i};const mn=class{constructor(s,t,e){u(this,"apiBase");u(this,"selfController");u(this,"pollController");u(this,"chatController");u(this,"metaController");u(this,"storesManager");u(this,"stageController");u(this,"pluginController");u(this,"internalsController");u(this,"recordingController");u(this,"livestreamController");u(this,"participantController");u(this,"connectedMeetingsController");u(this,"telemetry");u(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var N,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(hT(s),ye.isSupported()===!1)throw new b("Browser not supported","0010",c,!0);const d=fM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new QM(s);s.setValue("connectionHandler",l);const h=mn.createSocketService(s),p=h.connect(),f=d.getUserDetails(),T=d.getPlugins();let E,P="";try{await mn.setupFlagsmith(s)}catch(q){c.error("Failed to setup flagsmith",{error:q})}try{await p}catch(q){c.error("[Controller]: Failed to connect to socket server:",{error:q})}try{({meetingTitle:P}=await d.getRoomNodeData()),E=await f,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(q){c.error("Failed to get room metadata",{error:q})}const _=bu.init(E.preset,!s.getValue("modules").theme);s.setValue("theme",_);const A=Mu.init(s,_.viewType,E.preset.permissions),M=mn.setupControllers(h,s,E,T,P,_,A);FM(_)&&((N=mn.createRoomNodeClient(s,h).initializeConnection(E.participant.name,i,!1,A))==null||N.catch(ee=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ee})})),y.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:x}=await M;return KC(),new mn(e,x,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=JC(i),d={entity:lu.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...ye.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const h=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?Yi({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${lu.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(h){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,a,o){var O,R,Ne;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),h=t.getValue("logger"),{viewType:p,mediaConstraints:{audio:f}}=a;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(O=f.enableHighBitrate)!=null?O:!1,enableStereo:(R=f.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",ye.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,P,_,A,M,x,N,$;const q=new ID(t,s),ee=new iO(s);t.setValue("connectedMeetingsSocketHandler",ee);const Qe=new Vl(t,s),is=new fr(t,s),ei=new LD(s),ns=new gT(t,s),k=new xD(t,s),v=new AD(s),C=await Zr.init(t,ns,d,o,a);t.setValue("selfController",C);const U=await mf.init(t,C.self,ns,q,i);if(c.participant&&(N=new Sr(t,C.self,ns)),(Ne=c.e2ee)!=null&&Ne.enabled&&c.e2ee.manager.init(h,t.getValue("peerSessionStore")),c.chat&&(E=await ts.init(t,is,C.self,N.participants)),c.internals&&(A=await yh.init(t)),c.livestream&&a.viewType===dr.Livestream&&t.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&(x=new Cf(t,C.self,v)),c.poll&&(T=await uf.init(t,C.self,Qe)),c.recording&&(M=new vf(t,C.self,ns)),c.stage&&(P=new ff(t,ei,ns,C.self,N.participants)),c.plugin){if(!N)throw new b("The plugin module cannot be initialized without the `participant` module","0102");const Ls=await r;_=await Mc.init(t,Ls,k,is,E==null?void 0:E.chat,C.self,N.participants,i)}if(c.connectedMeetings&&($=await Ul.init(t)),c.pip){const Ls=await uu._init(t,C.self);t.setValue("pip",Ls)}const be={storesManager:new q0(t,k),pollController:T,selfController:C,metaController:U,chatController:E,stageController:P,pluginController:_,recordingController:M,internalsController:A,livestreamController:x,participantController:N,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:be}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return uT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Vc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Lc=mn;$l([y.trace("Controller.init")],Lc,"init",1);$l([y.trace("setupFlagsmith")],Lc,"setupFlagsmith",1);$l([y.trace("Controller.createRoomNodeClient")],Lc,"createRoomNodeClient",1);$l([y.trace("Controller.createSocketService")],Lc,"createSocketService",1);class hO{constructor(){u(this,"battery");u(this,"logger");u(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)}});u(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});u(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});u(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 ng=new hO;function pO(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let a=ci.baseURI.prod;t&&(a=t);const o=`https://${Yi({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new b("Invalid auth token","0004")}}var jr,Wi,Ji,Cc,fl,MT;class gO{constructor(){g(this,fl);g(this,jr,new Audio);g(this,Wi,new MediaStream);g(this,Ji,new Map);g(this,Cc,void 0);n(this,jr).srcObject=n(this,Wi),n(this,jr).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Ji).has(e.id)||(n(this,Wi).addTrack(e),n(this,Ji).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,jr).setSinkId(t)}removeTrack(t){const e=n(this,Ji).get(t);e&&(n(this,Wi).removeTrack(e),n(this,Ji).delete(t))}async play(){return n(this,jr).srcObject=n(this,Wi),n(this,jr).play().catch(t=>{V(this,fl,MT).call(this,t)})}onError(t){m(this,Cc,t)}}jr=new WeakMap,Wi=new WeakMap,Ji=new WeakMap,Cc=new WeakMap,fl=new WeakSet,MT=function(t){var e;(e=n(this,Cc))==null||e.call(this,t)};var Ki;class mO extends gO{constructor(){super();g(this,Ki,void 0);m(this,Ki,new Map)}addParticipantTrack(e,r){n(this,Ki).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Ki).get(e);r&&this.removeTrack(r),n(this,Ki).delete(e)}}Ki=new WeakMap;var fO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,Fl=(s,t,e,r)=>{for(var i=r>1?void 0:r?TO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fO(t,e,i),i},Be,zi,wg;let zr=(wg=class{constructor(t,e){g(this,Be,void 0);g(this,zi,void 0);m(this,zi,t),m(this,Be,e)}get peerId(){return n(this,zi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:lr.v4(),a=or.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Df(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,T,E,P,_,A;ye.init();const e=(T=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?T:lr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=pO(r,i);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=zr.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");$T(l),ng.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(P=(E=t.modules)==null?void 0:E.tracing)!=null?P:!0),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(_=t.authToken)==null?void 0:_.slice(0,10)}...
|
|
13
|
-
${(A=t.authToken)==null?void 0:A.slice(-10)}`}});const h=await Lc.init(c),p=new zr(c,h);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=or.createContext(t,e),o={...xC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",UC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ys(e.cachedUserDetails)),a.setValue("sdkVersion","1.3.0
|
|
13
|
+
${(A=t.authToken)==null?void 0:A.slice(-10)}`}});const h=await Lc.init(c),p=new zr(c,h);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=or.createContext(t,e),o={...xC,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",UC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ys(e.cachedUserDetails)),a.setValue("sdkVersion","1.3.0"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new mO),a}async join(){const{selfController:t}=n(this,Be);return t.self.roomJoined?null:t.joinRoom()}async leave(t){ng.cleanup(),n(this,zi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Be);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,Be).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Be).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Be).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Be).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Be).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Be).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Be).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Be).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Be).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Be).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Be).stageController)==null?void 0:t.stage}get stores(){return n(this,Be).storesManager}get audio(){return n(this,zi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Be).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Be=new WeakMap,zi=new WeakMap,wg);Fl([at("0002"),Tr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1);Fl([at("0003")],zr.prototype,"leave",1);Fl([at("0001"),Tr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1);zr=Fl([at("0000")],zr);const DT=zr;module.exports=DT;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/realtimekit",
|
|
3
|
-
"version": "1.3.0
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "A real-time video and audio SDK for building custom, collaborative communication experiences.",
|
|
5
5
|
"main": "./dist/index.cjs.js",
|
|
6
6
|
"module": "./dist/index.es.js",
|
|
@@ -86,7 +86,8 @@
|
|
|
86
86
|
"worker-timers": "7.0.60"
|
|
87
87
|
},
|
|
88
88
|
"publishConfig": {
|
|
89
|
-
"
|
|
89
|
+
"access": "public",
|
|
90
|
+
"tag": "latest"
|
|
90
91
|
},
|
|
91
92
|
"devDependencies": {
|
|
92
93
|
"@types/events": "^3.0.0",
|