@cloudflare/realtimekit 1.2.1-staging.2 → 1.2.1-staging.3

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.
@@ -20,4 +20,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,Mr)},
20
20
  maxEnergy: ${a(this,hi)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||i<a(this,Mr))&&f(this,Mr,i),(!a(this,hi)||i>a(this,hi))&&f(this,hi,i),{energy:(i-a(this,Mr))/(a(this,hi)-a(this,Mr))*10||0,isVoice:r})},Mc=new WeakSet,Rp=function(t){return t<5},ou=new WeakSet,Hv=function(t=a(this,vn)){var r;if(!a(this,xs)||!t){a(this,Or).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xs)}`);return}const e={producerId:a(this,xs),energy:Math.round(t),silent:x(r=Oc,Mc,Rp).call(r,t)};f(this,eo,e.silent),this.reportRequest(e)},cu=new WeakSet,qv=function(t){const e=Math.log10(t);return Math.round(e)},m(Oo,Mc),m(Oo,cu);const qD=(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}},jD=(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 GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?WD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GD(t,e,i),i};const Yt=["video/VP9","video/VP8"],bS=(up=class{constructor(s,t){m(this,pi);m(this,du);m(this,lu);m(this,uu);m(this,xc);m(this,pu);m(this,gu);m(this,mu);m(this,ot);m(this,_n);m(this,fu);m(this,Su);m(this,vu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Dc,void 0);m(this,Nc,void 0);m(this,Et,void 0);m(this,j,void 0);m(this,to,void 0);m(this,Mt,void 0);m(this,Tn,void 0);m(this,yn,void 0);m(this,En,void 0);m(this,Vc,void 0);m(this,Ss,null);m(this,Nr,void 0);m(this,Lc,void 0);m(this,bn,void 0);m(this,wn,void 0);m(this,Ot,void 0);m(this,Ht,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,bn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,wn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Et,e),f(this,Tn,!1),f(this,j,new FD(s,e)),f(this,Mt,a(this,j).events),f(this,Nr,new Set),f(this,Ot,new Map),f(this,yn,!1),f(this,En,new Wh(s.getValue("logger"))),f(this,Ht,new Oo(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,Vc,Xu(async()=>{if(!a(this,pi,io).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Nc),a(this,Dc),!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,pi,io).mediaJoined}set mediaJoined(s){a(this,pi,io).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ot).clear(),a(this,Nr).clear(),f(this,Ss,null),a(this,En).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,En,new Wh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,pi,io).mediaJoinAttempted=!0,f(this,Tn,!0),e&&this.reset();try{return await a(this,En).push(()=>x(this,du,jv).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(R.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return a(this,Ss)?a(this,Ss):(f(this,Ss,(async()=>{try{await x(this,xc,kp).call(this,s,t,e,r)}catch(i){throw f(this,Ss,null),i}})()),a(this,Ss))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,yn,!1),a(this,pi,io).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,Et).sendMessagePromise(a(this,Mt).leaveRoom,DR.toBinary(s)).then(e=>{var r;(r=Ek.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g;const e=t==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,r=x(this,ot,Nt).call(this,e);if(r){const S=await r;if(a(this,j).producers.has(S)){const E=a(this,j).producers.get(S);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Yt.filter(S=>S!==t)),n=x(this,vu,Zv).call(this,s,i),o=xn(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(X.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=_1(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ot).delete(e)},u=a(this,j).createProducer(n,l);return x(this,_n,dd).call(this,e,u.then(S=>S.id)),u.then(S=>S.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Yt.filter(i=>{var n,o;return((o=(n=a(this,to).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,wn).get(i).size>0});return e.length===0&&e.push(Yt[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:Te.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);x(this,_n,dd).call(this,fe.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:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),x(this,_n,dd).call(this,fe.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 Ut("track undefined");const t=x(this,ot,Nt).call(this,fe.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,Ht)&&(a(this,Ht).audioTrack=s,a(this,Ht).producerId=n,a(this,Ht).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=x(this,Su,Xv).call(this,s),r=()=>{a(this,Ot).delete(fe.MIC)},i=a(this,j).createProducer(e,r);x(this,_n,dd).call(this,fe.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,Ht)&&(a(this,Ht).audioTrack=n.track,a(this,Ht).producerId=n.id,a(this,Ht).start())})}catch(t){throw new C(t)}}async pauseMic(){var r;const s=await x(this,ot,Nt).call(this,fe.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,Ht))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async pauseWebcam(){const s=await x(this,ot,Nt).call(this,fe.WEBCAM),t=await x(this,ot,Nt).call(this,fe.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,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await x(this,ot,Nt).call(this,fe.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(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async resumeWebcam(s=fe.WEBCAM){const t=await x(this,ot,Nt).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(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,e=await x(this,ot,Nt).call(this,t);x(this,fu,Qv).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await x(this,ot,Nt).call(this,fe.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,Ht))==null||t.stop(),a(this,Ot).delete(fe.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await x(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO),t=await x(this,ot,Nt).call(this,fe.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Nr).clear(),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await x(this,ot,Nt).call(this,fe.WEBCAM),r=await x(this,ot,Nt).call(this,fe.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,ot,Nt).call(this,fe.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,Et).sendMessagePromise(a(this,Mt).globalPinPeer,JR.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,Nr).add(s.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,Et).on(a(this,Mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Qk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ws.AUDIO?"audio/opus":"video/VP8"),i.kind===Ws.VIDEO&&!i.screenShare&&((e=(t=a(this,to).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Yt[0]))>=0&&a(this,bn).get(Yt[0]).has(r)&&i.mimeType!==Yt[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:{...i,kind:i.kind===Ws.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Et).on(a(this,Mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=lf.fromBinary(s);if(o)return;const c=r===Ws.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(lf.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,Et).on(a(this,Mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=uh.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Nr).delete(t),a(this,j).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,Et).on(a(this,Mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=eI.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,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(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,Et).on(a(this,Mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Tn)&&!a(this,yn)||(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,j).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,j).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<=Yt.length;o+=1){const c=Yt[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===Yt.length-1){a(this,wn).get(c).add(s);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[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===Yt.length-1){a(this,bn).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,bn).forEach(t=>t.delete(s)),a(this,wn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Yt[0])&&this.disableWebcam(e)}))}},Dc=new WeakMap,Nc=new WeakMap,Et=new WeakMap,j=new WeakMap,to=new WeakMap,Mt=new WeakMap,Tn=new WeakMap,yn=new WeakMap,En=new WeakMap,Vc=new WeakMap,Ss=new WeakMap,Nr=new WeakMap,Lc=new WeakMap,bn=new WeakMap,wn=new WeakMap,Ot=new WeakMap,Ht=new WeakMap,pi=new WeakSet,io=function(){return this.context.getValue("connectionHandler")},du=new WeakSet,jv=async function(s,t,e,r){f(this,Nc,s);try{return a(this,Ss)?await a(this,Ss):await x(this,xc,kp).call(this,s,t,e,r),x(this,uu,Wv).call(this,t),{roomJoined:await x(this,lu,Gv).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,Ss,null)}},lu=new WeakSet,Gv=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Dc,s.roomUuid),f(this,yn,!0),f(this,Tn,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},uu=new WeakSet,Wv=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...Te.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)},xc=new WeakSet,kp=async function(s,t,e,r){var i,n;try{(n=a(this,Lc))!=null||f(this,Lc,x(i=bS,hu,Jv).call(i));const o=x(this,pu,Kv).call(this);await x(this,gu,zv).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,mu,Yv).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},hu=new WeakSet,Jv=function(){const{ipInfo:s}=pt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},pu=new WeakSet,Kv=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=yD(s);return f(this,to,t),t},gu=new WeakSet,zv=async function(s,t,e,r){await mS(async(i,n)=>{if(!a(this,Et).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,Lc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},mu=new WeakSet,Yv=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(jD(!1))),s.canProduceAudio===H.Allowed){const r=qD(!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})}},ot=new WeakSet,Nt=function(s){return a(this,Ot).get(s)},_n=new WeakSet,dd=function(s,t){return a(this,Ot).set(s,t)},fu=new WeakSet,Qv=function(s){return a(this,Ot).delete(s)},Su=new WeakSet,Xv=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},vu=new WeakSet,Zv=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(up,hu),up);let re=bS;ce([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1),ce([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function wS(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 _S(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 JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Fi=(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};const PS=(pv=class{constructor(s,t,e,r){m(this,Dt);p(this,"self");p(this,"authToken");m(this,Pn,void 0);p(this,"viewType");m(this,Us,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,Pn,i),f(this,Us,e),t.config.viewType!==Vt.Chat&&this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await tt.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mm(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 PS(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,Dt,rs).shareMic(s),this.self.audioEnabled||a(this,Dt,rs).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,Dt,rs).shareWebcam(t);d&&d.id!==t.id&&a(this,ee).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await a(this,Dt,rs).shareWebcam(d),this.self.videoEnabled||a(this,Dt,rs).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Dt,rs))==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,ee).getValue("callstats").callEnded(),a(this,Dt,rs).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,ee).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,ee).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=vi()),a(this,Pn).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),pt().setHeader("tracing-id",t),nr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Us).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Us).on(Yd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),a(this,Us).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Us).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Us).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).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,ee).getValue("peerSessionStore").on(R.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Us).joinRoom(this.self);a(this,Us).socket.flush();const e=Oh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,ee).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,ee).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).notify("stageStatus");try{(e=a(this,Pn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}_S(a(this,ee)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===Vt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}wS(a(this,ee),{socket:a(this,Pn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u}=(o=await((n=a(this,Dt,rs))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new C("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Vt.Webinar)&&a(this,Dt,rs)&&(a(this,Dt,rs).mediaJoined&&s!=="disconnected"&&await a(this,Dt,rs).leaveRoom(),!(s==="stageLeft"&&t===Vt.Livestream)&&(a(this,Dt,rs).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()}},Pn=new WeakMap,Us=new WeakMap,ee=new WeakMap,Dt=new WeakSet,rs=function(){return a(this,ee).getValue("roomNodeClient")},pv);let jr=PS;Fi([y.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Fi([y.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Fi([y.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Fi([y.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Fi([y.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Fi([y.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Fi([y.trace("SelfController.init")],jr,"init",1);class zD{constructor(t){m(this,Uc,void 0);f(this,Uc,t)}on(t,e){let r;t===U.roomPeerCount?r=pf.fromBinary.bind(pf):r=Af.fromBinary.bind(Af),a(this,Uc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Uc=new WeakMap;class YD{constructor(t,e){m(this,Fc,void 0);m(this,Bc,void 0);f(this,Fc,e),f(this,Bc,t)}get logger(){return a(this,Bc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=hh.fromBinary.bind(hh),i=hh.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Fc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Fc=new WeakMap,Bc=new WeakMap;var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?XD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QD(t,e,i),i};class gl{constructor(t,e){m(this,Vr,void 0);m(this,so,void 0);f(this,Vr,e),f(this,so,t)}get logger(){return a(this,so).getValue("logger")}get telemetry(){return a(this,so).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(lr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(lr.createPoll,HM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(lr.votePoll,jM.toBinary(r))}on(t,e){let r,i;switch(t){case lr.updatePoll:case lr.createPoll:case lr.votePoll:{r=Ph.fromBinary.bind(Ph),i=Ph.create();break}}a(this,Vr).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,Vr).removeListeners(t)}}Vr=new WeakMap,so=new WeakMap,ep([y.trace("PollSocketHandler.getPolls")],gl.prototype,"getPolls",1),ep([y.trace("PollSocketHandler.createPoll")],gl.prototype,"createPoll",1),ep([y.trace("PollSocketHandler.votePoll")],gl.prototype,"votePoll",1);var ZD=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,tN=(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&&ZD(t,e,i),i};class CS{constructor(t,e){p(this,"socket");m(this,ts,void 0);f(this,ts,t),this.socket=e,this.handleSocketEvents(),a(this,ts).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ts).getValue("telemetry")}get logger(){return a(this,ts).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,II.toBinary(e));try{const{peer:n}=Fn.fromBinary((await r).payload);a(this,ts).getValue("connectionHandler").socketJoined=!0,a(this,ts).getValue("peerSessionStore").emit(R.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,ts).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,ts).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return pA.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,TI.toBinary(n));i=mh.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=mh.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=mh.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,ff.toBinary({peerId:t}));e=Fn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=mf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=mf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=bf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=bf.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,Eo.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,Eo.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,Eo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,MI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,yf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,nf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,TA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,EA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Yd.updateUserPreset,YA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Eo.fromBinary(t);a(this,ts).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=Eo.fromBinary(t);a(this,ts).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=Fn.fromBinary.bind(Fn),i=Fn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?Ef.fromBinary(n,o):{requests:[]},i=Ef.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Nf.fromBinary.bind(Nf);break}case Yd.updateUserPreset:{r=_f.fromBinary.bind(_f);break}case ws.peerJoinedBroadcast:case $r.peerJoinedBroadcast:{r=cf.fromBinary.bind(cf);break}case ws.selfJoinComplete:case $r.selfJoinComplete:{r=lh.fromBinary.bind(lh);break}case ws.globalPeerPinBroadcast:case $r.globalPeerPinBroadcast:{r=uf.fromBinary.bind(uf);break}case ws.selectedPeer:case $r.selectedPeer:{r=dh.fromBinary.bind(dh);break}case ws.selectedPeerDiff:case $r.selectedPeerDiff:{r=of.fromBinary.bind(of);break}case ws.leaveRoom:case $r.leaveRoom:{r=uh.fromBinary.bind(uh);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(Yd.getUserPresets,qA.toBinary(e)),i=JA.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}}}ts=new WeakMap,tN([y.trace("RoomSocketHandler.joinRoom")],CS.prototype,"joinRoom",1);class sN{constructor(t){m(this,qt,void 0);f(this,qt,t)}async getStageRequests(){const{payload:t}=await a(this,qt).sendMessagePromise(U.getStageRequests);return t?_h.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,qt).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,qt).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,qt).sendMessage(U.grantStageAccess,OM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,qt).sendMessage(U.denyStageAccess,NM.toBinary(e))}joinStage(){return a(this,qt).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,qt).sendMessagePromise(U.leaveStage,Of.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,qt).sendMessagePromise(U.leaveStage,Of.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=Mf.fromBinary.bind(Mf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=_h.fromBinary.bind(_h);break}case U.peerStageStatusUpdate:{r=hf.fromBinary.bind(hf);break}}a(this,qt).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,qt).sendMessagePromise(U.getPeerInfo,ff.toBinary({peerId:t}));return Fn.fromBinary(e.payload)}}qt=new WeakMap;class rN{constructor(t,e){m(this,Qe,void 0);m(this,$c,void 0);f(this,Qe,e),f(this,$c,t)}get logger(){return a(this,$c).getValue("logger")}addPlugin(t,e){a(this,Qe).sendMessage(G.addPlugin,z0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Qe).sendMessage(G.removePlugin,Q0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Qe).sendMessagePromise(G.getPlugins);return t?yM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Qe).sendMessage(G.customPluginEventToRoom,oM.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(G.customPluginEventToPeers,dM.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Qe).sendMessage(G.enablePluginForRoom,Z0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.enablePluginForPeers,rM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Qe).sendMessage(G.disablePluginForRoom,tM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.disablePluginForPeers,nM.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(G.storeInsertKeys,Cf.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(G.storeGetKeys,pM.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(G.storeDeleteKeys,mM.toBinary(n),i)}storeDelete(t,e,r){a(this,Qe).sendMessage(G.storeDelete,SM.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(G.storeInsertKeys,Cf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=wh.fromBinary.bind(wh);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Rf.fromBinary.bind(Rf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=If.fromBinary.bind(If);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=kf.fromBinary.bind(kf);break}}a(this,Qe).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Qe=new WeakMap,$c=new WeakMap;var iN=Object.defineProperty,nN=(s,t,e)=>t in s?iN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,aN=(s,t,e)=>(nN(s,typeof t!="symbol"?t+"":t,e),e),tp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(tp(s,t,"read from private field"),e?e.call(s):t.get(s)),Ee=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>(tp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(tp(s,t,"access private method"),e),ml={},oN={get exports(){return ml},set exports(s){ml=s}},Kn=typeof Reflect=="object"?Reflect:null,RS=Kn&&typeof Kn.apply=="function"?Kn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},fl;Kn&&typeof Kn.ownKeys=="function"?fl=Kn.ownKeys:Object.getOwnPropertySymbols?fl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:fl=function(s){return Object.getOwnPropertyNames(s)};function cN(s){console&&console.warn&&console.warn(s)}var kS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}oN.exports=de,ml.once=hN,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var IS=10;function Sl(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 IS},set:function(s){if(typeof s!="number"||s<0||kS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");IS=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||kS(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 AS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return AS(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")RS(c,this,t);else for(var d=c.length,l=VS(c,d),e=0;e<d;++e)RS(l[e],this,t);return!0};function MS(s,t,e,r){var i,n,o;if(Sl(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=AS(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,cN(c)}return s}de.prototype.addListener=function(s,t){return MS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return MS(this,s,t,!0)};function dN(){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 OS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=dN.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return Sl(t),this.on(s,OS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return Sl(t),this.prependListener(s,OS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Sl(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():lN(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 DS(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?uN(i):VS(i,i.length)}de.prototype.listeners=function(s){return DS(this,s,!0)},de.prototype.rawListeners=function(s){return DS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):NS.call(s,t)},de.prototype.listenerCount=NS;function NS(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?fl(this._events):[]};function VS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function lN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function uN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function hN(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))}LS(s,t,n,{once:!0}),t!=="error"&&pN(s,i,{once:!0})})}function pN(s,t,e){typeof s.on=="function"&&LS(s,"error",t,e)}function LS(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 gN 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 xS=new gN;class US{static encode(t){return xS.toBinary(t)}static decode(t){return xS.fromBinary(new Uint8Array(t))}}function mN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class fN{constructor(t={}){aN(this,"opts"),Ee(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=mN(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 Bi,$i;class SN{constructor(t){Ee(this,Bi,void 0),Ee(this,$i,void 0),ie(this,Bi,console),ie(this,$i,t)}debug(...t){Wr[O(this,$i)]>Wr.debug||O(this,Bi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,$i)]>Wr.info||O(this,Bi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,$i)]>Wr.warn||O(this,Bi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,$i)]>Wr.error||O(this,Bi).error("[Sockrates]:",...t)}}Bi=new WeakMap,$i=new WeakMap;var FS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(FS||{});const vN="2",TN="3";var Ne,zn,Ce,Fe,Jr,st,gr,Kr,ks,Yn,mr,sp,BS,Do,vl,rp,$S,ip,HS,Tl,np,ap,qS,No,yl,Vo,El,bl,op,Qn,Lo,xo,wl;class yN{constructor(t,e){var g,S,E,w,_,b,F,B,N,$;Ee(this,sp),Ee(this,Do),Ee(this,rp),Ee(this,ip),Ee(this,Tl),Ee(this,ap),Ee(this,No),Ee(this,Vo),Ee(this,bl),Ee(this,Qn),Ee(this,xo),Ee(this,Ne,void 0),Ee(this,zn,void 0),Ee(this,Ce,void 0),Ee(this,Fe,void 0),Ee(this,Jr,void 0),Ee(this,st,void 0),Ee(this,gr,void 0),Ee(this,Kr,void 0),Ee(this,ks,void 0),Ee(this,Yn,void 0),Ee(this,mr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,zn,t),ie(this,Jr,[]),ie(this,st,new ml),ie(this,gr,!0),ie(this,ks,!1),ie(this,Ce,e!=null?e:{}),(g=(r=O(this,Ce)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,Ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=O(this,Ce)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=O(this,Ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=O(this,Ce)).debug)!=null||(c.debug=!0),(b=(d=O(this,Ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(F=(l=O(this,Ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=O(this,Ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(h=O(this,Ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Kr,{code:void 0,reason:void 0}),ie(this,Fe,($=O(this,Ce).logger)!=null?$:new SN(O(this,Ce).debug?"debug":"info")),ie(this,mr,new fN)}get readyState(){var t;return(t=O(this,Ne))==null?void 0:t.readyState}get url(){return O(this,zn)}updateURL(t){ie(this,zn,t),Pe(this,ap,qS).call(this)}get config(){return O(this,Ce)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,Ce).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,Fe).debug("Websocket was already connecting or connected.");return}if(O(this,gr)!==!1)return new Promise((e,r)=>{Pe(this,Qn,Lo).call(this),Pe(this,xo,wl).call(this);try{ie(this,Ne,new WebSocket(Pe(this,sp,BS).call(this,O(this,zn)))),O(this,Ne).binaryType="arraybuffer",O(this,Fe).debug("Connecting");const i=setTimeout(()=>{O(this,Fe).debug("Connection timeout. Closing socket"),ie(this,gr,!0),Pe(this,xo,wl).call(this),O(this,Ne).close(3001,"Connection Timeout"),O(this,Ce).autoReconnect&&!O(this,ks)&&(O(this,st).emit("reconnecting"),Pe(this,No,yl).call(this)),r(new Error("Connection timed out!"))},O(this,Ce).connectionTimeout);O(this,Ne).onopen=()=>{O(this,Fe).debug(`Ready State: ${FS[O(this,Ne).readyState]}`),i&&clearTimeout(i),Pe(this,bl,op).call(this),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("connected"),O(this,Ce).flushOnReconnect&&this.flush(),e()},O(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Fe).debug("Socket closed. Close event:",{event:n}),O(this,Fe).debug(`Connection closed code: ${o}`),O(this,Fe).debug(`Connection closed reason: ${c}`),O(this,ks)||Pe(this,Tl,np).call(this,o,c)}catch(o){Pe(this,Do,vl).call(this,o)}},O(this,Ne).onerror=n=>{Pe(this,Do,vl).call(this,n)},O(this,Ne).onmessage=n=>Pe(this,rp,$S).call(this,n)}catch(i){Pe(this,Do,vl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,Ce).queueOnDisconnect&&(!O(this,Ne)||O(this,Ne).readyState!==1))return O(this,Fe).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=US.encode(n);return Pe(this,Vo,El).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Vo,El).call(this,t)}receive(t,e){return O(this,st).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,st).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,st).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,st).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,st).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,gr,!1),Pe(this,Qn,Lo).call(this),this.removeAllListeners(),ie(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,zn=new WeakMap,Ce=new WeakMap,Fe=new WeakMap,Jr=new WeakMap,st=new WeakMap,gr=new WeakMap,Kr=new WeakMap,ks=new WeakMap,Yn=new WeakMap,mr=new WeakMap,sp=new WeakSet,BS=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)://.")},Do=new WeakSet,vl=function(s,t){O(this,Fe).error("Error:",{error:s}),O(this,st).emit("errored",{error:s}),t==null||t(s)},rp=new WeakSet,$S=function(s){if(Pe(this,bl,op).call(this),s.data===vN){O(this,Fe).debug("Received ping from server"),Pe(this,Vo,El).call(this,TN);return}const t=US.decode(s.data),{id:e,payload:r}=t;O(this,Fe).debug("Received message",{event:t.event,messageID:e}),O(this,st).emit(t.event.toString(),{id:e,payload:r})},ip=new WeakSet,HS=function(){return O(this,Ne).readyState===1},Tl=new WeakSet,np=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,st).emit("disconnected",{code:s,reason:t})},ap=new WeakSet,qS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,gr)&&O(this,Ce).autoReconnect&&!O(this,ks)&&(O(this,Fe).debug(`Triggering reconnection due to ${s}.`),O(this,st).emit("reconnecting"),Pe(this,No,yl).call(this))},No=new WeakSet,yl=async function(s=!0){if(s&&O(this,ks)){O(this,Fe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,ks)||O(this,mr).reset(),O(this,Ce).maxReconnectionAttempts!==null&&O(this,mr).getAttempts()>=O(this,Ce).maxReconnectionAttempts){O(this,st).emit("failed"),ie(this,ks,!1);return}ie(this,ks,!0),Pe(this,xo,wl).call(this),Pe(this,Qn,Lo).call(this);try{if(await O(this,mr).wait(),O(this,gr)===!1)return;if(O(this,Fe).debug(`Reconnection attempt ${O(this,mr).getAttempts()}`),O(this,st).emit("reconnectAttempt",{attempt:O(this,mr).getAttempts()}),await this.connect(),!Pe(this,ip,HS).call(this))throw Error("Reconnect Failed");ie(this,ks,!1),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("reconnected")}catch(t){O(this,Fe).debug("Failed to reconnect."),O(this,st).emit("reconnectFailure",{attempt:O(this,mr).getAttempts()}),Pe(this,No,yl).call(this,!1)}},Vo=new WeakSet,El=function(s){try{return O(this,Ne).send(s),!0}catch(t){return O(this,Fe).error(t.message),!1}},bl=new WeakSet,op=function(){this.config.disconnectOnPingTimeout&&(O(this,Fe).debug("Resetting ping timeout"),Pe(this,Qn,Lo).call(this),ie(this,Yn,setTimeout(()=>{var s;O(this,Fe).debug("Disconnecting the socket due to ping timeout"),ie(this,gr,!0);const t=3002,e="Ping timeout";(s=O(this,Ne))==null||s.close(t,e),Pe(this,Tl,np).call(this,t,e)},O(this,Ce).pingTimeout)))},Qn=new WeakSet,Lo=function(){O(this,Yn)&&(clearTimeout(O(this,Yn)),ie(this,Yn,void 0))},xo=new WeakSet,wl=function(){O(this,Ne)&&(O(this,Ne).onopen=void 0,O(this,Ne).onerror=void 0,O(this,Ne).onmessage=void 0,O(this,Ne).onclose=void 0)};var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,_l=(s,t,e,r)=>{for(var i=r>1?void 0:r?bN(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&&EN(t,e,i),i};const jS=65535,wN=3e3,GS=(gv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Oe);m(this,Hc);m(this,qc);m(this,gi,void 0);m(this,Me,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,vs,void 0);m(this,ct,void 0);var n;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,vs,void 0),f(this,ct,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,gi,x(this,Hc,Ip).call(this,t)),f(this,Me,new yN(a(this,gi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Oe,je).socketJoinAttempted}set joinAttempted(s){a(this,Oe,je).socketJoinAttempted=s}get telemetry(){return a(this,ct).getValue("telemetry")}get logger(){return a(this,ct).getValue("logger")}get peerId(){return a(this,ct).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,gi,x(this,Hc,Ip).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Me).updateURL(a(this,gi))}static getSocketEdgeDomain(s){return _i({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,gi)}async connect(){a(this,Oe,je).socketJoinAttempted=!0,await a(this,Me).connect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Oe,je).socketJoinAttempted=!1,a(this,Me).disconnect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Me).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ct).getValue("telemetry").injectContext(r),a(this,Me).send(s,e!=null?e:x(this,qc,Ap).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,w)=>{a(this,Me).removeListener(n,E),a(this,Me).removeListener(jS,w),a(this,Me).removeListener($r.errorResponse,w),a(this,Me).removeListener(ws.errorResponse,w)},l=r!=null?r:x(this,qc,Ap).call(this),u={};a(this,ct).getValue("telemetry").injectContext(u);const g=({id:E,payload:w})=>{if(l===E){let _;try{const b=uk.fromBinary(w);_=new Error(b.errorMessage)}catch(b){_=new Error("failed to parse error message",{cause:b});try{const F=hI.fromBinary(w);_=new Error(F.message)}catch(F){_=new Error("failed to parse error message",{cause:F})}}c(_),d(S,g)}},S=({id:E,payload:w})=>{l===E&&(o({id:E,payload:w}),d(S,g))};a(this,Me).on(n,S),a(this,Me).on(jS,g),a(this,Me).on($r.errorResponse,g),a(this,Me).on(ws.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Me).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Me).on(s,t)}onStateEvent(s,t){a(this,Me).on(s,t)}removeListener(s,t){a(this,Me).removeListener(s,t)}removeListeners(s){a(this,Me).removeListeners(s)}flush(){return a(this,Me).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,vs)&&(clearTimeout(a(this,vs)),f(this,vs,void 0)),a(this,Oe,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:y.location.country});const{recv:e,send:r}=(i=a(this,Oe,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Jn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Jn.CONNECTED?a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}):f(this,vs,setTimeout(()=>{a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}),f(this,vs,void 0)},wN)),a(this,Oe,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),a(this,Oe,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Oe,je).mediaJoinAttempted}}),a(this,vs)&&(clearTimeout(a(this,vs)),f(this,vs,void 0)),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Oe,je).mediaJoinAttempted}),a(this,Oe,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Oe,je).updateSocketConnectionState("failed")})}},gi=new WeakMap,Me=new WeakMap,Oe=new WeakSet,je=function(){return a(this,ct).getValue("connectionHandler")},vs=new WeakMap,ct=new WeakMap,Hc=new WeakSet,Ip=function(s){let t=GS.getSocketEdgeDomain(a(this,ct).getValue("baseURI"));typeof xn(a(this,ct),"socket_server_base")=="string"&&(t=xn(a(this,ct),"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=>Gd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},qc=new WeakSet,Ap=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},gv);let Uo=GS;_l([y.trace("SocketService.connect")],Uo.prototype,"connect",1),_l([y.trace("SocketService.disconnect")],Uo.prototype,"disconnect",1),_l([y.trace("SocketService.sendMessagePromise")],Uo.prototype,"sendMessagePromise",1),_l([y.trace("SocketService.sendMessagePromiseWithTimeout")],Uo.prototype,"sendMessagePromiseWithTimeout",1);class _N{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=FI.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=uA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Tf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return vf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return tA.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,qI.toBinary({payloads:t}));return vf.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,ZI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,oA.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 PN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,RN=(s,t,e,r)=>{for(var i=r>1?void 0:r?CN(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&&PN(t,e,i),i};class WS extends Gt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Fs,void 0);f(this,Fs,e)}get supportsConnectedMeetings(){return a(this,Fs).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.
21
21
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){return this.validateConnectedMeetingsAction(),await a(this,Fs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()}async createMeetings(e){return this.validateConnectedMeetingsAction(),(await a(this,Fs).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),await a(this,Fs).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))}async deleteMeetings(e){this.validateConnectedMeetingsAction();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());return await Promise.all(r),await a(this,Fs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction();const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success&&this.moveSuccessHandler(e,r,i),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction();const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success&&this.moveSuccessHandler(e,r,i.map(o=>o.id)),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})}}Fs=new WeakMap,RN([Lt({maxInvocations:60,period:60})],WS.prototype,"getConnectedMeetings",1);var kN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,cp=(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&&kN(t,e,i),i};const JS=(mv=class{constructor(s){p(this,"connectedMeetings");m(this,ve,void 0);f(this,ve,s),this.connectedMeetings=new WS(s)}get telemetry(){return a(this,ve).getValue("telemetry")}get logger(){return a(this,ve).getValue("logger")}static init(s){const t=new JS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){const t=a(this,ve).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return 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.
22
22
  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,ve).getValue("self").videoEnabled,audio:a(this,ve).getValue("self").audioEnabled};try{a(this,ve).getValue("self").cleanupEvents(),await a(this,ve).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,ve).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 zS.init({...a(this,ve).getValue("options"),cachedUserDetails:null,defaults:{...a(this,ve).getValue("options").defaults,...e,mediaHandler:a(this,ve).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,ve).getValue("self");r.self.setName(a(this,ve).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,ve).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,ve).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ve).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,ve).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})}},ve=new WeakMap,mv);let Pl=JS;cp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Pl.prototype,"getConnectedMeetings",1),cp([y.trace("ConnectedMeetingsController.setupEvents")],Pl.prototype,"setupEvents",1),cp([y.trace("ConnectedMeetingsController.switchMeeting")],Pl.prototype,"switchMeeting",1);var AN=Object.defineProperty,MN=Object.getOwnPropertyDescriptor,Cl=(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&&AN(t,e,i),i};const Xn=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 N,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(_S(s),Te.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=wO(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 n1(s);s.setValue("connectionHandler",l);const u=Xn.createSocketService(s),h=u.connect(),g=d.getUserDetails(),S=d.getPlugins();let E,w="";try{await Xn.setupFlagsmith(s)}catch(Y){c.error("Failed to setup flagsmith",{error:Y})}try{await h}catch(Y){c.error("[Controller]: Failed to connect to socket server:",{error:Y})}try{({meetingTitle:w}=await d.getRoomNodeData()),E=await g,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(Y){c.error("Failed to get room metadata",{error:Y})}const _=$h.init(E.preset,!s.getValue("modules").theme),b=qh.init(s,_.viewType,E.preset.permissions),F=Xn.setupControllers(u,s,E,S,w,_,b);KO(_)&&((N=Xn.createRoomNodeClient(s,u).initializeConnection(E.participant.name,i,!1,b))==null||N.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),y.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:B}=await F;return TC(),new Xn(e,B,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=vC(i),d={entity:th.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...Te.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?_i({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${th.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 k,Ke,fi;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:(k=g.enableHighBitrate)!=null?k:!1,enableStereo:(Ke=g.enableStereo)!=null?Ke:!1}},...l}),t.setValue("maxPreferredStreams",Te.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,E,w,_,b,F,B,N,$;const Y=new YD(t,s),ae=new _N(s);t.setValue("connectedMeetingsSocketHandler",ae);const bt=new gl(t,s),Bs=new as(t,s),An=new sN(s),$s=new CS(t,s),I=new rN(t,s),T=new zD(s),P=new Ii(t,s),L=await jr.init(t,$s,d,o,n);t.setValue("selfController",L);const we=await qf.init(t,L.self,$s,Y,i);if(c.participant&&(N=new pr(t,L.self,$s)),(fi=c.e2ee)!=null&&fi.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await Cs.init(t,Bs,P,L.self,N.participants)),c.internals&&(b=await Vh.init(t)),c.livestream&&n.viewType===Vt.Livestream&&t.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&(B=new lS(t,L.self,T)),n.viewType!==Vt.Chat){if(c.poll&&(S=await Ff.init(t,L.self,bt)),c.recording&&(F=new Kf(t,L.self,$s)),c.stage&&(w=new jf(t,An,$s,L.self,N.participants)),c.plugin){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Lr=await r;_=await wo.init(t,Lr,I,Bs,E==null?void 0:E.chat,L.self,N.participants,i)}if(c.connectedMeetings&&($=await Pl.init(t)),c.pip){const Lr=await sh._init(t,L.self);t.setValue("pip",Lr)}}const V={storesManager:new sD(t,I),pollController:S,selfController:L,metaController:we,chatController:E,stageController:w,pluginController:_,recordingController:F,internalsController:b,livestreamController:B,participantController:N,connectedMeetingsController:$};return{theme:n,permissions:o,controllers:V}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return wS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Uo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Fo=Xn;Cl([y.trace("Controller.init")],Fo,"init",1),Cl([y.trace("setupFlagsmith")],Fo,"setupFlagsmith",1),Cl([y.trace("Controller.createRoomNodeClient")],Fo,"createRoomNodeClient",1),Cl([y.trace("Controller.createSocketService")],Fo,"createSocketService",1);class ON{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 KS=new ON;function DN(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=Pi.baseURI.prod;t&&(n=t);const o=`https://${_i({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}class NN{constructor(){m(this,Tu);m(this,mi,new Audio);m(this,Cn,new MediaStream);m(this,Rn,new Map);m(this,jc,void 0);a(this,mi).srcObject=a(this,Cn),a(this,mi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Rn).has(e.id)||(a(this,Cn).addTrack(e),a(this,Rn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,mi).setSinkId(t)}removeTrack(t){const e=a(this,Rn).get(t);e&&(a(this,Cn).removeTrack(e),a(this,Rn).delete(t))}async play(){return a(this,mi).srcObject=a(this,Cn),a(this,mi).play().catch(t=>{x(this,Tu,eT).call(this,t)})}onError(t){f(this,jc,t)}}mi=new WeakMap,Cn=new WeakMap,Rn=new WeakMap,jc=new WeakMap,Tu=new WeakSet,eT=function(t){var e;(e=a(this,jc))==null||e.call(this,t)};class VN extends NN{constructor(){super();m(this,kn,void 0);f(this,kn,new Map)}addParticipantTrack(e,r){a(this,kn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,kn).get(e);r&&this.removeTrack(r),a(this,kn).delete(e)}}kn=new WeakMap;var LN=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,Rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?xN(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&&LN(t,e,i),i};let zr=(fv=class{constructor(t,e){m(this,Xe,void 0);m(this,In,void 0);f(this,In,t),f(this,Xe,e)}get peerId(){return a(this,In).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:vi(),n=nr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new pS(o);return c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var S,E,w,_,b,F,B;Te.init();const{mediaHandler:e}=(S=t.defaults)!=null?S:{},r=(e==null?void 0:e.peerId)||((w=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?w:vi()),{authToken:i,baseURI:n}=t,{meetingId:o,...c}=DN(i,n);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),u=d.getValue("logger");iT(u),KS.init(u),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(b=(_=t.modules)==null?void 0:_.tracing)!=null?b:!0),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(F=t.authToken)==null?void 0:F.slice(0,10)}...
23
- ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...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",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ps(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.1-staging.2"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){KS.cleanup(),a(this,In).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,In).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,In=new WeakMap,fv);Rl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),Rl([ut("0003")],zr.prototype,"leave",1),Rl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=Rl([ut("0000")],zr);const zS=zr;return zS}();
23
+ ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...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",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Ps(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.1-staging.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){KS.cleanup(),a(this,In).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,In).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,In=new WeakMap,fv);Rl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),Rl([ut("0003")],zr.prototype,"leave",1),Rl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=Rl([ut("0000")],zr);const zS=zr;return zS}();
@@ -1,5 +1,5 @@
1
1
  Name: @cloudflare/realtimekit
2
- Version: 1.2.1-staging.1
2
+ Version: 1.2.1-staging.2
3
3
  License: Apache-2.0
4
4
  Private: false
5
5
  Description: A real-time video and audio SDK for building custom, collaborative communication experiences.
package/dist/index.cjs.js CHANGED
@@ -12,4 +12,4 @@ ${s}`}const Fa={maxInvocations:5,period:1};function Mt(s,t){return function(e,r,
12
12
  maxEnergy: ${n(this,Kr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,cr)||i<n(this,cr))&&f(this,cr,i),(!n(this,Kr)||i>n(this,Kr))&&f(this,Kr,i),{energy:(i-n(this,cr))/(n(this,Kr)-n(this,cr))*10||0,isVoice:r})},Pc=new WeakSet,th=function(t){return t<5},gl=new WeakSet,vT=function(t=n(this,Gi)){var r;if(!n(this,vs)||!t){n(this,dr).getValue("flagsmith").hasFeature(ee.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,vs)}`);return}const e={producerId:n(this,vs),energy:Math.round(t),silent:x(r=wo,Pc,th).call(r,t)};f(this,Aa,e.silent),this.reportRequest(e)},ml=new WeakSet,ET=function(t){const e=Math.log10(t);return Math.round(e)},m(mo,Pc),m(mo,ml);const nO=(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=()=>u(exports,null,function*(){try{const T=new Float32Array(a*o),y=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:a,numberOfChannels:o,timestamp:c,data:T});c+=a/i*1e6,yield r.ready,yield r.write(y)}catch(T){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 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}},aO=(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 oO=Object.defineProperty,cO=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?cO(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&&oO(t,e,i),i};const Ot=["video/VP9","video/VP8"];var Cc,wc,ct,W,Ma,yt,Wi,Ji,Ki,Rc,rs,ur,bc,zi,Yi,St,bt,zr,vn,fl,PT,Tl,CT,yl,wT,kc,sh,Sl,gu,RT,vl,bT,El,kT,_l,IT,Ze,pt,Qi,fo,Pl,AT,Cl,MT,wl,DT;const _T=(gu=class{constructor(s,t){m(this,zr);m(this,fl);m(this,Tl);m(this,yl);m(this,kc);m(this,vl);m(this,El);m(this,_l);m(this,Ze);m(this,Qi);m(this,Pl);m(this,Cl);m(this,wl);h(this,"context");h(this,"authToken");h(this,"e2ee");m(this,Cc,void 0);m(this,wc,void 0);m(this,ct,void 0);m(this,W,void 0);m(this,Ma,void 0);m(this,yt,void 0);m(this,Wi,void 0);m(this,Ji,void 0);m(this,Ki,void 0);m(this,Rc,void 0);m(this,rs,null);m(this,ur,void 0);m(this,bc,void 0);m(this,zi,void 0);m(this,Yi,void 0);m(this,St,void 0);m(this,bt,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,zi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Yi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ct,e),f(this,Wi,!1),f(this,W,new tO(s,e)),f(this,yt,n(this,W).events),f(this,ur,new Set),f(this,St,new Map),f(this,Ji,!1),f(this,Ki,new Ju(s.getValue("logger"))),f(this,bt,new mo(this.context,n(this,W).socketHandler.audioActivity.bind(n(this,W).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Rc,kh(()=>u(this,null,function*(){if(!n(this,zr,vn).mediaJoinAttempted)return;const{roomJoined:a}=yield this.joinRoom(n(this,wc),n(this,Cc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(k.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,zr,vn).mediaJoined}set mediaJoined(s){n(this,zr,vn).mediaJoined=s}reset(){n(this,W).closeAllProducers(),n(this,W).closeAllConsumers(),n(this,St).clear(),n(this,ur).clear(),f(this,rs,null),n(this,Ki).stop(),n(this,W).stopAllTransports(),n(this,W).reset(),f(this,Ki,new Ju)}joinRoom(a,o){return u(this,arguments,function*(s,t,e=!1,r=!1,i={}){n(this,zr,vn).mediaJoinAttempted=!0,f(this,Wi,!0),e&&this.reset();try{return yield n(this,Ki).push(()=>x(this,fl,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(k.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(i,a){return u(this,arguments,function*(s,t,e=!1,r={}){return n(this,rs)?n(this,rs):(f(this,rs,(()=>u(this,null,function*(){try{yield x(this,kc,sh).call(this,s,t,e,r)}catch(o){throw f(this,rs,null),o}}))()),n(this,rs))})}getConsumers(){return n(this,W).consumers}getProducers(){return n(this,W).producers}leaveRoom(){return u(this,null,function*(){n(this,W).stopAllTransports(),f(this,Ji,!1),n(this,zr,vn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,ct).sendMessagePromise(n(this,yt).leaveRoom,cR.toBinary(s)).then(e=>{var r;(r=YR.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():n(this,W).createConsumers(s)})}closeConsumers(s){return u(this,null,function*(){if(!s.length)return;const t=s.reduce((e,r)=>{const i=n(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 n(this,W).closeConsumers(t)})}_shareWebcam(s,t){return u(this,null,function*(){var g,T;const e=t==="video/VP9"?he.WEBCAM:he.WEBCAM_BACKUP,r=x(this,Ze,pt).call(this,e);if(r){const y=yield r;if(n(this,W).producers.has(y)){const _=n(this,W).producers.get(y);if(!_.closed)return yield _.replaceTrack({track:s}),yield this.resumeWebcam(e),s;yield this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Ot.filter(y=>y!==t)),a=x(this,wl,DT).call(this,s,i),o=La(this.context,"disableSimulcast"),c=(T=(g=this.context)==null?void 0:g.getValue("overrides"))==null?void 0:T.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(ee.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=J0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(ee.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(ee.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,St).delete(e)},p=n(this,W).createProducer(a,l);return x(this,Qi,fo).call(this,e,p.then(y=>y.id)),p.then(y=>y.track)})}shareWebcam(s){return u(this,null,function*(){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(ee.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=Ot.filter(i=>{var a,o;return((o=(a=n(this,Ma).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,Yi).get(i).size>0});return e.length===0&&e.push(Ot[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:ve.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,St).delete(he.SCREENSHARE_VIDEO),n(this,St).delete(he.SCREENSHARE_AUDIO)},a=n(this,W).createProducer(r,i);x(this,Qi,fo).call(this,he.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:ve.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,W).createProducer(c,d),x(this,Qi,fo).call(this,he.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([a,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(s){return u(this,null,function*(){try{if(s===void 0)throw new It("track undefined");const t=x(this,Ze,pt).call(this,he.MIC);if(t){const a=yield t;if(n(this,W).producers.has(a)){const o=n(this,W).producers.get(a);if(!o.closed){yield o.replaceTrack({track:s}),yield this.resumeMic(),n(this,bt)&&(n(this,bt).audioTrack=s,n(this,bt).producerId=a,n(this,bt).start());return}yield n(this,W).closeProducer(a,{stopTrack:!1})}yield this.shareMic(s);return}const e=x(this,Cl,MT).call(this,s),r=()=>{n(this,St).delete(he.MIC)},i=n(this,W).createProducer(e,r);x(this,Qi,fo).call(this,he.MIC,i.then(a=>a.id)),yield i.then(a=>{n(this,bt)&&(n(this,bt).audioTrack=a.track,n(this,bt).producerId=a.id,n(this,bt).start())})}catch(t){throw new b(t)}})}pauseMic(){return u(this,null,function*(){var r;const s=yield x(this,Ze,pt).call(this,he.MIC),t=n(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=n(this,bt))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,ct).sendMessage(n(this,yt).toggleProducer,Qc.toBinary(e))})}pauseWebcam(){return u(this,null,function*(){const s=yield x(this,Ze,pt).call(this,he.WEBCAM),t=yield x(this,Ze,pt).call(this,he.WEBCAM_BACKUP),e=n(this,W).producers.get(s),r=n(this,W).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,ct).sendMessage(n(this,yt).toggleProducer,Qc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))})}resumeMic(){return u(this,null,function*(){const s=yield x(this,Ze,pt).call(this,he.MIC),t=n(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(k.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,ct).sendMessage(n(this,yt).toggleProducer,Qc.toBinary(e))})}resumeWebcam(){return u(this,arguments,function*(s=he.WEBCAM){const t=yield x(this,Ze,pt).call(this,s),e=n(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(k.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,ct).sendMessage(n(this,yt).toggleProducer,Qc.toBinary(r))})}disableWebcam(s){return u(this,null,function*(){const t=s==="video/VP9"?he.WEBCAM:he.WEBCAM_BACKUP,e=yield x(this,Ze,pt).call(this,t);x(this,Pl,AT).call(this,t),e&&(yield n(this,W).closeProducer(e))})}disableMic(){return u(this,null,function*(){var t;const s=yield x(this,Ze,pt).call(this,he.MIC);s&&(yield n(this,W).closeProducer(s)),(t=n(this,bt))==null||t.stop(),n(this,St).delete(he.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=yield x(this,Ze,pt).call(this,he.SCREENSHARE_VIDEO),t=yield x(this,Ze,pt).call(this,he.SCREENSHARE_AUDIO);s&&(yield n(this,W).closeProducer(s)),t&&(yield n(this,W).closeProducer(t)),n(this,ur).clear(),n(this,St).delete(he.SCREENSHARE_VIDEO),n(this,St).delete(he.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}resetVideoProducers(s,t){return u(this,null,function*(){if(s){const e=yield x(this,Ze,pt).call(this,he.WEBCAM),r=yield x(this,Ze,pt).call(this,he.WEBCAM_BACKUP);yield n(this,W).closeProducer(e,{stopTrack:!1}),yield n(this,W).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=yield x(this,Ze,pt).call(this,he.SCREENSHARE_VIDEO);yield n(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 n(this,W).socketHandler.changeDisplayName(e)))throw new Error("failed to change display name!")})}kick(s){const t={peerIds:[s]};n(this,W).socketHandler.kickPeer(t)}kickAll(){n(this,W).socketHandler.kickAll()}muteAll(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(s){return u(this,null,function*(){if(!(yield n(this,W).socketHandler.hostControlForPeer(s,"audio")))throw new Error("failed to mute given participant")})}disableVideo(s){return u(this,null,function*(){if(!(yield n(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 n(this,ct).sendMessagePromise(n(this,yt).globalPinPeer,_R.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}})}validateScreenShare(s){return this.peerId===s.peerId&&n(this,W).producers.get(s.producerId)&&n(this,ur).add(s.consumerPeerId),n(this,ur).size}switchConsumersToLayer(s,t){return u(this,null,function*(){const e=s.map(r=>this.getConsumers().get(r));n(this,W).switchConsumersToLayer(e,t)})}handleSocketEvents(){return u(this,null,function*(){n(this,ct).on(n(this,yt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Rb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Fs.AUDIO?"audio/opus":"video/VP8"),i.kind===Fs.VIDEO&&!i.screenShare&&((e=(t=n(this,Ma).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===Ot[0]))>=0&&n(this,zi).get(Ot[0]).has(r)&&i.mimeType!==Ot[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(k.NEW_PRODUCER,{peerId:r,producer:H(D({},i),{kind:i.kind===Fs.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,ct).on(n(this,yt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=Jp.fromBinary(s);if(o)return;const c=r===Fs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(Jp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?k.MUTE_SELF:k.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(k.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(k.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,ct).on(n(this,yt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=Ru.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,ur).delete(t),n(this,W).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(k.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,ct).on(n(this,yt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=Ib.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(k.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=n(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}`),n(this,W).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),n(this,W).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(k.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,ct).on(n(this,yt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Wi)&&!n(this,Ji)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),n(this,Rc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=n(this,W).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(k.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,W).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(k.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<=Ot.length;o+=1){const c=Ot[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===Ot.length-1){n(this,Yi).get(c).add(s);break}}for(let o=0;o<=Ot.length;o+=1){const c=Ot[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===Ot.length-1){n(this,zi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(ee.FORCE_VIDEO_CODEC)||(n(this,zi).forEach(t=>t.delete(s)),n(this,Yi).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Ot[0])&&this.disableWebcam(e)}))}},Cc=new WeakMap,wc=new WeakMap,ct=new WeakMap,W=new WeakMap,Ma=new WeakMap,yt=new WeakMap,Wi=new WeakMap,Ji=new WeakMap,Ki=new WeakMap,Rc=new WeakMap,rs=new WeakMap,ur=new WeakMap,bc=new WeakMap,zi=new WeakMap,Yi=new WeakMap,St=new WeakMap,bt=new WeakMap,zr=new WeakSet,vn=function(){return this.context.getValue("connectionHandler")},fl=new WeakSet,PT=function(s,t,e,r){return u(this,null,function*(){f(this,wc,s);try{return n(this,rs)?yield n(this,rs):yield x(this,kc,sh).call(this,s,t,e,r),x(this,yl,wT).call(this,t),{roomJoined:yield x(this,Tl,CT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,rs,null)}})},Tl=new WeakSet,CT=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:s}=yield n(this,W).socketHandler.notifySelfJoinComplete();return f(this,Cc,s.roomUuid),f(this,Ji,!0),f(this,Wi,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}})},yl=new WeakSet,wT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:H(D({},ve.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},kc=new WeakSet,sh=function(s,t,e,r){return u(this,null,function*(){var i,a;try{(a=n(this,bc))!=null||f(this,bc,x(i=_T,Sl,RT).call(i));const o=x(this,vl,bT).call(this);yield x(this,El,kT).call(this,s,t,e,o),yield n(this,W).setupTransports({send:!0,recv:!0}),yield x(this,_l,IT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},Sl=new WeakSet,RT=function(){const{ipInfo:s}=dt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},vl=new WeakSet,bT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(ee.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=qD(s);return f(this,Ma,t),t},El=new WeakSet,kT=function(s,t,e,r){return u(this,null,function*(){yield tT((i,a)=>u(this,null,function*(){if(!n(this,ct).isConnected){a(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{yield n(this,W).socketHandler.joinRoom(t,s,r,e,n(this,bc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})})},_l=new WeakSet,IT=function(s){return u(this,null,function*(){if(!(!this.context.getValue("flagsmith").hasFeature(ee.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===j.Allowed&&e.push(this.shareWebcam(aO(!1))),s.canProduceAudio===j.Allowed){const r=nO(!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})}})},Ze=new WeakSet,pt=function(s){return n(this,St).get(s)},Qi=new WeakSet,fo=function(s,t){return n(this,St).set(s,t)},Pl=new WeakSet,AT=function(s){return n(this,St).delete(s)},Cl=new WeakSet,MT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},wl=new WeakSet,DT=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(gu,Sl),gu);let ae=_T;de([E.trace("MediaNodeClient.reset",{country:E.location.country})],ae.prototype,"reset",1);de([E.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1);de([E.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1);de([E.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1);de([E.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1);de([E.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1);de([E.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1);de([E.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1);de([E.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1);de([E.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1);de([E.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1);de([E.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1);de([E.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1);de([E.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1);de([E.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1);de([E.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1);de([E.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1);de([E.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1);de([E.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1);de([E.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1);de([E.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1);de([E.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1);de([E.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1);de([E.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1);de([E.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1);de([E.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1);de([E.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1);de([E.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function OT(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 NT(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 dO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,mn=(s,t,e,r)=>{for(var i=r>1?void 0:r?lO(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&&dO(t,e,i),i},Xi,Es,te,vt,Vt,jg;const VT=(jg=class{constructor(s,t,e,r){m(this,vt);h(this,"self");h(this,"authToken");m(this,Xi,void 0);h(this,"viewType");m(this,Es,void 0);m(this,te,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,f(this,te,s),this.viewType=r,this.authToken=a,f(this,Xi,i),f(this,Es,e),t.config.viewType!==At.Chat&&this.setupEvents()}get peerId(){return n(this,te).getValue("peerId")}get telemetry(){return n(this,te).getValue("telemetry")}get logger(){return n(this,te).getValue("logger")}get mediaJoined(){return n(this,te).getValue("connectionHandler").mediaJoined}static init(s,t,e,r,i){return u(this,null,function*(){const a=dt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=yield Ye.__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(ee.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(T=>T.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",g==null?void 0:g.filter(T=>T.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",g==null?void 0:g.filter(T=>T.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield s.getValue("callstats").initialize({peerId:o,engineName:ve.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:yield a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:uf(s),skipConnectivityChecks:p}),l.info("Callstats:: initialized")}catch(T){l.error("Callstats:: initialization failed",{error:T})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new VT(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:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===j.Allowed&&r)try{yield n(this,vt,Vt).shareMic(s),this.self.audioEnabled||n(this,vt,Vt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===j.Allowed&&i)try{const d=yield n(this,vt,Vt).shareWebcam(t);d&&d.id!==t.id&&n(this,te).getValue("flagsmith").hasFeature(ee.EXP_RESHARE)&&(yield n(this,vt,Vt).shareWebcam(d)),this.self.videoEnabled||n(this,vt,Vt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===j.Allowed&&a)try{yield(c=n(this,vt,Vt))==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*(){n(this,te).getValue("callstats").callEnded(),n(this,vt,Vt).reset(),s&&(yield this.joinRoom(s))})}setupEvents(){n(this,te).getValue("peerSessionStore").on(k.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,te).getValue("peerSessionStore").on(k.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,te).getValue("flagsmith").hasFeature(ee.REFRESH_ID_ON_DISCONNECTION)&&(t=Tr.v4()),n(this,Xi).updateURL(t),n(this,te).getValue("telemetry").resetPeerId(t),dt().setHeader("tracing-id",t),mr.remapContext(t,n(this,te)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,te).getValue("peerSessionStore").on(k.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Es).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Es).on(dd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,te).getValue("peerSessionStore").emit(k.UPDATE_PERMISSIONS,t.patch)})}),n(this,Es).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Es).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Es).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,te).getValue("peerSessionStore").onAsync(k.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,te).getValue("peerSessionStore").on(k.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,te).getValue("peerSessionStore").on(k.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),n(this,te).getValue("callstats").audioOff())})),n(this,te).getValue("peerSessionStore").on(k.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),n(this,te).getValue("callstats").videoOff())})),n(this,te).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,te).getValue("peerSessionStore").on(k.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(s=!1){return u(this,null,function*(){try{const{peer:t}=yield n(this,Es).joinRoom(this.self);n(this,Es).socket.flush();const e=Oh(t.stageType);if(n(this,te).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(s),n(this,te).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=n(this,te).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,te).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(s),n(this,te).notify("stageStatus");try{(e=n(this,Xi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}NT(n(this,te)),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 a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,te).getAllValues();try{if(e===At.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}OT(n(this,te),{socket:n(this,Xi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:p}=(o=yield(a=n(this,vt,Vt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}))!=null?o:{};if(!p)return;i==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new b("Error: could not join media room","0002")}})}leaveMediaRoom(s){return u(this,null,function*(){const t=n(this,te).getValue("viewType");s!=="connected-meeting"&&(yield this.cleanupSelf()),!(s==="stageLeft"&&t===At.Webinar)&&n(this,vt,Vt)&&(n(this,vt,Vt).mediaJoined&&s!=="disconnected"&&(yield n(this,vt,Vt).leaveRoom()),!(s==="stageLeft"&&t===At.Livestream)&&(n(this,vt,Vt).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()})}},Xi=new WeakMap,Es=new WeakMap,te=new WeakMap,vt=new WeakSet,Vt=function(){return n(this,te).getValue("roomNodeClient")},jg);let ii=VT;mn([E.trace("SelfController.resetSelf")],ii.prototype,"resetSelf",1);mn([E.trace("SelfController.setupEvents")],ii.prototype,"setupEvents",1);mn([E.trace("SelfController.joinRoom")],ii.prototype,"joinRoom",1);mn([E.trace("SelfController.leaveRoom")],ii.prototype,"leaveRoom",1);mn([E.trace("SelfController.joinMediaRoom")],ii.prototype,"joinMediaRoom",1);mn([E.trace("SelfController.leaveMediaRoom")],ii.prototype,"leaveMediaRoom",1);mn([E.trace("SelfController.init")],ii,"init",1);var Ic;class uO{constructor(t){m(this,Ic,void 0);f(this,Ic,t)}on(t,e){let r;t===U.roomPeerCount?r=Yp.fromBinary.bind(Yp):r=og.fromBinary.bind(og),n(this,Ic).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const a=r(i);e(a)})}}Ic=new WeakMap;var Ac,Mc;class hO{constructor(t,e){m(this,Ac,void 0);m(this,Mc,void 0);f(this,Ac,e),f(this,Mc,t)}get logger(){return n(this,Mc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=iu.fromBinary.bind(iu),i=iu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Ac).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Ac=new WeakMap,Mc=new WeakMap;var pO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,Gh=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(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&&pO(t,e,i),i},hr,Da;class Gl{constructor(t,e){m(this,hr,void 0);m(this,Da,void 0);f(this,hr,e),f(this,Da,t)}get logger(){return n(this,Da).getValue("logger")}get telemetry(){return n(this,Da).getValue("telemetry")}getPolls(){return n(this,hr).sendMessagePromise(Ws.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,hr).sendMessage(Ws.createPoll,TM.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,hr).sendMessage(Ws.votePoll,SM.toBinary(r))}on(t,e){let r,i;switch(t){case Ws.updatePoll:case Ws.createPoll:case Ws.votePoll:{r=lu.fromBinary.bind(lu),i=lu.create();break}}n(this,hr).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,hr).removeListeners(t)}}hr=new WeakMap,Da=new WeakMap;Gh([E.trace("PollSocketHandler.getPolls")],Gl.prototype,"getPolls",1);Gh([E.trace("PollSocketHandler.createPoll")],Gl.prototype,"createPoll",1);Gh([E.trace("PollSocketHandler.votePoll")],Gl.prototype,"votePoll",1);var mO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,TO=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(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&&mO(t,e,i),i},Ft;class LT{constructor(t,e){h(this,"socket");m(this,Ft,void 0);f(this,Ft,t),this.socket=e,this.handleSocketEvents(),n(this,Ft).setValue("roomSocketHandler",this)}get telemetry(){return n(this,Ft).getValue("telemetry")}get logger(){return n(this,Ft).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,ik.toBinary(e));try{const{peer:a}=Tn.fromBinary((yield r).payload);n(this,Ft).getValue("connectionHandler").socketJoined=!0,n(this,Ft).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return n(this,Ft).getValue("peerSessionStore").emit(k.ROOM_STATE,d),n(this,Ft).getValue("peerSessionStore").emit(k.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)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return Hk.fromBinary((yield this.socket.sendMessagePromise(U.getAllAddedParticipants)).payload).participants.map(i=>{var a=i,{id:e}=a,r=ro(a,["id"]);return H(D({},r),{userId:e})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let i;try{const a={seachQuery:t,limit:e,offset:r},o=yield this.socket.sendMessagePromise(U.getRoomPeersInfo,Kb.toBinary(a));i=nu.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(U.getRoomPeersInfo);t=nu.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=nu.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,Ef.toBinary({peerId:t}));e=Tn.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=tg.create();try{const e=yield this.socket.sendMessagePromise(U.getRoomStageState);t=tg.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,ao.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,ao.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,ao.toBinary(i))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,ak.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,yf.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,Kk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,Yk.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(dd.updateUserPreset,wI.toBinary(r))})}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=ao.fromBinary(t);n(this,Ft).getValue("peerSessionStore").emit(k.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=ao.fromBinary(t);n(this,Ft).getValue("peerSessionStore").emit(k.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=Tn.fromBinary.bind(Tn),i=Tn.create();break}case U.getWaitingRoomRequests:{r=(a,o)=>a?eg.fromBinary(a,o):{requests:[]},i=eg.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=lg.fromBinary.bind(lg);break}case dd.updateUserPreset:{r=sg.fromBinary.bind(sg);break}case Cs.peerJoinedBroadcast:case Mr.peerJoinedBroadcast:{r=Gp.fromBinary.bind(Gp);break}case Cs.selfJoinComplete:case Mr.selfJoinComplete:{r=wu.fromBinary.bind(wu);break}case Cs.globalPeerPinBroadcast:case Mr.globalPeerPinBroadcast:{r=Kp.fromBinary.bind(Kp);break}case Cs.selectedPeer:case Mr.selectedPeer:{r=Cu.fromBinary.bind(Cu);break}case Cs.selectedPeerDiff:case Mr.selectedPeerDiff:{r=jp.fromBinary.bind(jp);break}case Cs.leaveRoom:case Mr.leaveRoom:{r=Ru.fromBinary.bind(Ru);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(dd.getUserPresets,yI.toBinary(e)),i=_I.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}})}}Ft=new WeakMap;TO([E.trace("RoomSocketHandler.joinRoom")],LT.prototype,"joinRoom",1);var kt;class yO{constructor(t){m(this,kt,void 0);f(this,kt,t)}getStageRequests(){return u(this,null,function*(){const{payload:t}=yield n(this,kt).sendMessagePromise(U.getStageRequests);return t?du.fromBinary(t):{stageRequests:[]}})}requestAccess(){n(this,kt).sendMessage(U.requestStageAccess)}cancelRequestAccess(){n(this,kt).sendMessage(U.cancelStageRequest)}grantAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,kt).sendMessage(U.grantStageAccess,oM.toBinary(e))})}denyAccess(t){return u(this,null,function*(){const e={userIds:t};n(this,kt).sendMessage(U.denyStageAccess,dM.toBinary(e))})}joinStage(){return n(this,kt).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,kt).sendMessagePromise(U.leaveStage,dg.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,kt).sendMessagePromise(U.leaveStage,dg.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=cg.fromBinary.bind(cg);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=du.fromBinary.bind(du);break}case U.peerStageStatusUpdate:{r=zp.fromBinary.bind(zp);break}}n(this,kt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}getPeerInfo(t){return u(this,null,function*(){const e=yield n(this,kt).sendMessagePromise(U.getPeerInfo,Ef.toBinary({peerId:t}));return Tn.fromBinary(e.payload)})}}kt=new WeakMap;var je,Dc;class SO{constructor(t,e){m(this,je,void 0);m(this,Dc,void 0);f(this,je,e),f(this,Dc,t)}get logger(){return n(this,Dc).getValue("logger")}addPlugin(t,e){n(this,je).sendMessage(J.addPlugin,CA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,je).sendMessage(J.removePlugin,RA.toBinary({pluginId:t,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:t}=yield n(this,je).sendMessagePromise(J.getPlugins);return t?zA.fromBinary(t):{plugins:[]}})}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,je).sendMessage(J.customPluginEventToRoom,LA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,je).sendMessage(J.customPluginEventToPeers,UA.toBinary(a),i)}enablePluginForRoom(t,e){n(this,je).sendMessage(J.enablePluginForRoom,kA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,je).sendMessage(J.enablePluginForPeers,DA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,je).sendMessage(J.disablePluginForRoom,AA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,je).sendMessage(J.disablePluginForPeers,NA.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,je).sendMessage(J.storeInsertKeys,rg.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,je).sendMessage(J.storeGetKeys,HA.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,je).sendMessage(J.storeDeleteKeys,jA.toBinary(a),i)}storeDelete(t,e,r){n(this,je).sendMessage(J.storeDelete,WA.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,je).sendMessage(J.storeInsertKeys,rg.toBinary(i))}on(t,e){let r;switch(t){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{r=Au.fromBinary.bind(Au);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{r=ig.fromBinary.bind(ig);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{r=ag.fromBinary.bind(ag);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{r=ng.fromBinary.bind(ng);break}}n(this,je).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}je=new WeakMap,Dc=new WeakMap;var vO=Object.defineProperty,EO=(s,t,e)=>t in s?vO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,_O=(s,t,e)=>(EO(s,typeof t!="symbol"?t+"":t,e),e),Wh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>(Wh(s,t,"read from private field"),e?e.call(s):t.get(s)),Te=(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)=>(Wh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(Wh(s,t,"access private method"),e),Ad={},PO={get exports(){return Ad},set exports(s){Ad=s}},Mn=typeof Reflect=="object"?Reflect:null,Eg=Mn&&typeof Mn.apply=="function"?Mn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},fd;Mn&&typeof Mn.ownKeys=="function"?fd=Mn.ownKeys:Object.getOwnPropertySymbols?fd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:fd=function(s){return Object.getOwnPropertyNames(s)};function CO(s){console&&console.warn&&console.warn(s)}var xT=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}PO.exports=ce;Ad.once=kO;ce.EventEmitter=ce;ce.prototype._events=void 0;ce.prototype._eventsCount=0;ce.prototype._maxListeners=void 0;var _g=10;function Wl(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 _g},set:function(s){if(typeof s!="number"||s<0||xT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");_g=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||xT(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 UT(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return UT(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 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=qT(c,d),e=0;e<d;++e)Eg(l[e],this,t);return!0};function $T(s,t,e,r){var i,a,o;if(Wl(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=UT(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,CO(c)}return s}ce.prototype.addListener=function(s,t){return $T(this,s,t,!1)};ce.prototype.on=ce.prototype.addListener;ce.prototype.prependListener=function(s,t){return $T(this,s,t,!0)};function wO(){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 FT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=wO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return Wl(t),this.on(s,FT(this,s,t)),this};ce.prototype.prependOnceListener=function(s,t){return Wl(t),this.prependListener(s,FT(this,s,t)),this};ce.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Wl(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():RO(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),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 BT(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?bO(i):qT(i,i.length)}ce.prototype.listeners=function(s){return BT(this,s,!0)};ce.prototype.rawListeners=function(s){return BT(this,s,!1)};ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):HT.call(s,t)};ce.prototype.listenerCount=HT;function HT(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?fd(this._events):[]};function qT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function RO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function bO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function kO(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))}jT(s,t,a,{once:!0}),t!=="error"&&IO(s,i,{once:!0})})}function IO(s,t,e){typeof s.on=="function"&&jT(s,"error",t,e)}function jT(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 AO 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 Pg=new AO;class GT{static encode(t){return Pg.toBinary(t)}static decode(t){return Pg.fromBinary(new Uint8Array(t))}}function MO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Ir;class DO{constructor(t={}){_O(this,"opts"),Te(this,Ir,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ne(this,Ir,0)}wait(){return u(this,null,function*(){ne(this,Ir,M(this,Ir)+1);const t=MO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Zh(2,M(this,Ir))));yield new Promise(e=>{setTimeout(e,t)})})}getAttempts(){return M(this,Ir)}reset(){ne(this,Ir,0)}}Ir=new WeakMap;const Rr={debug:0,info:1,warn:2,error:3};var li,ui;class OO{constructor(t){Te(this,li,void 0),Te(this,ui,void 0),ne(this,li,console),ne(this,ui,t)}debug(...t){Rr[M(this,ui)]>Rr.debug||M(this,li).debug("[Sockrates]:",...t)}info(...t){Rr[M(this,ui)]>Rr.info||M(this,li).info("[Sockrates]:",...t)}warn(...t){Rr[M(this,ui)]>Rr.warn||M(this,li).warn("[Sockrates]:",...t)}error(...t){Rr[M(this,ui)]>Rr.error||M(this,li).error("[Sockrates]:",...t)}}li=new WeakMap,ui=new WeakMap;var WT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(WT||{});const NO="2",VO="3";var Ae,En,_e,Le,Ar,Ke,gr,Zr,Ps,_n,Gs,rh,JT,To,Td,ih,KT,nh,Cg,Md,ah,oh,zT,Eo,yd,_o,Dd,Od,ch,Dn,Po,Co,Nd;class LO{constructor(t,e){var T,y,_,P,C,w,$,F,N,B;Te(this,rh),Te(this,To),Te(this,ih),Te(this,nh),Te(this,Md),Te(this,oh),Te(this,Eo),Te(this,_o),Te(this,Od),Te(this,Dn),Te(this,Co),Te(this,Ae,void 0),Te(this,En,void 0),Te(this,_e,void 0),Te(this,Le,void 0),Te(this,Ar,void 0),Te(this,Ke,void 0),Te(this,gr,void 0),Te(this,Zr,void 0),Te(this,Ps,void 0),Te(this,_n,void 0),Te(this,Gs,void 0);var r,i,a,o,c,d,l,p,g;ne(this,En,t),ne(this,Ar,[]),ne(this,Ke,new Ad),ne(this,gr,!0),ne(this,Ps,!1),ne(this,_e,e!=null?e:{}),(T=(r=M(this,_e)).autoReconnect)!=null||(r.autoReconnect=!0),(y=(i=M(this,_e)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(_=(a=M(this,_e)).pingTimeout)!=null||(a.pingTimeout=3e4),(P=(o=M(this,_e)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(C=(c=M(this,_e)).debug)!=null||(c.debug=!0),(w=(d=M(this,_e)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),($=(l=M(this,_e)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(F=(p=M(this,_e)).queueOnDisconnect)!=null||(p.queueOnDisconnect=!1),(N=(g=M(this,_e)).flushOnReconnect)!=null||(g.flushOnReconnect=!1),ne(this,Zr,{code:void 0,reason:void 0}),ne(this,Le,(B=M(this,_e).logger)!=null?B:new OO(M(this,_e).debug?"debug":"info")),ne(this,Gs,new DO)}get readyState(){var t;return(t=M(this,Ae))==null?void 0:t.readyState}get url(){return M(this,En)}updateURL(t){ne(this,En,t),Pe(this,oh,zT).call(this)}get config(){return M(this,_e)}get sendQueue(){return M(this,Ar)}flush(){if(!M(this,_e).queueOnDisconnect)return!1;const t=[];return M(this,Ar).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ne(this,Ar,t),M(this,Ar)}connect(t=!1){return u(this,null,function*(){if(!t&&[0,1].includes(this.readyState)){M(this,Le).debug("Websocket was already connecting or connected.");return}if(M(this,gr)!==!1)return new Promise((e,r)=>{Pe(this,Dn,Po).call(this),Pe(this,Co,Nd).call(this);try{ne(this,Ae,new WebSocket(Pe(this,rh,JT).call(this,M(this,En)))),M(this,Ae).binaryType="arraybuffer",M(this,Le).debug("Connecting");const i=setTimeout(()=>{M(this,Le).debug("Connection timeout. Closing socket"),ne(this,gr,!0),Pe(this,Co,Nd).call(this),M(this,Ae).close(3001,"Connection Timeout"),M(this,_e).autoReconnect&&!M(this,Ps)&&(M(this,Ke).emit("reconnecting"),Pe(this,Eo,yd).call(this)),r(new Error("Connection timed out!"))},M(this,_e).connectionTimeout);M(this,Ae).onopen=()=>{M(this,Le).debug(`Ready State: ${WT[M(this,Ae).readyState]}`),i&&clearTimeout(i),Pe(this,Od,ch).call(this),ne(this,Zr,{code:void 0,reason:void 0}),M(this,Ke).emit("connected"),M(this,_e).flushOnReconnect&&this.flush(),e()},M(this,Ae).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),M(this,Le).debug("Socket closed. Close event:",{event:a}),M(this,Le).debug(`Connection closed code: ${o}`),M(this,Le).debug(`Connection closed reason: ${c}`),M(this,Ps)||Pe(this,Md,ah).call(this,o,c)}catch(o){Pe(this,To,Td).call(this,o)}},M(this,Ae).onerror=a=>{Pe(this,To,Td).call(this,a)},M(this,Ae).onmessage=a=>Pe(this,ih,KT).call(this,a)}catch(i){Pe(this,To,Td).call(this,i,r)}})})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(M(this,_e).queueOnDisconnect&&(!M(this,Ae)||M(this,Ae).readyState!==1))return M(this,Le).debug("Queuing message since socket is not connected!",a),M(this,Ar).push(a),!1;const o=GT.encode(a);return Pe(this,_o,Dd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,_o,Dd).call(this,t)}receive(t,e){return M(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")){M(this,Ke).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ke).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ke).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ke).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ne(this,gr,!1),Pe(this,Dn,Po).call(this),this.removeAllListeners(),ne(this,Zr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Ae).close(1e3,"Sockrates disconnect method called.")}}Ae=new WeakMap,En=new WeakMap,_e=new WeakMap,Le=new WeakMap,Ar=new WeakMap,Ke=new WeakMap,gr=new WeakMap,Zr=new WeakMap,Ps=new WeakMap,_n=new WeakMap,Gs=new WeakMap,rh=new WeakSet,JT=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)://.")},To=new WeakSet,Td=function(s,t){M(this,Le).error("Error:",{error:s}),M(this,Ke).emit("errored",{error:s}),t==null||t(s)},ih=new WeakSet,KT=function(s){if(Pe(this,Od,ch).call(this),s.data===NO){M(this,Le).debug("Received ping from server"),Pe(this,_o,Dd).call(this,VO);return}const t=GT.decode(s.data),{id:e,payload:r}=t;M(this,Le).debug("Received message",{event:t.event,messageID:e}),M(this,Ke).emit(t.event.toString(),{id:e,payload:r})},nh=new WeakSet,Cg=function(){return M(this,Ae).readyState===1},Md=new WeakSet,ah=function(s,t){ne(this,Zr,{reason:t,code:s}),M(this,Ke).emit("disconnected",{code:s,reason:t})},oh=new WeakSet,zT=function(){const{reason:s,code:t}=M(this,Zr);t&&t!==1e3&&M(this,gr)&&M(this,_e).autoReconnect&&!M(this,Ps)&&(M(this,Le).debug(`Triggering reconnection due to ${s}.`),M(this,Ke).emit("reconnecting"),Pe(this,Eo,yd).call(this))},Eo=new WeakSet,yd=function(s=!0){return u(this,null,function*(){if(s&&M(this,Ps)){M(this,Le).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,Ps)||M(this,Gs).reset(),M(this,_e).maxReconnectionAttempts!==null&&M(this,Gs).getAttempts()>=M(this,_e).maxReconnectionAttempts){M(this,Ke).emit("failed"),ne(this,Ps,!1);return}ne(this,Ps,!0),Pe(this,Co,Nd).call(this),Pe(this,Dn,Po).call(this);try{if(yield M(this,Gs).wait(),M(this,gr)===!1)return;if(M(this,Le).debug(`Reconnection attempt ${M(this,Gs).getAttempts()}`),M(this,Ke).emit("reconnectAttempt",{attempt:M(this,Gs).getAttempts()}),yield this.connect(),!Pe(this,nh,Cg).call(this))throw Error("Reconnect Failed");ne(this,Ps,!1),ne(this,Zr,{code:void 0,reason:void 0}),M(this,Ke).emit("reconnected")}catch(t){M(this,Le).debug("Failed to reconnect."),M(this,Ke).emit("reconnectFailure",{attempt:M(this,Gs).getAttempts()}),Pe(this,Eo,yd).call(this,!1)}})},_o=new WeakSet,Dd=function(s){try{return M(this,Ae).send(s),!0}catch(t){return M(this,Le).error(t.message),!1}},Od=new WeakSet,ch=function(){this.config.disconnectOnPingTimeout&&(M(this,Le).debug("Resetting ping timeout"),Pe(this,Dn,Po).call(this),ne(this,_n,setTimeout(()=>{var s;M(this,Le).debug("Disconnecting the socket due to ping timeout"),ne(this,gr,!0);const t=3002,e="Ping timeout";(s=M(this,Ae))==null||s.close(t,e),Pe(this,Md,ah).call(this,t,e)},M(this,_e).pingTimeout)))},Dn=new WeakSet,Po=function(){M(this,_n)&&(clearTimeout(M(this,_n)),ne(this,_n,void 0))},Co=new WeakSet,Nd=function(){M(this,Ae)&&(M(this,Ae).onopen=void 0,M(this,Ae).onerror=void 0,M(this,Ae).onmessage=void 0,M(this,Ae).onclose=void 0)};var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,Jl=(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&&xO(t,e,i),i};const wg=65535,$O=3e3;var Yr,Ce,we,Me,is,et,Oc,dh,Nc,lh,Gg;const YT=(Gg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,we);m(this,Oc);m(this,Nc);m(this,Yr,void 0);m(this,Ce,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");m(this,is,void 0);m(this,et,void 0);var a;if(!t||!e||!r)throw new b("peerId, meetingId, or authToken can not be empty","0404");f(this,is,void 0),f(this,et,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Yr,x(this,Oc,dh).call(this,t)),f(this,Ce,new LO(n(this,Yr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,we,Me).socketJoinAttempted}set joinAttempted(s){n(this,we,Me).socketJoinAttempted=s}get telemetry(){return n(this,et).getValue("telemetry")}get logger(){return n(this,et).getValue("logger")}get peerId(){return n(this,et).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,Yr,x(this,Oc,dh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ce).updateURL(n(this,Yr))}static getSocketEdgeDomain(s){return rn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Yr)}connect(){return u(this,null,function*(){n(this,we,Me).socketJoinAttempted=!0,yield n(this,Ce).connect(),n(this,we,Me).socketJoinAttempted=!0,n(this,we,Me).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){n(this,we,Me).socketJoinAttempted=!1,n(this,Ce).disconnect(),n(this,we,Me).socketJoinAttempted=!0,n(this,we,Me).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,et).getValue("telemetry").injectContext(r),n(this,Ce).send(s,e!=null?e:x(this,Nc,lh).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=(_,P)=>{n(this,Ce).removeListener(a,_),n(this,Ce).removeListener(wg,P),n(this,Ce).removeListener(Mr.errorResponse,P),n(this,Ce).removeListener(Cs.errorResponse,P)},l=r!=null?r:x(this,Nc,lh).call(this),p={};n(this,et).getValue("telemetry").injectContext(p);const T=({id:_,payload:P})=>{if(l===_){let C;try{const w=FR.fromBinary(P);C=new Error(w.errorMessage)}catch(w){C=new Error("failed to parse error message",{cause:w});try{const $=Bb.fromBinary(P);C=new Error($.message)}catch($){C=new Error("failed to parse error message",{cause:$})}}c(C),d(y,T)}},y=({id:_,payload:P})=>{l===_&&(o({id:_,payload:P}),d(y,T))};n(this,Ce).on(a,y),n(this,Ce).on(wg,T),n(this,Ce).on(Mr.errorResponse,T),n(this,Ce).on(Cs.errorResponse,T),setTimeout(()=>{d(y,T),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(p)))})}on(s,t){n(this,Ce).on(s,t)}onStateEvent(s,t){n(this,Ce).on(s,t)}removeListener(s,t){n(this,Ce).removeListener(s,t)}removeListeners(s){n(this,Ce).removeListeners(s)}flush(){return n(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),n(this,is)&&(clearTimeout(n(this,is)),f(this,is,void 0)),n(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:E.location.country});const{recv:e,send:r}=(i=n(this,we,Me).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==An.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==An.CONNECTED?n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}):f(this,is,setTimeout(()=>{n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,we,Me).joinAttempted}),f(this,is,void 0)},$O)),n(this,we,Me).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),n(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}}),n(this,we,Me).updateSocketConnectionState("reconnectAttempt",s)})),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,we,Me).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,we,Me).mediaJoinAttempted}}),n(this,is)&&(clearTimeout(n(this,is)),f(this,is,void 0)),n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,we,Me).mediaJoinAttempted}),n(this,we,Me).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),n(this,et).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),n(this,we,Me).updateSocketConnectionState("failed")}))}},Yr=new WeakMap,Ce=new WeakMap,we=new WeakSet,Me=function(){return n(this,et).getValue("connectionHandler")},is=new WeakMap,et=new WeakMap,Oc=new WeakSet,dh=function(s){let t=YT.getSocketEdgeDomain(n(this,et).getValue("baseURI"));typeof La(n(this,et),"socket_server_base")=="string"&&(t=La(n(this,et),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,a=H(D({roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0},i!==s&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>wd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Nc=new WeakSet,lh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Gg);let Gc=YT;Jl([E.trace("SocketService.connect")],Gc.prototype,"connect",1);Jl([E.trace("SocketService.disconnect")],Gc.prototype,"disconnect",1);Jl([E.trace("SocketService.sendMessagePromise")],Gc.prototype,"sendMessagePromise",1);Jl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Gc.prototype,"sendMessagePromiseWithTimeout",1);class FO{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=gk.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=Fk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=_f.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Zp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return Ak.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,yk.toBinary({payloads:t}));return Zp.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,kk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield this.socketService.sendMessagePromise(U.movePeers,Lk.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 BO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,qO=(s,t,e,r)=>{for(var i=r>1?void 0:r?HO(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&&BO(t,e,i),i},_s;class QT extends qt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);m(this,_s,void 0);f(this,_s,e)}get supportsConnectedMeetings(){return n(this,_s).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.
13
13
  Please connect with our support team to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield n(this,_s).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield n(this,_s).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield n(this,_s).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();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());return yield Promise.all(r),yield n(this,_s).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const a=yield n(this,_s).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success&&this.moveSuccessHandler(e,r,i),a})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const a=yield n(this,_s).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success&&this.moveSuccessHandler(e,r,i.map(o=>o.id)),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 H(D({},o),{participants:c})}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return H(D({},o),{participants:c})}return o})}}_s=new WeakMap;qO([Mt({maxInvocations:60,period:60})],QT.prototype,"getConnectedMeetings",1);var jO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?GO(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&&jO(t,e,i),i},ge,Wg;const XT=(Wg=class{constructor(s){h(this,"connectedMeetings");m(this,ge,void 0);f(this,ge,s),this.connectedMeetings=new QT(s)}get telemetry(){return n(this,ge).getValue("telemetry")}get logger(){return n(this,ge).getValue("logger")}static init(s){const t=new XT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){const t=n(this,ge).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.switchMeeting(t)}switchMeeting(e){return u(this,arguments,function*({authToken:s,meetingId:t}){var a,o,c,d;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
14
14
  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:n(this,ge).getValue("self").videoEnabled,audio:n(this,ge).getValue("self").audioEnabled};try{n(this,ge).getValue("self").cleanupEvents(),yield n(this,ge).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(o=(a=n(this,ge).getValue("meeting"))==null?void 0:a.meta)==null?void 0:o.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const i=yield ey.init(H(D({},n(this,ge).getValue("options")),{cachedUserDetails:null,defaults:H(D(D({},n(this,ge).getValue("options").defaults),r),{mediaHandler:n(this,ge).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}=n(this,ge).getValue("self");i.self.setName(n(this,ge).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=n(this,ge).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,ge).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ge).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,H(D({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,ge).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})}},ge=new WeakMap,Wg);let Kl=XT;Jh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Kl.prototype,"getConnectedMeetings",1);Jh([E.trace("ConnectedMeetingsController.setupEvents")],Kl.prototype,"setupEvents",1);Jh([E.trace("ConnectedMeetingsController.switchMeeting")],Kl.prototype,"switchMeeting",1);var WO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,zl=(s,t,e,r)=>{for(var i=r>1?void 0:r?JO(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&&WO(t,e,i),i};const Pn=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 N,B;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(NT(s),ve.isSupported()===!1)throw new b("Browser not supported","0010",c,!0);const d=XM(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 N0(s);s.setValue("connectionHandler",l);const p=Pn.createSocketService(s),g=p.connect(),T=d.getUserDetails(),y=d.getPlugins();let _,P="";try{yield Pn.setupFlagsmith(s)}catch(G){c.error("Failed to setup flagsmith",{error:G})}try{yield g}catch(G){c.error("[Controller]: Failed to connect to socket server:",{error:G})}try{({meetingTitle:P}=yield d.getRoomNodeData()),_=yield T,c.info("CF SFU is being used."),s.setValue("presetName",_.preset.name)}catch(G){c.error("Failed to get room metadata",{error:G})}const C=Bu.init(_.preset,!s.getValue("modules").theme),w=Gu.init(s,C.viewType,_.preset.permissions),$=Pn.setupControllers(p,s,_,y,P,C,w);P0(C)&&((N=Pn.createRoomNodeClient(s,p).initializeConnection(_.participant.name,i,!1,w))==null||N.catch(re=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:re})})),E.location.country=(B=d.ipInfo)==null?void 0:B.country;const{controllers:F}=yield $;return Ew(),new Pn(e,F,s)})}static setupFlagsmith(s){return u(this,null,function*(){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=vw(i),d=H(D({entity:_u.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i},ve.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const p=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?rn({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";yield s.getValue("flagsmith").identify(`${_u.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,a,o){return u(this,null,function*(){var I,Ue,wr;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),p=t.getValue("logger"),{viewType:g,mediaConstraints:{audio:T}}=a;t.setValue("viewType",g),t.setValue("defaults",D({mediaConfiguration:{audio:{enableHighBitrate:(I=T.enableHighBitrate)!=null?I:!1,enableStereo:(Ue=T.enableStereo)!=null?Ue:!1}}},l)),t.setValue("maxPreferredStreams",ve.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let y,_,P,C,w,$,F,N,B;const G=new hO(t,s),re=new FO(s);t.setValue("connectedMeetingsSocketHandler",re);const tt=new Gl(t,s),cs=new as(t,s),ni=new yO(s),ds=new LT(t,s),A=new SO(t,s),v=new uO(s),R=new on(t,s),L=yield ii.init(t,ds,d,o,a);t.setValue("selfController",L);const fe=yield xf.init(t,L.self,ds,G,i);if(c.participant&&(N=new Cr(t,L.self,ds)),(wr=c.e2ee)!=null&&wr.enabled&&c.e2ee.manager.init(p,t.getValue("peerSessionStore")),c.chat&&(_=yield ws.init(t,cs,R,L.self,N.participants)),c.internals&&(w=yield Vh.init(t)),c.livestream&&a.viewType===At.Livestream&&t.getValue("flagsmith").hasFeature(ee.LIVESTREAM)&&(F=new Wf(t,L.self,v)),a.viewType!==At.Chat){if(c.poll&&(y=yield Of.init(t,L.self,tt)),c.recording&&($=new Bf(t,L.self,ds)),c.stage&&(P=new Uf(t,ni,ds,L.self,N.participants)),c.plugin){if(!N)throw new b("The plugin module cannot be initialized without the `participant` module","0102");const qs=yield r;C=yield Bc.init(t,qs,A,cs,_==null?void 0:_.chat,L.self,N.participants,i)}if(c.connectedMeetings&&(B=yield Kl.init(t)),c.pip){const qs=yield Pu._init(t,L.self);t.setValue("pip",qs)}}const V={storesManager:new wD(t,A),pollController:y,selfController:L,metaController:fe,chatController:_,stageController:P,pluginController:C,recordingController:$,internalsController:w,livestreamController:F,participantController:N,connectedMeetingsController:B};return{theme:a,permissions:o,controllers:V}})}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return OT(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Gc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Wc=Pn;zl([E.trace("Controller.init")],Wc,"init",1);zl([E.trace("setupFlagsmith")],Wc,"setupFlagsmith",1);zl([E.trace("Controller.createRoomNodeClient")],Wc,"createRoomNodeClient",1);zl([E.trace("Controller.createSocketService")],Wc,"createSocketService",1);class KO{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 Rg=new KO;function zO(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=mi.baseURI.prod;t&&(a=t);const o=`https://${rn({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 Qr,Zi,en,Vc,Rl,ZT;class YO{constructor(){m(this,Rl);m(this,Qr,new Audio);m(this,Zi,new MediaStream);m(this,en,new Map);m(this,Vc,void 0);n(this,Qr).srcObject=n(this,Zi),n(this,Qr).autoplay=!0}playTracks(t){return u(this,null,function*(){return t.forEach(e=>{n(this,en).has(e.id)||(n(this,Zi).addTrack(e),n(this,en).set(e.id,e))}),this.play()})}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Qr).setSinkId(t)}removeTrack(t){const e=n(this,en).get(t);e&&(n(this,Zi).removeTrack(e),n(this,en).delete(t))}play(){return u(this,null,function*(){return n(this,Qr).srcObject=n(this,Zi),n(this,Qr).play().catch(t=>{x(this,Rl,ZT).call(this,t)})})}onError(t){f(this,Vc,t)}}Qr=new WeakMap,Zi=new WeakMap,en=new WeakMap,Vc=new WeakMap,Rl=new WeakSet,ZT=function(t){var e;(e=n(this,Vc))==null||e.call(this,t)};var tn;class QO extends YO{constructor(){super();m(this,tn,void 0);f(this,tn,new Map)}addParticipantTrack(e,r){n(this,tn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,tn).get(e);r&&this.removeTrack(r),n(this,tn).delete(e)}}tn=new WeakMap;var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Yl=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZO(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&&XO(t,e,i),i},Ge,sn,Jg;let si=(Jg=class{constructor(t,e){m(this,Ge,void 0);m(this,sn,void 0);f(this,sn,t),f(this,Ge,e)}get peerId(){return n(this,sn).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Tr.v4(),a=mr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new eT(o);return c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var y,_,P,w,$,F,N;ve.init();const{mediaHandler:e}=(y=t.defaults)!=null?y:{},r=(e==null?void 0:e.peerId)||((P=(_=t==null?void 0:t.cachedUserDetails)==null?void 0:_.peerId)!=null?P:Tr.v4()),{authToken:i,baseURI:a}=t,C=zO(i,a),{meetingId:o}=C,c=ro(C,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=si.setupContext(r,t,o,c),l=d.getValue("telemetry"),p=d.getValue("logger");ly(p),Rg.init(p),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},($=(w=t.modules)==null?void 0:w.tracing)!=null?$:!0),p.init(d),p.info("Client::init::options",{clientInitOptions:H(D({},t),{authToken:`${(F=t.authToken)==null?void 0:F.slice(0,10)}...
15
- ${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield Wc.init(d),T=new si(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=mr.createContext(t,e),o=D(D({},lw),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",uw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.1-staging.2"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new QO),a}join(){return u(this,null,function*(){const{selfController:t}=n(this,Ge);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Rg.cleanup(),n(this,sn).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Ge);return e.leaveRoom(t)})}get participants(){var t;return(t=n(this,Ge).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Ge).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Ge).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Ge).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Ge).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Ge).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Ge).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Ge).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Ge).stageController)==null?void 0:t.stage}get stores(){return n(this,Ge).storesManager}get audio(){return n(this,sn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Ge).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)})}},Ge=new WeakMap,sn=new WeakMap,Jg);Yl([ut("0002"),Pr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],si.prototype,"join",1);Yl([ut("0003")],si.prototype,"leave",1);Yl([ut("0001"),Pr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],si,"init",1);si=Yl([ut("0000")],si);const ey=si;module.exports=ey;
15
+ ${(N=t.authToken)==null?void 0:N.slice(-10)}`})});const g=yield Wc.init(d),T=new si(d,g);return d.setValue("meeting",T),T})}static setupContext(t,e,r,i){var d,l;const a=mr.createContext(t,e),o=D(D({},lw),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",uw({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Rs(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.1-staging.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new QO),a}join(){return u(this,null,function*(){const{selfController:t}=n(this,Ge);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Rg.cleanup(),n(this,sn).getValue("peerSessionStore").reset();const{selfController:e}=n(this,Ge);return e.leaveRoom(t)})}get participants(){var t;return(t=n(this,Ge).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,Ge).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,Ge).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,Ge).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,Ge).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,Ge).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,Ge).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,Ge).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,Ge).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,Ge).stageController)==null?void 0:t.stage}get stores(){return n(this,Ge).storesManager}get audio(){return n(this,sn).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,Ge).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)})}},Ge=new WeakMap,sn=new WeakMap,Jg);Yl([ut("0002"),Pr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],si.prototype,"join",1);Yl([ut("0003")],si.prototype,"leave",1);Yl([ut("0001"),Pr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],si,"init",1);si=Yl([ut("0000")],si);const ey=si;module.exports=ey;
package/dist/index.es.js CHANGED
@@ -28335,7 +28335,7 @@ let ti = (Kg = class {
28335
28335
  video: !0
28336
28336
  };
28337
28337
  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", lw({ baseURI: i.baseURI })), a.setValue("defaults", c), a.setValue("onError", e.onError || (() => {
28338
- })), a.setValue("cachedUserDetails", Rs(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.1-staging.2"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new YO()), a;
28338
+ })), a.setValue("cachedUserDetails", Rs(e.cachedUserDetails)), a.setValue("sdkVersion", "1.2.1-staging.3"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new YO()), a;
28339
28339
  }
28340
28340
  join() {
28341
28341
  return u(this, null, function* () {
package/dist/index.rn.js CHANGED
@@ -12,4 +12,4 @@ ${s}`}const xa={maxInvocations:5,period:1};function kt(s,t){return function(e,r,
12
12
  maxEnergy: ${n(this,Gr)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,nr)||i<n(this,nr))&&m(this,nr,i),(!n(this,Gr)||i>n(this,Gr))&&m(this,Gr,i),{energy:(i-n(this,nr))/(n(this,Gr)-n(this,nr))*10||0,isVoice:r})},yc=new WeakSet,Ku=function(t){return t<5},dl=new WeakSet,cT=function(t=n(this,Hi)){var r;if(!n(this,Ts)||!t){n(this,ar).getValue("flagsmith").hasFeature(Q.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${n(this,Ts)}`);return}const e={producerId:n(this,Ts),energy:Math.round(t),silent:V(r=Eo,yc,Ku).call(r,t)};m(this,ba,e.silent),this.reportRequest(e)},ll=new WeakSet,dT=function(t){const e=Math.log10(t);return Math.round(e)},g(uo,yc),g(uo,ll);const GD=(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}},WD=(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 JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,ae=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&JD(t,e,i),i};const At=["video/VP9","video/VP8"];var vc,Ec,nt,H,ka,mt,qi,ji,Gi,_c,es,cr,Pc,Wi,Ji,ft,Ct,Wr,Tn,ul,uT,hl,hT,pl,pT,Cc,zu,gl,cu,gT,ml,mT,fl,fT,Tl,TT,Ye,lt,Ki,ho,Sl,ST,yl,yT,vl,vT;const lT=(cu=class{constructor(s,t){g(this,Wr);g(this,ul);g(this,hl);g(this,pl);g(this,Cc);g(this,ml);g(this,fl);g(this,Tl);g(this,Ye);g(this,Ki);g(this,Sl);g(this,yl);g(this,vl);u(this,"context");u(this,"authToken");u(this,"e2ee");g(this,vc,void 0);g(this,Ec,void 0);g(this,nt,void 0);g(this,H,void 0);g(this,ka,void 0);g(this,mt,void 0);g(this,qi,void 0);g(this,ji,void 0);g(this,Gi,void 0);g(this,_c,void 0);g(this,es,null);g(this,cr,void 0);g(this,Pc,void 0);g(this,Wi,void 0);g(this,Ji,void 0);g(this,ft,void 0);g(this,Ct,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,m(this,Wi,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,Ji,new Map([["video/VP9",new Set],["video/VP8",new Set]])),m(this,nt,e),m(this,qi,!1),m(this,H,new BD(s,e)),m(this,mt,n(this,H).events),m(this,cr,new Set),m(this,ft,new Map),m(this,ji,!1),m(this,Gi,new Fu(s.getValue("logger"))),m(this,Ct,new uo(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,_c,Eh(async()=>{if(!n(this,Wr,Tn).mediaJoinAttempted)return;const{roomJoined:a}=await this.joinRoom(n(this,Ec),n(this,vc),!0,!0);a&&(this.context.getValue("peerSessionStore").emit(b.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(b.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,Wr,Tn).mediaJoined}set mediaJoined(s){n(this,Wr,Tn).mediaJoined=s}reset(){n(this,H).closeAllProducers(),n(this,H).closeAllConsumers(),n(this,ft).clear(),n(this,cr).clear(),m(this,es,null),n(this,Gi).stop(),n(this,H).stopAllTransports(),n(this,H).reset(),m(this,Gi,new Fu)}async joinRoom(s,t,e=!1,r=!1,i={}){n(this,Wr,Tn).mediaJoinAttempted=!0,m(this,qi,!0),e&&this.reset();try{return await n(this,Gi).push(()=>V(this,ul,uT).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(b.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return n(this,es)?n(this,es):(m(this,es,(async()=>{try{await V(this,Cc,zu).call(this,s,t,e,r)}catch(i){throw m(this,es,null),i}})()),n(this,es))}getConsumers(){return n(this,H).consumers}getProducers(){return n(this,H).producers}async leaveRoom(){n(this,H).stopAllTransports(),m(this,ji,!1),n(this,Wr,Tn).mediaJoinAttempted=!1;const s={closeRoom:!1};n(this,nt).sendMessagePromise(n(this,mt).leaveRoom,Kw.toBinary(s)).then(e=>{var r;(r=LR.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;const e=t==="video/VP9"?de.WEBCAM:de.WEBCAM_BACKUP,r=V(this,Ye,lt).call(this,e);if(r){const T=await r;if(n(this,H).producers.has(T)){const E=n(this,H).producers.get(T);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(At.filter(T=>T!==t)),a=V(this,vl,vT).call(this,s,i),o=Oa(this.context,"disableSimulcast"),c=(f=(p=this.context)==null?void 0:p.getValue("overrides"))==null?void 0:f.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(Q.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),a.encodings=O0(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(Q.TRACK_HINT)&&(a.track.contentHint=this.context.getValue("flagsmith").getValue(Q.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,ft).delete(e)},h=n(this,H).createProducer(a,l);return V(this,Ki,ho).call(this,e,h.then(T=>T.id)),h.then(T=>T.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(Q.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=At.filter(i=>{var a,o;return((o=(a=n(this,ka).sender)==null?void 0:a.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&n(this,Ji).get(i).size>0});return e.length===0&&e.push(At[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:Te.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,ft).delete(de.SCREENSHARE_VIDEO),n(this,ft).delete(de.SCREENSHARE_AUDIO)},a=n(this,H).createProducer(r,i);V(this,Ki,ho).call(this,de.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:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=n(this,H).createProducer(c,d),V(this,Ki,ho).call(this,de.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 Rt("track undefined");const t=V(this,Ye,lt).call(this,de.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,Ct)&&(n(this,Ct).audioTrack=s,n(this,Ct).producerId=a,n(this,Ct).start());return}await n(this,H).closeProducer(a,{stopTrack:!1})}await this.shareMic(s);return}const e=V(this,yl,yT).call(this,s),r=()=>{n(this,ft).delete(de.MIC)},i=n(this,H).createProducer(e,r);V(this,Ki,ho).call(this,de.MIC,i.then(a=>a.id)),await i.then(a=>{n(this,Ct)&&(n(this,Ct).audioTrack=a.track,n(this,Ct).producerId=a.id,n(this,Ct).start())})}catch(t){throw new w(t)}}async pauseMic(){var r;const s=await V(this,Ye,lt).call(this,de.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,Ct))==null||r.stop();const e={producerId:t.id,pause:!0};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(e))}async pauseWebcam(){const s=await V(this,Ye,lt).call(this,de.WEBCAM),t=await V(this,Ye,lt).call(this,de.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,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await V(this,Ye,lt).call(this,de.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(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(e))}async resumeWebcam(s=de.WEBCAM){const t=await V(this,Ye,lt).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(b.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,nt).sendMessage(n(this,mt).toggleProducer,Wc.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?de.WEBCAM:de.WEBCAM_BACKUP,e=await V(this,Ye,lt).call(this,t);V(this,Sl,ST).call(this,t),e&&await n(this,H).closeProducer(e)}async disableMic(){var t;const s=await V(this,Ye,lt).call(this,de.MIC);s&&await n(this,H).closeProducer(s),(t=n(this,Ct))==null||t.stop(),n(this,ft).delete(de.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await V(this,Ye,lt).call(this,de.SCREENSHARE_VIDEO),t=await V(this,Ye,lt).call(this,de.SCREENSHARE_AUDIO);s&&await n(this,H).closeProducer(s),t&&await n(this,H).closeProducer(t),n(this,cr).clear(),n(this,ft).delete(de.SCREENSHARE_VIDEO),n(this,ft).delete(de.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await V(this,Ye,lt).call(this,de.WEBCAM),r=await V(this,Ye,lt).call(this,de.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,Ye,lt).call(this,de.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,nt).sendMessagePromise(n(this,mt).globalPinPeer,cR.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,cr).add(s.consumerPeerId),n(this,cr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));n(this,H).switchConsumersToLayer(e,t)}async handleSocketEvents(){n(this,nt).on(n(this,mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=hb.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===xs.AUDIO?"audio/opus":"video/VP8"),i.kind===xs.VIDEO&&!i.screenShare&&((e=(t=n(this,ka).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(a=>a.mimeType===At[0]))>=0&&n(this,Wi).get(At[0]).has(r)&&i.mimeType!==At[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(b.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===xs.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),n(this,nt).on(n(this,mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:a,screenShare:o}}=Vp.fromBinary(s);if(o)return;const c=r===xs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${a}, kind:${c}, paused:${i} payload: ${JSON.stringify(Vp.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?b.MUTE_SELF:b.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(b.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(b.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(b.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),n(this,nt).on(n(this,mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=yu.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),n(this,cr).delete(t),n(this,H).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(b.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),n(this,nt).on(n(this,mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=mb.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(b.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(b.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,nt).on(n(this,mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,qi)&&!n(this,ji)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(b.ROOM_NODE_DISCONNECTED),n(this,_c).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(b.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(b.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<=At.length;o+=1){const c=At[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===At.length-1){n(this,Ji).get(c).add(s);break}}for(let o=0;o<=At.length;o+=1){const c=At[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===At.length-1){n(this,Wi).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(Q.FORCE_VIDEO_CODEC)||(n(this,Wi).forEach(t=>t.delete(s)),n(this,Ji).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===At[0])&&this.disableWebcam(e)}))}},vc=new WeakMap,Ec=new WeakMap,nt=new WeakMap,H=new WeakMap,ka=new WeakMap,mt=new WeakMap,qi=new WeakMap,ji=new WeakMap,Gi=new WeakMap,_c=new WeakMap,es=new WeakMap,cr=new WeakMap,Pc=new WeakMap,Wi=new WeakMap,Ji=new WeakMap,ft=new WeakMap,Ct=new WeakMap,Wr=new WeakSet,Tn=function(){return this.context.getValue("connectionHandler")},ul=new WeakSet,uT=async function(s,t,e,r){m(this,Ec,s);try{return n(this,es)?await n(this,es):await V(this,Cc,zu).call(this,s,t,e,r),V(this,pl,pT).call(this,t),{roomJoined:await V(this,hl,hT).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{m(this,es,null)}},hl=new WeakSet,hT=async function(){try{this.mediaJoined=!0;const{roomState:s}=await n(this,H).socketHandler.notifySelfJoinComplete();return m(this,vc,s.roomUuid),m(this,ji,!0),m(this,qi,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},pl=new WeakSet,pT=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...Te.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)},Cc=new WeakSet,zu=async function(s,t,e,r){var i,a;try{(a=n(this,Pc))!=null||m(this,Pc,V(i=lT,gl,gT).call(i));const o=V(this,ml,mT).call(this);await V(this,fl,fT).call(this,s,t,e,o),await n(this,H).setupTransports({send:!0,recv:!0}),await V(this,Tl,TT).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},gl=new WeakSet,gT=function(){const{ipInfo:s}=at();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},ml=new WeakSet,mT=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(Q.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=ID(s);return m(this,ka,t),t},fl=new WeakSet,fT=async function(s,t,e,r){await qf(async(i,a)=>{if(!n(this,nt).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,Pc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},Tl=new WeakSet,TT=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(Q.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===B.Allowed&&e.push(this.shareWebcam(WD(!1))),s.canProduceAudio===B.Allowed){const r=GD(!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})}},Ye=new WeakSet,lt=function(s){return n(this,ft).get(s)},Ki=new WeakSet,ho=function(s,t){return n(this,ft).set(s,t)},Sl=new WeakSet,ST=function(s){return n(this,ft).delete(s)},yl=new WeakSet,yT=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},vl=new WeakSet,vT=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(cu,gl),cu);let re=lT;ae([v.trace("MediaNodeClient.reset",{country:v.location.country})],re.prototype,"reset",1);ae([v.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1);ae([v.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1);ae([v.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1);ae([v.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1);ae([v.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1);ae([v.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1);ae([v.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1);ae([v.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1);ae([v.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1);ae([v.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1);ae([v.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1);ae([v.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1);ae([v.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1);ae([v.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1);ae([v.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1);ae([v.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1);ae([v.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1);ae([v.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1);ae([v.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1);ae([v.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1);ae([v.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1);ae([v.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1);ae([v.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1);ae([v.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1);ae([v.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1);ae([v.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1);ae([v.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function ET(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 _T(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 zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,hn=(s,t,e,r)=>{for(var i=r>1?void 0:r?YD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zD(t,e,i),i},zi,Ss,X,Tt,Dt,Dg;const PT=(Dg=class{constructor(s,t,e,r){g(this,Tt);u(this,"self");u(this,"authToken");g(this,zi,void 0);u(this,"viewType");g(this,Ss,void 0);g(this,X,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,X,s),this.viewType=r,this.authToken=a,m(this,zi,i),m(this,Ss,e),t.config.viewType!==bt.Chat&&this.setupEvents()}get peerId(){return n(this,X).getValue("peerId")}get telemetry(){return n(this,X).getValue("telemetry")}get logger(){return n(this,X).getValue("logger")}get mediaJoined(){return n(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=at(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const h=!s.getValue("flagsmith").hasFeature(Q.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:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Xm(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===B.Allowed&&r)try{await n(this,Tt,Dt).shareMic(s),this.self.audioEnabled||n(this,Tt,Dt).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===B.Allowed&&i)try{const d=await n(this,Tt,Dt).shareWebcam(t);d&&d.id!==t.id&&n(this,X).getValue("flagsmith").hasFeature(Q.EXP_RESHARE)&&await n(this,Tt,Dt).shareWebcam(d),this.self.videoEnabled||n(this,Tt,Dt).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===B.Allowed&&a)try{await((c=n(this,Tt,Dt))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){n(this,X).getValue("callstats").callEnded(),n(this,Tt,Dt).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,X).getValue("peerSessionStore").on(b.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,X).getValue("peerSessionStore").on(b.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&n(this,X).getValue("flagsmith").hasFeature(Q.REFRESH_ID_ON_DISCONNECTION)&&(t=gr.v4()),n(this,zi).updateURL(t),n(this,X).getValue("telemetry").resetPeerId(t),at().setHeader("tracing-id",t),hr.remapContext(t,n(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,X).getValue("peerSessionStore").on(b.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,Ss).on(L.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,Ss).on(id.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,X).getValue("peerSessionStore").emit(b.UPDATE_PERMISSIONS,t.patch)})}),n(this,Ss).on(L.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,Ss).on(L.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,Ss).on(L.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,X).getValue("peerSessionStore").onAsync(b.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(b.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,X).getValue("peerSessionStore").on(b.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,X).getValue("callstats").audioOff())}),n(this,X).getValue("peerSessionStore").on(b.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,X).getValue("callstats").videoOff())}),n(this,X).getValue("peerSessionStore").onAsync(b.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(b.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,Ss).joinRoom(this.self);n(this,Ss).socket.flush();const e=Rh(t.stageType);if(n(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),n(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=n(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,X).notify("stageStatus");try{(e=n(this,zi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}_T(n(this,X)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,X).getAllValues();try{if(e===bt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}ET(n(this,X),{socket:n(this,zi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:h}=(o=await((a=n(this,Tt,Dt))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!h)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new w("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=n(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===bt.Webinar)&&n(this,Tt,Dt)&&(n(this,Tt,Dt).mediaJoined&&s!=="disconnected"&&await n(this,Tt,Dt).leaveRoom(),!(s==="stageLeft"&&t===bt.Livestream)&&(n(this,Tt,Dt).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()}},zi=new WeakMap,Ss=new WeakMap,X=new WeakMap,Tt=new WeakSet,Dt=function(){return n(this,X).getValue("roomNodeClient")},Dg);let ti=PT;hn([v.trace("SelfController.resetSelf")],ti.prototype,"resetSelf",1);hn([v.trace("SelfController.setupEvents")],ti.prototype,"setupEvents",1);hn([v.trace("SelfController.joinRoom")],ti.prototype,"joinRoom",1);hn([v.trace("SelfController.leaveRoom")],ti.prototype,"leaveRoom",1);hn([v.trace("SelfController.joinMediaRoom")],ti.prototype,"joinMediaRoom",1);hn([v.trace("SelfController.leaveMediaRoom")],ti.prototype,"leaveMediaRoom",1);hn([v.trace("SelfController.init")],ti,"init",1);var wc;class QD{constructor(t){g(this,wc,void 0);m(this,wc,t)}on(t,e){let r;t===L.roomPeerCount?r=Up.fromBinary.bind(Up):r=zp.fromBinary.bind(zp),n(this,wc).on(t,({payload:i})=>{if(t===L.roomPeerCount&&!i)return;const a=r(i);e(a)})}}wc=new WeakMap;var Rc,bc;class XD{constructor(t,e){g(this,Rc,void 0);g(this,bc,void 0);m(this,Rc,e),m(this,bc,t)}get logger(){return n(this,bc).getValue("logger")}on(t,e){let r,i;switch(t){case L.transcript:{r=Xl.fromBinary.bind(Xl),i=Xl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,Rc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Rc=new WeakMap,bc=new WeakMap;var ZD=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,Uh=(s,t,e,r)=>{for(var i=r>1?void 0:r?eO(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZD(t,e,i),i},dr,Ia;class Fl{constructor(t,e){g(this,dr,void 0);g(this,Ia,void 0);m(this,dr,e),m(this,Ia,t)}get logger(){return n(this,Ia).getValue("logger")}get telemetry(){return n(this,Ia).getValue("telemetry")}getPolls(){return n(this,dr).sendMessagePromise(qs.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,dr).sendMessage(qs.createPoll,rM.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,dr).sendMessage(qs.votePoll,nM.toBinary(r))}on(t,e){let r,i;switch(t){case qs.updatePoll:case qs.createPoll:case qs.votePoll:{r=iu.fromBinary.bind(iu),i=iu.create();break}}n(this,dr).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,dr).removeListeners(t)}}dr=new WeakMap,Ia=new WeakMap;Uh([v.trace("PollSocketHandler.getPolls")],Fl.prototype,"getPolls",1);Uh([v.trace("PollSocketHandler.createPoll")],Fl.prototype,"createPoll",1);Uh([v.trace("PollSocketHandler.votePoll")],Fl.prototype,"votePoll",1);var tO=Object.defineProperty,sO=Object.getOwnPropertyDescriptor,rO=(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},xt;class CT{constructor(t,e){u(this,"socket");g(this,xt,void 0);m(this,xt,t),this.socket=e,this.handleSocketEvents(),n(this,xt).setValue("roomSocketHandler",this)}get telemetry(){return n(this,xt).getValue("telemetry")}get logger(){return n(this,xt).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,jb.toBinary(e));try{const{peer:a}=gn.fromBinary((await r).payload);n(this,xt).getValue("connectionHandler").socketJoined=!0,n(this,xt).getValue("peerSessionStore").emit(b.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,xt).getValue("peerSessionStore").emit(b.ROOM_STATE,d),n(this,xt).getValue("peerSessionStore").emit(b.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),new w("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,a)}}async getAllAddedParticipants(){try{return kk.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,Nb.toBinary(a));i=Zl.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=Zl.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=Zl.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,df.toBinary({peerId:t}));e=gn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=$p.create();try{const e=await this.socket.sendMessagePromise(L.getRoomInfo);t=$p.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=qp.create();try{const e=await this.socket.sendMessagePromise(L.getRoomStageState);t=qp.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,so.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,so.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,so.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(L.leaveRoom,Wb.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(L.kick,uf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(L.kickAll,af.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(L.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.acceptWaitingRoomRequests,Nk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(L.denyWaitingRoomRequests,Lk.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(id.updateUserPreset,uI.toBinary(r))}handleSocketEvents(){this.socket.on(L.broadcastMessage,({payload:t})=>{try{const e=so.fromBinary(t);n(this,xt).getValue("peerSessionStore").emit(b.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=so.fromBinary(t);n(this,xt).getValue("peerSessionStore").emit(b.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=gn.fromBinary.bind(gn),i=gn.create();break}case L.getWaitingRoomRequests:{r=(a,o)=>a?Hp.fromBinary(a,o):{requests:[]},i=Hp.create();break}case L.recordingPaused:case L.recordingStarted:case L.recordingStopped:{r=Xp.fromBinary.bind(Xp);break}case id.updateUserPreset:{r=jp.fromBinary.bind(jp);break}case Es.peerJoinedBroadcast:case kr.peerJoinedBroadcast:{r=Op.fromBinary.bind(Op);break}case Es.selfJoinComplete:case kr.selfJoinComplete:{r=Su.fromBinary.bind(Su);break}case Es.globalPeerPinBroadcast:case kr.globalPeerPinBroadcast:{r=Lp.fromBinary.bind(Lp);break}case Es.selectedPeer:case kr.selectedPeer:{r=Tu.fromBinary.bind(Tu);break}case Es.selectedPeerDiff:case kr.selectedPeerDiff:{r=Dp.fromBinary.bind(Dp);break}case Es.leaveRoom:case kr.leaveRoom:{r=yu.fromBinary.bind(yu);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(id.getUserPresets,iI.toBinary(e)),i=cI.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}}}xt=new WeakMap;rO([v.trace("RoomSocketHandler.joinRoom")],CT.prototype,"joinRoom",1);var wt;class iO{constructor(t){g(this,wt,void 0);m(this,wt,t)}async getStageRequests(){const{payload:t}=await n(this,wt).sendMessagePromise(L.getStageRequests);return t?ru.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,wt).sendMessage(L.requestStageAccess)}cancelRequestAccess(){n(this,wt).sendMessage(L.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,wt).sendMessage(L.grantStageAccess,JA.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,wt).sendMessage(L.denyStageAccess,zA.toBinary(e))}joinStage(){return n(this,wt).sendMessagePromise(L.joinStage,void 0,void 0,L.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,wt).sendMessagePromise(L.leaveStage,Qp.toBinary(e),void 0,L.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,wt).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=Yp.fromBinary.bind(Yp);break}case L.getStageRequests:case L.requestStageAccess:case L.cancelStageRequest:{r=ru.fromBinary.bind(ru);break}case L.peerStageStatusUpdate:{r=xp.fromBinary.bind(xp);break}}n(this,wt).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,wt).sendMessagePromise(L.getPeerInfo,df.toBinary({peerId:t}));return gn.fromBinary(e.payload)}}wt=new WeakMap;var Be,kc;class nO{constructor(t,e){g(this,Be,void 0);g(this,kc,void 0);m(this,Be,e),m(this,kc,t)}get logger(){return n(this,kc).getValue("logger")}addPlugin(t,e){n(this,Be).sendMessage(q.addPlugin,lA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Be).sendMessage(q.removePlugin,hA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Be).sendMessagePromise(q.getPlugins);return t?VA.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Be).sendMessage(q.customPluginEventToRoom,_A.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Be).sendMessage(q.customPluginEventToPeers,CA.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Be).sendMessage(q.enablePluginForRoom,gA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Be).sendMessage(q.enablePluginForPeers,SA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Be).sendMessage(q.disablePluginForRoom,fA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Be).sendMessage(q.disablePluginForPeers,vA.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,Be).sendMessage(q.storeInsertKeys,Gp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Be).sendMessage(q.storeGetKeys,kA.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Be).sendMessage(q.storeDeleteKeys,AA.toBinary(a),i)}storeDelete(t,e,r){n(this,Be).sendMessage(q.storeDelete,DA.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,Be).sendMessage(q.storeInsertKeys,Gp.toBinary(i))}on(t,e){let r;switch(t){case q.addPlugin:case q.enablePluginForPeers:case q.enablePluginForRoom:{r=Pu.fromBinary.bind(Pu);break}case q.removePlugin:case q.disablePluginForPeers:case q.disablePluginForRoom:{r=Wp.fromBinary.bind(Wp);break}case q.customPluginEventToPeers:case q.customPluginEventToRoom:{r=Kp.fromBinary.bind(Kp);break}case q.storeInsertKeys:case q.storeGetKeys:case q.storeDeleteKeys:case q.storeDelete:{r=Jp.fromBinary.bind(Jp);break}}n(this,Be).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Be=new WeakMap,kc=new WeakMap;var aO=Object.defineProperty,oO=(s,t,e)=>t in s?aO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,cO=(s,t,e)=>(oO(s,typeof t!="symbol"?t+"":t,e),e),$h=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>($h(s,t,"read from private field"),e?e.call(s):t.get(s)),ge=(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)=>($h(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ve=(s,t,e)=>($h(s,t,"access private method"),e),wd={},dO={get exports(){return wd},set exports(s){wd=s}},kn=typeof Reflect=="object"?Reflect:null,dg=kn&&typeof kn.apply=="function"?kn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ud;kn&&typeof kn.ownKeys=="function"?ud=kn.ownKeys:Object.getOwnPropertySymbols?ud=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ud=function(s){return Object.getOwnPropertyNames(s)};function lO(s){console&&console.warn&&console.warn(s)}var wT=Number.isNaN||function(s){return s!==s};function ne(){ne.init.call(this)}dO.exports=ne;wd.once=gO;ne.EventEmitter=ne;ne.prototype._events=void 0;ne.prototype._eventsCount=0;ne.prototype._maxListeners=void 0;var lg=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(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return lg},set:function(s){if(typeof s!="number"||s<0||wT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");lg=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||wT(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 RT(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return RT(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")dg(c,this,t);else for(var d=c.length,l=MT(c,d),e=0;e<d;++e)dg(l[e],this,t);return!0};function bT(s,t,e,r){var i,a,o;if(Bl(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=RT(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,lO(c)}return s}ne.prototype.addListener=function(s,t){return bT(this,s,t,!1)};ne.prototype.on=ne.prototype.addListener;ne.prototype.prependListener=function(s,t){return bT(this,s,t,!0)};function uO(){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 kT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=uO.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(s,t){return Bl(t),this.on(s,kT(this,s,t)),this};ne.prototype.prependOnceListener=function(s,t){return Bl(t),this.prependListener(s,kT(this,s,t)),this};ne.prototype.removeListener=function(s,t){var e,r,i,a,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,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():hO(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 IT(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?pO(i):MT(i,i.length)}ne.prototype.listeners=function(s){return IT(this,s,!0)};ne.prototype.rawListeners=function(s){return IT(this,s,!1)};ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):AT.call(s,t)};ne.prototype.listenerCount=AT;function AT(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ne.prototype.eventNames=function(){return this._eventsCount>0?ud(this._events):[]};function MT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function hO(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function pO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function gO(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))}DT(s,t,a,{once:!0}),t!=="error"&&mO(s,i,{once:!0})})}function mO(s,t,e){typeof s.on=="function"&&DT(s,"error",t,e)}function DT(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 fO 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 ug=new fO;class OT{static encode(t){return ug.toBinary(t)}static decode(t){return ug.fromBinary(new Uint8Array(t))}}function TO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Rr;class SO{constructor(t={}){cO(this,"opts"),ge(this,Rr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},se(this,Rr,0)}async wait(){se(this,Rr,A(this,Rr)+1);const t=TO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**A(this,Rr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return A(this,Rr)}reset(){se(this,Rr,0)}}Rr=new WeakMap;const Pr={debug:0,info:1,warn:2,error:3};var oi,ci;class yO{constructor(t){ge(this,oi,void 0),ge(this,ci,void 0),se(this,oi,console),se(this,ci,t)}debug(...t){Pr[A(this,ci)]>Pr.debug||A(this,oi).debug("[Sockrates]:",...t)}info(...t){Pr[A(this,ci)]>Pr.info||A(this,oi).info("[Sockrates]:",...t)}warn(...t){Pr[A(this,ci)]>Pr.warn||A(this,oi).warn("[Sockrates]:",...t)}error(...t){Pr[A(this,ci)]>Pr.error||A(this,oi).error("[Sockrates]:",...t)}}oi=new WeakMap,ci=new WeakMap;var NT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(NT||{});const vO="2",EO="3";var be,Sn,ye,Oe,br,Ge,ur,Yr,vs,yn,Hs,Yu,VT,po,hd,Qu,LT,Xu,hg,Rd,Zu,eh,xT,To,pd,So,bd,kd,th,In,yo,vo,Id;class _O{constructor(t,e){var f,T,E,P,R,_,x,U,D,$;ge(this,Yu),ge(this,po),ge(this,Qu),ge(this,Xu),ge(this,Rd),ge(this,eh),ge(this,To),ge(this,So),ge(this,kd),ge(this,In),ge(this,vo),ge(this,be,void 0),ge(this,Sn,void 0),ge(this,ye,void 0),ge(this,Oe,void 0),ge(this,br,void 0),ge(this,Ge,void 0),ge(this,ur,void 0),ge(this,Yr,void 0),ge(this,vs,void 0),ge(this,yn,void 0),ge(this,Hs,void 0);var r,i,a,o,c,d,l,h,p;se(this,Sn,t),se(this,br,[]),se(this,Ge,new wd),se(this,ur,!0),se(this,vs,!1),se(this,ye,e!=null?e:{}),(f=(r=A(this,ye)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=A(this,ye)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=A(this,ye)).pingTimeout)!=null||(a.pingTimeout=3e4),(P=(o=A(this,ye)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(R=(c=A(this,ye)).debug)!=null||(c.debug=!0),(_=(d=A(this,ye)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(x=(l=A(this,ye)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(U=(h=A(this,ye)).queueOnDisconnect)!=null||(h.queueOnDisconnect=!1),(D=(p=A(this,ye)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),se(this,Yr,{code:void 0,reason:void 0}),se(this,Oe,($=A(this,ye).logger)!=null?$:new yO(A(this,ye).debug?"debug":"info")),se(this,Hs,new SO)}get readyState(){var t;return(t=A(this,be))==null?void 0:t.readyState}get url(){return A(this,Sn)}updateURL(t){se(this,Sn,t),ve(this,eh,xT).call(this)}get config(){return A(this,ye)}get sendQueue(){return A(this,br)}flush(){if(!A(this,ye).queueOnDisconnect)return!1;const t=[];return A(this,br).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),se(this,br,t),A(this,br)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){A(this,Oe).debug("Websocket was already connecting or connected.");return}if(A(this,ur)!==!1)return new Promise((e,r)=>{ve(this,In,yo).call(this),ve(this,vo,Id).call(this);try{se(this,be,new WebSocket(ve(this,Yu,VT).call(this,A(this,Sn)))),A(this,be).binaryType="arraybuffer",A(this,Oe).debug("Connecting");const i=setTimeout(()=>{A(this,Oe).debug("Connection timeout. Closing socket"),se(this,ur,!0),ve(this,vo,Id).call(this),A(this,be).close(3001,"Connection Timeout"),A(this,ye).autoReconnect&&!A(this,vs)&&(A(this,Ge).emit("reconnecting"),ve(this,To,pd).call(this)),r(new Error("Connection timed out!"))},A(this,ye).connectionTimeout);A(this,be).onopen=()=>{A(this,Oe).debug(`Ready State: ${NT[A(this,be).readyState]}`),i&&clearTimeout(i),ve(this,kd,th).call(this),se(this,Yr,{code:void 0,reason:void 0}),A(this,Ge).emit("connected"),A(this,ye).flushOnReconnect&&this.flush(),e()},A(this,be).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),A(this,Oe).debug("Socket closed. Close event:",{event:a}),A(this,Oe).debug(`Connection closed code: ${o}`),A(this,Oe).debug(`Connection closed reason: ${c}`),A(this,vs)||ve(this,Rd,Zu).call(this,o,c)}catch(o){ve(this,po,hd).call(this,o)}},A(this,be).onerror=a=>{ve(this,po,hd).call(this,a)},A(this,be).onmessage=a=>ve(this,Qu,LT).call(this,a)}catch(i){ve(this,po,hd).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(A(this,ye).queueOnDisconnect&&(!A(this,be)||A(this,be).readyState!==1))return A(this,Oe).debug("Queuing message since socket is not connected!",a),A(this,br).push(a),!1;const o=OT.encode(a);return ve(this,So,bd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ve(this,So,bd).call(this,t)}receive(t,e){return A(this,Ge).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){A(this,Ge).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,Ge).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,Ge).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,Ge).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){se(this,ur,!1),ve(this,In,yo).call(this),this.removeAllListeners(),se(this,Yr,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,be).close(1e3,"Sockrates disconnect method called.")}}be=new WeakMap,Sn=new WeakMap,ye=new WeakMap,Oe=new WeakMap,br=new WeakMap,Ge=new WeakMap,ur=new WeakMap,Yr=new WeakMap,vs=new WeakMap,yn=new WeakMap,Hs=new WeakMap,Yu=new WeakSet,VT=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)://.")},po=new WeakSet,hd=function(s,t){A(this,Oe).error("Error:",{error:s}),A(this,Ge).emit("errored",{error:s}),t==null||t(s)},Qu=new WeakSet,LT=function(s){if(ve(this,kd,th).call(this),s.data===vO){A(this,Oe).debug("Received ping from server"),ve(this,So,bd).call(this,EO);return}const t=OT.decode(s.data),{id:e,payload:r}=t;A(this,Oe).debug("Received message",{event:t.event,messageID:e}),A(this,Ge).emit(t.event.toString(),{id:e,payload:r})},Xu=new WeakSet,hg=function(){return A(this,be).readyState===1},Rd=new WeakSet,Zu=function(s,t){se(this,Yr,{reason:t,code:s}),A(this,Ge).emit("disconnected",{code:s,reason:t})},eh=new WeakSet,xT=function(){const{reason:s,code:t}=A(this,Yr);t&&t!==1e3&&A(this,ur)&&A(this,ye).autoReconnect&&!A(this,vs)&&(A(this,Oe).debug(`Triggering reconnection due to ${s}.`),A(this,Ge).emit("reconnecting"),ve(this,To,pd).call(this))},To=new WeakSet,pd=async function(s=!0){if(s&&A(this,vs)){A(this,Oe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,vs)||A(this,Hs).reset(),A(this,ye).maxReconnectionAttempts!==null&&A(this,Hs).getAttempts()>=A(this,ye).maxReconnectionAttempts){A(this,Ge).emit("failed"),se(this,vs,!1);return}se(this,vs,!0),ve(this,vo,Id).call(this),ve(this,In,yo).call(this);try{if(await A(this,Hs).wait(),A(this,ur)===!1)return;if(A(this,Oe).debug(`Reconnection attempt ${A(this,Hs).getAttempts()}`),A(this,Ge).emit("reconnectAttempt",{attempt:A(this,Hs).getAttempts()}),await this.connect(),!ve(this,Xu,hg).call(this))throw Error("Reconnect Failed");se(this,vs,!1),se(this,Yr,{code:void 0,reason:void 0}),A(this,Ge).emit("reconnected")}catch(t){A(this,Oe).debug("Failed to reconnect."),A(this,Ge).emit("reconnectFailure",{attempt:A(this,Hs).getAttempts()}),ve(this,To,pd).call(this,!1)}},So=new WeakSet,bd=function(s){try{return A(this,be).send(s),!0}catch(t){return A(this,Oe).error(t.message),!1}},kd=new WeakSet,th=function(){this.config.disconnectOnPingTimeout&&(A(this,Oe).debug("Resetting ping timeout"),ve(this,In,yo).call(this),se(this,yn,setTimeout(()=>{var s;A(this,Oe).debug("Disconnecting the socket due to ping timeout"),se(this,ur,!0);const t=3002,e="Ping timeout";(s=A(this,be))==null||s.close(t,e),ve(this,Rd,Zu).call(this,t,e)},A(this,ye).pingTimeout)))},In=new WeakSet,yo=function(){A(this,yn)&&(clearTimeout(A(this,yn)),se(this,yn,void 0))},vo=new WeakSet,Id=function(){A(this,be)&&(A(this,be).onopen=void 0,A(this,be).onerror=void 0,A(this,be).onmessage=void 0,A(this,be).onclose=void 0)};var PO=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,Hl=(s,t,e,r)=>{for(var i=r>1?void 0:r?CO(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&&PO(t,e,i),i};const pg=65535,wO=3e3;var Jr,Ee,_e,ke,ts,Qe,Ic,sh,Ac,rh,Og;const UT=(Og=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,_e);g(this,Ic);g(this,Ac);g(this,Jr,void 0);g(this,Ee,void 0);u(this,"roomName");u(this,"authToken");u(this,"capabilities");g(this,ts,void 0);g(this,Qe,void 0);var a;if(!t||!e||!r)throw new w("peerId, meetingId, or authToken can not be empty","0404");m(this,ts,void 0),m(this,Qe,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,Jr,V(this,Ic,sh).call(this,t)),m(this,Ee,new _O(n(this,Jr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,_e,ke).socketJoinAttempted}set joinAttempted(s){n(this,_e,ke).socketJoinAttempted=s}get telemetry(){return n(this,Qe).getValue("telemetry")}get logger(){return n(this,Qe).getValue("logger")}get peerId(){return n(this,Qe).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,Jr,V(this,Ic,sh).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,Ee).updateURL(n(this,Jr))}static getSocketEdgeDomain(s){return en({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,Jr)}async connect(){n(this,_e,ke).socketJoinAttempted=!0,await n(this,Ee).connect(),n(this,_e,ke).socketJoinAttempted=!0,n(this,_e,ke).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,_e,ke).socketJoinAttempted=!1,n(this,Ee).disconnect(),n(this,_e,ke).socketJoinAttempted=!0,n(this,_e,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,Qe).getValue("telemetry").injectContext(r),n(this,Ee).send(s,e!=null?e:V(this,Ac,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 a=i!=null?i:s;return new Promise((o,c)=>{const d=(E,P)=>{n(this,Ee).removeListener(a,E),n(this,Ee).removeListener(pg,P),n(this,Ee).removeListener(kr.errorResponse,P),n(this,Ee).removeListener(Es.errorResponse,P)},l=r!=null?r:V(this,Ac,rh).call(this),h={};n(this,Qe).getValue("telemetry").injectContext(h);const f=({id:E,payload:P})=>{if(l===E){let R;try{const _=RR.fromBinary(P);R=new Error(_.errorMessage)}catch(_){R=new Error("failed to parse error message",{cause:_});try{const x=bb.fromBinary(P);R=new Error(x.message)}catch(x){R=new Error("failed to parse error message",{cause:x})}}c(R),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(pg,f),n(this,Ee).on(kr.errorResponse,f),n(this,Ee).on(Es.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,ts)&&(clearTimeout(n(this,ts)),m(this,ts,void 0)),n(this,_e,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:v.location.country});const{recv:e,send:r}=(i=n(this,_e,ke).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?n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,_e,ke).joinAttempted}):m(this,ts,setTimeout(()=>{n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,_e,ke).joinAttempted}),m(this,ts,void 0)},wO)),n(this,_e,ke).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:v.location.country}),n(this,_e,ke).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,_e,ke).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,_e,ke).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,_e,ke).mediaJoinAttempted}}),n(this,ts)&&(clearTimeout(n(this,ts)),m(this,ts,void 0)),n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,_e,ke).mediaJoinAttempted}),n(this,_e,ke).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:v.location.country}),n(this,Qe).getValue("peerSessionStore").emit(b.SOCKET_SERVICE_FAILED),n(this,_e,ke).updateSocketConnectionState("failed")})}},Jr=new WeakMap,Ee=new WeakMap,_e=new WeakSet,ke=function(){return n(this,Qe).getValue("connectionHandler")},ts=new WeakMap,Qe=new WeakMap,Ic=new WeakSet,sh=function(s){let t=UT.getSocketEdgeDomain(n(this,Qe).getValue("baseURI"));typeof Oa(n(this,Qe),"socket_server_base")=="string"&&(t=Oa(n(this,Qe),"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=>vd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(a).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Ac=new WeakSet,rh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Og);let Bc=UT;Hl([v.trace("SocketService.connect")],Bc.prototype,"connect",1);Hl([v.trace("SocketService.disconnect")],Bc.prototype,"disconnect",1);Hl([v.trace("SocketService.sendMessagePromise")],Bc.prototype,"sendMessagePromise",1);Hl([v.trace("SocketService.sendMessagePromiseWithTimeout")],Bc.prototype,"sendMessagePromiseWithTimeout",1);class RO{constructor(t){u(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=ek.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=Rk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=lf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Bp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return fk.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,ik.toBinary({payloads:t}));return Bp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(L.deleteConnectedRooms,gk.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(L.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 bO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,IO=(s,t,e,r)=>{for(var i=r>1?void 0:r?kO(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&&bO(t,e,i),i},ys;class $T extends Ft{constructor(e){const r=e.getValue("logger");super(r);u(this,"meetings",[]);u(this,"parentMeeting",null);g(this,ys,void 0);m(this,ys,e)}get supportsConnectedMeetings(){return n(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.
13
13
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){return this.validateConnectedMeetingsAction(),await n(this,ys).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()}async createMeetings(e){return this.validateConnectedMeetingsAction(),(await n(this,ys).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),await n(this,ys).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))}async deleteMeetings(e){this.validateConnectedMeetingsAction();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());return await Promise.all(r),await n(this,ys).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction();const a=await n(this,ys).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success&&this.moveSuccessHandler(e,r,i),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction();const a=await n(this,ys).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success&&this.moveSuccessHandler(e,r,i.map(o=>o.id)),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})}}ys=new WeakMap;IO([kt({maxInvocations:60,period:60})],$T.prototype,"getConnectedMeetings",1);var AO=Object.defineProperty,MO=Object.getOwnPropertyDescriptor,Fh=(s,t,e,r)=>{for(var i=r>1?void 0:r?MO(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&&AO(t,e,i),i},ue,Ng;const FT=(Ng=class{constructor(s){u(this,"connectedMeetings");g(this,ue,void 0);m(this,ue,s),this.connectedMeetings=new $T(s)}get telemetry(){return n(this,ue).getValue("telemetry")}get logger(){return n(this,ue).getValue("logger")}static init(s){const t=new FT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(L.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(L.transferPeer,this.handleTransferPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(L.movedPeer,this.handleMovedPeer.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(L.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){const t=n(this,ue).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return 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.
14
14
  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,ue).getValue("self").videoEnabled,audio:n(this,ue).getValue("self").audioEnabled};try{n(this,ue).getValue("self").cleanupEvents(),await n(this,ue).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,ue).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 HT.init({...n(this,ue).getValue("options"),cachedUserDetails:null,defaults:{...n(this,ue).getValue("options").defaults,...e,mediaHandler:n(this,ue).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,ue).getValue("self");r.self.setName(n(this,ue).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,ue).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,ue).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ue).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,ue).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})}},ue=new WeakMap,Ng);let ql=FT;Fh([v.trace("ConnectedMeetingsController.getConnectedMeetings")],ql.prototype,"getConnectedMeetings",1);Fh([v.trace("ConnectedMeetingsController.setupEvents")],ql.prototype,"setupEvents",1);Fh([v.trace("ConnectedMeetingsController.switchMeeting")],ql.prototype,"switchMeeting",1);var DO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,jl=(s,t,e,r)=>{for(var i=r>1?void 0:r?OO(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&&DO(t,e,i),i};const vn=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 D,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(_T(s),Te.isSupported()===!1)throw new w("Browser not supported","0010",c,!0);const d=UM(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 v0(s);s.setValue("connectionHandler",l);const h=vn.createSocketService(s),p=h.connect(),f=d.getUserDetails(),T=d.getPlugins();let E,P="";try{await vn.setupFlagsmith(s)}catch(G){c.error("Failed to setup flagsmith",{error:G})}try{await p}catch(G){c.error("[Controller]: Failed to connect to socket server:",{error:G})}try{({meetingTitle:P}=await d.getRoomNodeData()),E=await f,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(G){c.error("Failed to get room metadata",{error:G})}const R=Nu.init(E.preset,!s.getValue("modules").theme),_=Uu.init(s,R.viewType,E.preset.permissions),x=vn.setupControllers(h,s,E,T,P,R,_);d0(R)&&((D=vn.createRoomNodeClient(s,h).initializeConnection(E.participant.name,i,!1,_))==null||D.catch(ee=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ee})})),v.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:U}=await x;return ow(),new vn(e,U,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:a,logger:o}=s.getAllValues(),c=aw(i),d={entity:mu.PEER,clientId:a,isAnonUser:!a,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...Te.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const h=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?en({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${mu.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 k,Ve,_r;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:(k=f.enableHighBitrate)!=null?k:!1,enableStereo:(Ve=f.enableStereo)!=null?Ve:!1}},...l}),t.setValue("maxPreferredStreams",Te.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,P,R,_,x,U,D,$;const G=new XD(t,s),ee=new RO(s);t.setValue("connectedMeetingsSocketHandler",ee);const Xe=new Fl(t,s),ns=new rs(t,s),si=new iO(s),as=new CT(t,s),I=new nO(t,s),y=new QD(s),C=new rn(t,s),N=await ti.init(t,as,d,o,a);t.setValue("selfController",N);const pe=await wf.init(t,N.self,as,G,i);if(c.participant&&(D=new Er(t,N.self,as)),(_r=c.e2ee)!=null&&_r.enabled&&c.e2ee.manager.init(h,t.getValue("peerSessionStore")),c.chat&&(E=await _s.init(t,ns,C,N.self,D.participants)),c.internals&&(_=await kh.init(t)),c.livestream&&a.viewType===bt.Livestream&&t.getValue("flagsmith").hasFeature(Q.LIVESTREAM)&&(U=new Nf(t,N.self,y)),a.viewType!==bt.Chat){if(c.poll&&(T=await Ef.init(t,N.self,Xe)),c.recording&&(x=new If(t,N.self,as)),c.stage&&(P=new Rf(t,si,as,N.self,D.participants)),c.plugin){if(!D)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const Fs=await r;R=await xc.init(t,Fs,I,ns,E==null?void 0:E.chat,N.self,D.participants,i)}if(c.connectedMeetings&&($=await ql.init(t)),c.pip){const Fs=await fu._init(t,N.self);t.setValue("pip",Fs)}}const O={storesManager:new uD(t,I),pollController:T,selfController:N,metaController:pe,chatController:E,stageController:P,pluginController:R,recordingController:x,internalsController:_,livestreamController:U,participantController:D,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:O}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return ET(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Bc(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Hc=vn;jl([v.trace("Controller.init")],Hc,"init",1);jl([v.trace("setupFlagsmith")],Hc,"setupFlagsmith",1);jl([v.trace("Controller.createRoomNodeClient")],Hc,"createRoomNodeClient",1);jl([v.trace("Controller.createSocketService")],Hc,"createSocketService",1);class NO{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 gg=new NO;function VO(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=hi.baseURI.prod;t&&(a=t);const o=`https://${en({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new w("Invalid auth token","0004")}}var Kr,Yi,Qi,Mc,El,BT;class LO{constructor(){g(this,El);g(this,Kr,new Audio);g(this,Yi,new MediaStream);g(this,Qi,new Map);g(this,Mc,void 0);n(this,Kr).srcObject=n(this,Yi),n(this,Kr).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Qi).has(e.id)||(n(this,Yi).addTrack(e),n(this,Qi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Kr).setSinkId(t)}removeTrack(t){const e=n(this,Qi).get(t);e&&(n(this,Yi).removeTrack(e),n(this,Qi).delete(t))}async play(){return n(this,Kr).srcObject=n(this,Yi),n(this,Kr).play().catch(t=>{V(this,El,BT).call(this,t)})}onError(t){m(this,Mc,t)}}Kr=new WeakMap,Yi=new WeakMap,Qi=new WeakMap,Mc=new WeakMap,El=new WeakSet,BT=function(t){var e;(e=n(this,Mc))==null||e.call(this,t)};var Xi;class xO extends LO{constructor(){super();g(this,Xi,void 0);m(this,Xi,new Map)}addParticipantTrack(e,r){n(this,Xi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Xi).get(e);r&&this.removeTrack(r),n(this,Xi).delete(e)}}Xi=new WeakMap;var UO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,Gl=(s,t,e,r)=>{for(var i=r>1?void 0:r?$O(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&&UO(t,e,i),i},He,Zi,Vg;let Zr=(Vg=class{constructor(t,e){g(this,He,void 0);g(this,Zi,void 0);m(this,Zi,t),m(this,He,e)}get peerId(){return n(this,Zi).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:gr.v4(),a=hr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Hf(o);return c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var T,E,P,R,_,x,U;Te.init();const{mediaHandler:e}=(T=t.defaults)!=null?T:{},r=(e==null?void 0:e.peerId)||((P=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?P:gr.v4()),{authToken:i,baseURI:a}=t,{meetingId:o,...c}=VO(i,a);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=Zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),h=d.getValue("logger");zT(h),gg.init(h),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(_=(R=t.modules)==null?void 0:R.tracing)!=null?_:!0),h.init(d),h.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(x=t.authToken)==null?void 0:x.slice(0,10)}...
15
- ${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Hc.init(d),f=new Zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=hr.createContext(t,e),o={...YC,...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",QC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Ps(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.1-staging.2"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new xO),a}async join(){const{selfController:t}=n(this,He);return t.self.roomJoined?null:t.joinRoom()}async leave(t){gg.cleanup(),n(this,Zi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,He);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,He).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,He).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,He).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,He).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,He).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,He).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,He).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,He).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,He).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,He).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,He).stageController)==null?void 0:t.stage}get stores(){return n(this,He).storesManager}get audio(){return n(this,Zi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,He).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},He=new WeakMap,Zi=new WeakMap,Vg);Gl([ct("0002"),vr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1);Gl([ct("0003")],Zr.prototype,"leave",1);Gl([ct("0001"),vr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1);Zr=Gl([ct("0000")],Zr);const HT=Zr;module.exports=HT;
15
+ ${(U=t.authToken)==null?void 0:U.slice(-10)}`}});const p=await Hc.init(d),f=new Zr(d,p);return d.setValue("meeting",f),f}static setupContext(t,e,r,i){var d,l;const a=hr.createContext(t,e),o={...YC,...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",QC({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",Ps(e.cachedUserDetails)),a.setValue("sdkVersion","1.2.1-staging.3"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new xO),a}async join(){const{selfController:t}=n(this,He);return t.self.roomJoined?null:t.joinRoom()}async leave(t){gg.cleanup(),n(this,Zi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,He);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,He).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,He).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,He).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,He).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,He).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,He).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,He).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,He).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,He).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,He).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,He).stageController)==null?void 0:t.stage}get stores(){return n(this,He).storesManager}get audio(){return n(this,Zi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,He).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},He=new WeakMap,Zi=new WeakMap,Vg);Gl([ct("0002"),vr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Zr.prototype,"join",1);Gl([ct("0003")],Zr.prototype,"leave",1);Gl([ct("0001"),vr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Zr,"init",1);Zr=Gl([ct("0000")],Zr);const HT=Zr;module.exports=HT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.2.1-staging.2",
3
+ "version": "1.2.1-staging.3",
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",
@@ -18,7 +18,7 @@
18
18
  }
19
19
  },
20
20
  "./inlined": {
21
- "default": "./dist/index.iife.js",
21
+ "default": "./dist/browser.js",
22
22
  "types": "./dist/index.d.ts",
23
23
  "typesVersions": {
24
24
  "<4.0": {