@cloudflare/realtimekit 1.1.0-staging.23 → 1.1.0-staging.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -19,4 +19,4 @@ slogScale: ${n}, isVoice: ${r}, minEnergy: ${a(this,Ur)},
19
19
  maxEnergy: ${a(this,Ln)}`),n===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Ur)||n<a(this,Ur))&&f(this,Ur,n),(!a(this,Ln)||n>a(this,Ln))&&f(this,Ln,n),{energy:(n-a(this,Ur))/(a(this,Ln)-a(this,Ur))*10||0,isVoice:r})},dl=new WeakSet,Xh=function(t){return t<5},Zh=new WeakSet,iy=function(t=a(this,Gs)){var e;if(!a(this,Wi)||!t){a(this,qs).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Wi)}`);return}const i={producerId:a(this,Wi),energy:Math.round(t),silent:U(e=ll,dl,Xh).call(e,t)};f(this,Bo,i.silent),this.reportRequest(i)},ep=new WeakSet,ry=function(t){const e=Math.log10(t);return Math.round(e)},g(tp,dl),g(tp,ep);const dO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),r=i.writable.getWriter(),n=48e3,s=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const m=new Float32Array(s*o),v=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:m});c+=s/n*1e6,yield r.ready,yield r.write(v)}catch(m){d&&clearInterval(d),r.releaseLock(),i.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([i]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch(i){}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const r=i.createOscillator();r.frequency.value=0,r.type="sine";const n=i.createGain();n.gain.value=0,r.connect(n);const s=i.createMediaStreamDestination();n.connect(s),r.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch(i){return}},lO=(t=!1)=>{var e,i;const r=new MediaStream().getVideoTracks()[0],n=document.createElement("canvas");n.height=(e=r==null?void 0:r.getSettings().height)!=null?e:720,n.width=(i=r==null?void 0:r.getSettings().width)!=null?i:1280;const s=n.getContext("2d");s.fillStyle="black",s.fillRect(0,0,n.width,n.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,n.width,n.height)},1e3);const o=n.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,he=(t,e,i,r)=>{for(var n=r>1?void 0:r?hO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&uO(e,i,n),n};const Yt=["video/VP9","video/VP8"];var ul,hl,Pt,J,Wo,cr,Ut,$s,Js,Ks,pl,Ci,Fr,jo,zs,Ys,Ft,Qt,xn,Qs,ip,ny,rp,sy,np,ay,ml,sp,ap,op,oy,cp,cy,dp,dy,lp,ly,gt,Rt,Xs,Ho,up,uy,hp,hy,pp,py;const my=(op=class{constructor(t,e,i){g(this,xn),g(this,ip),g(this,rp),g(this,np),g(this,ml),g(this,cp),g(this,dp),g(this,lp),g(this,gt),g(this,Xs),g(this,up),g(this,hp),g(this,pp),p(this,"context"),p(this,"authToken"),p(this,"e2ee"),g(this,ul,void 0),g(this,hl,void 0),g(this,Pt,void 0),g(this,J,void 0),g(this,Wo,void 0),g(this,cr,void 0),g(this,Ut,void 0),g(this,$s,void 0),g(this,Js,void 0),g(this,Ks,void 0),g(this,pl,void 0),g(this,Ci,null),g(this,Fr,void 0),g(this,jo,void 0),g(this,zs,void 0),g(this,Ys,void 0),g(this,Ft,void 0),g(this,Qt,void 0);var r,n;this.context=t;const{socket:s}=i;this.mediaJoined=!1,f(this,zs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Ys,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,cr,e),f(this,Pt,s),f(this,$s,!1),f(this,J,new aO(t,s,e)),f(this,Ut,a(this,J).events),f(this,Fr,new Set),f(this,Ft,new Map),f(this,Js,!1),f(this,Ks,new fh(t.getValue("logger"))),e===Ae.CF&&!navigator.isReactNative&&f(this,Qt,new tp(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,pl,gu(()=>u(this,null,function*(){if(!a(this,xn,Qs).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,hl),a(this,ul),!0,!0);o&&(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,xn,Qs).mediaJoined}set mediaJoined(t){a(this,xn,Qs).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Ft).clear(),a(this,Fr).clear(),f(this,Ci,null),a(this,Ks).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,Ks,new fh)}joinRoom(t,e){return u(this,arguments,function*(i,r,n=!1,s=!1,o={}){a(this,xn,Qs).mediaJoinAttempted=!0,f(this,$s,!0),n&&this.reset();try{return yield a(this,Ks).push(()=>U(this,ip,ny).call(this,i,r,s,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,r,n=!1,s={}){return a(this,Ci)?a(this,Ci):(f(this,Ci,(()=>u(this,null,function*(){try{yield U(this,ml,sp).call(this,i,r,n,s)}catch(o){throw f(this,Ci,null),o}}))()),a(this,Ci))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,J).stopAllTransports(),f(this,Js,!1),a(this,xn,Qs).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,Pt).sendMessagePromise(a(this,Ut).leaveRoom,lI.toBinary(e));(t=XI.fromBinary(i.payload))!=null&&t.closed||this.logger.warn("weird state on peer closed and should not happen")}catch(i){this.logger.error("error on sending leave room request",{error:i})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()})}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,r)=>{const n=a(this,J).producerIdToConsumerIdMap.get(r.producerId);return n?(i.push(n),i):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),i)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?Te.WEBCAM:Te.WEBCAM_BACKUP,r=U(this,gt,Rt).call(this,i);if(r){const h=yield r;if(a(this,J).producers.has(h)){const m=a(this,J).producers.get(h);if(!m.closed)return yield m.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Yt.filter(h=>h!==e)),s=U(this,pp,py).call(this,t,n),o=Xn(this.context,"disableSimulcast"),c=a(this,cr)===Ae.CF?Z.ENABLE_CF_SIMULCAST:Z.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,cr)}`),s.encodings=z1(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,cr)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(s.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ft).delete(i)},l=a(this,J).createProducer(s,d);return U(this,Xs,Ho).call(this,i,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const r=Yt.filter(n=>{var s,o;return((o=(s=a(this,Wo).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,Ys).get(n).size>0});return r.length===0&&r.push(Yt[0]),yield Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const r={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ke.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ft).delete(Te.SCREENSHARE_VIDEO),a(this,Ft).delete(Te.SCREENSHARE_AUDIO)},s=a(this,J).createProducer(r,n);U(this,Xs,Ho).call(this,Te.SCREENSHARE_VIDEO,s.then(c=>c.id));let o;if(i){const c={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ke.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,cr)!==Ae.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,Xs,Ho).call(this,Te.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([s,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=U(this,gt,Rt).call(this,Te.MIC);if(e){const s=yield e;if(a(this,J).producers.has(s)){const o=a(this,J).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Qt)&&(a(this,Qt).audioTrack=t,a(this,Qt).producerId=s,a(this,Qt).start());return}yield a(this,J).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=U(this,hp,hy).call(this,t),r=()=>{a(this,Ft).delete(Te.MIC)},n=a(this,J).createProducer(i,r);U(this,Xs,Ho).call(this,Te.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,Qt)&&(a(this,Qt).audioTrack=s.track,a(this,Qt).producerId=s.id,a(this,Qt).start())})}catch(e){throw new I(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,gt,Rt).call(this,Te.MIC),i=a(this,J).producers.get(e);if(!i){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Qt))==null||t.stop();const r={producerId:i.id,pause:!0};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,Yc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,gt,Rt).call(this,Te.WEBCAM),e=yield U(this,gt,Rt).call(this,Te.WEBCAM_BACKUP),i=a(this,J).producers.get(t),r=a(this,J).producers.get(e);if(!i&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,Yc.toBinary(o))};i&&(i.pause(),n(i)),r&&(r.pause(),n(r))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,gt,Rt).call(this,Te.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,Yc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=Te.WEBCAM){const e=yield U(this,gt,Rt).call(this,t),i=a(this,J).producers.get(e);if(!i){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,i);const r={producerId:i.id,pause:!1};a(this,Pt).sendMessage(a(this,Ut).toggleProducer,Yc.toBinary(r))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Te.WEBCAM:Te.WEBCAM_BACKUP,i=yield U(this,gt,Rt).call(this,e);U(this,up,uy).call(this,e),i&&(yield a(this,J).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,gt,Rt).call(this,Te.MIC);e&&(yield a(this,J).closeProducer(e)),(t=a(this,Qt))==null||t.stop(),a(this,Ft).delete(Te.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,gt,Rt).call(this,Te.SCREENSHARE_VIDEO),e=yield U(this,gt,Rt).call(this,Te.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,Fr).clear(),a(this,Ft).delete(Te.SCREENSHARE_VIDEO),a(this,Ft).delete(Te.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const i=yield U(this,gt,Rt).call(this,Te.WEBCAM),r=yield U(this,gt,Rt).call(this,Te.WEBCAM_BACKUP);yield a(this,J).closeProducer(i,{stopTrack:!1}),yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield U(this,gt,Rt).call(this,Te.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const i={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,Pt).sendMessagePromise(a(this,Ut).globalPinPeer,wI.toBinary(e))}catch(i){this.logger.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,Fr).add(t.consumerPeerId),a(this,Fr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(r=>this.getConsumers().get(r));a(this,J).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,Pt).on(a(this,Ut).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:r,producerState:n}=PC.fromBinary(t);if(r===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Ni.AUDIO?"audio/opus":"video/VP8"),n.kind===Ni.VIDEO&&!n.screenShare&&((i=(e=a(this,Wo).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Yt[0]))>=0&&a(this,zs).get(Yt[0]).has(r)&&n.mimeType!==Yt[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:H(V({},n),{kind:n.kind===Ni.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Pt).on(a(this,Ut).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:r,pause:n,producerId:s}}=pf.fromBinary(t),o=r===Ni.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${n} payload: ${JSON.stringify(pf.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(o==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:n,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==n&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${n}`),n?(c.pause(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,Pt).on(a(this,Ut).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Eu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Fr).delete(e),a(this,J).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,Pt).on(a(this,Ut).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=AC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:e,producerId:i});const r=a(this,J).producerIdToConsumerIdMap.get(i);if(!r){this.logger.warn(`no consumer found for producer:${i}`);return}this.logger.info(`closing consumer ${r}, producer id: ${i}`),a(this,J).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,J).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:r})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,Pt).on(a(this,Ut).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,$s)&&!a(this,Js)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,pl).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,i)=>{const r=a(this,J).consumers.get(i);r&&this.context.getValue("peerSessionStore").emit(R.CONSUMER_SCORE_UPDATE,{id:i,kind:r.kind,peerId:r.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,i)=>{const r=Array.from(a(this,J).producers.values()).find(n=>n.id===i);r&&this.context.getValue("peerSessionStore").emit(R.PRODUCER_SCORE_UPDATE,{id:i,kind:r.kind,appData:r.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,r,n,s;for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((r=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,Ys).get(c).add(t);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((s=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,zs).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,zs).forEach(e=>e.delete(t)),a(this,Ys).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===Yt[0])&&this.disableWebcam(i)}))}},ul=new WeakMap,hl=new WeakMap,Pt=new WeakMap,J=new WeakMap,Wo=new WeakMap,cr=new WeakMap,Ut=new WeakMap,$s=new WeakMap,Js=new WeakMap,Ks=new WeakMap,pl=new WeakMap,Ci=new WeakMap,Fr=new WeakMap,jo=new WeakMap,zs=new WeakMap,Ys=new WeakMap,Ft=new WeakMap,Qt=new WeakMap,xn=new WeakSet,Qs=function(){return this.context.getValue("connectionHandler")},ip=new WeakSet,ny=function(t,e,i,r){return u(this,null,function*(){f(this,hl,t);try{return a(this,Ci)?yield a(this,Ci):yield U(this,ml,sp).call(this,t,e,i,r),U(this,np,ay).call(this,e),{roomJoined:yield U(this,rp,sy).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{f(this,Ci,null)}})},rp=new WeakSet,sy=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,ul,t.roomUuid),f(this,Js,!0),f(this,$s,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},np=new WeakSet,ay=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:H(V({},ke.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(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},ml=new WeakSet,sp=function(t,e,i,r){return u(this,null,function*(){var n,s;try{(s=a(this,jo))!=null||f(this,jo,U(n=my,ap,oy).call(n));const o=U(this,cp,cy).call(this);yield U(this,dp,dy).call(this,t,e,i,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,lp,ly).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},ap=new WeakSet,oy=function(){const{ipInfo:t}=ht();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},cp=new WeakSet,cy=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=JD(e);return f(this,Wo,i),i},dp=new WeakSet,dy=function(t,e,i,r){return u(this,null,function*(){yield Nv((n,s)=>u(this,null,function*(){if(!a(this,Pt).isConnected){s(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,J).socketHandler.joinRoom(e,t,r,i,a(this,jo))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},lp=new WeakSet,ly=function(t){return u(this,null,function*(){if(!(a(this,cr)===Ae.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(lO(!1))),t.canProduceAudio===G.Allowed){const i=dO(!1);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},gt=new WeakSet,Rt=function(t){return a(this,Ft).get(t)},Xs=new WeakSet,Ho=function(t,e){return a(this,Ft).set(t,e)},up=new WeakSet,uy=function(t){return a(this,Ft).delete(t)},hp=new WeakSet,hy=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,cr)!==Ae.CF}},pp=new WeakSet,py=function(t,e){return{track:t,codecOptions:e?e.map(i=>({name:i.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(op,ap),op);let ce=my;he([E.trace("MediaNodeClient.reset",{country:E.location.country})],ce.prototype,"reset",1),he([E.trace("MediaNodeClient.joinRoom")],ce.prototype,"joinRoom",1),he([E.trace("MediaNodeClient.leaveRoom")],ce.prototype,"leaveRoom",1),he([E.trace("MediaNodeClient.activatePeers")],ce.prototype,"activatePeers",1),he([E.trace("MediaNodeClient.createConsumers")],ce.prototype,"createConsumers",1),he([E.trace("MediaNodeClient.closeConsumers")],ce.prototype,"closeConsumers",1),he([E.trace("MediaNodeClient._shareWebcam")],ce.prototype,"_shareWebcam",1),he([E.trace("MediaNodeClient.shareWebcam")],ce.prototype,"shareWebcam",1),he([E.trace("MediaNodeClient.shareScreen")],ce.prototype,"shareScreen",1),he([E.trace("MediaNodeClient.shareMic")],ce.prototype,"shareMic",1),he([E.trace("MediaNodeClient.pauseMic")],ce.prototype,"pauseMic",1),he([E.trace("MediaNodeClient.pauseWebcam")],ce.prototype,"pauseWebcam",1),he([E.trace("MediaNodeClient.resumeMic")],ce.prototype,"resumeMic",1),he([E.trace("MediaNodeClient.resumeWebcam")],ce.prototype,"resumeWebcam",1),he([E.trace("MediaNodeClient.disableWebcam")],ce.prototype,"disableWebcam",1),he([E.trace("HiveClient.disableMic")],ce.prototype,"disableMic",1),he([E.trace("HiveClient.disableScreenShare")],ce.prototype,"disableScreenShare",1),he([E.trace("MediaNodeClient.muteSelf")],ce.prototype,"muteSelf",1),he([E.trace("MediaNodeClient.resetVideoProducers")],ce.prototype,"resetVideoProducers",1),he([E.trace("MediaNodeClient.changeDisplayName")],ce.prototype,"changeDisplayName",1),he([E.trace("MediaNodeClient.kickPeer")],ce.prototype,"kick",1),he([E.trace("MediaNodeClient.kickAllPeers")],ce.prototype,"kickAll",1),he([E.trace("MediaNodeClient.muteAll")],ce.prototype,"muteAll",1),he([E.trace("MediaNodeClient.muteAllVideo")],ce.prototype,"muteAllVideo",1),he([E.trace("MediaNodeClient.disableAudio")],ce.prototype,"disableAudio",1),he([E.trace("MediaNodeClient.disableVideo")],ce.prototype,"disableVideo",1),he([E.trace("MediaNodeClient.pinPeer")],ce.prototype,"pinPeer",1),he([E.trace("MediaNodeClient.validateScreenShare")],ce.prototype,"validateScreenShare",1);function gy(t,e,i){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const n=new ce(t,e,i);return t.setValue("roomNodeClient",n),n}function fy(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var pO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,Un=(t,e,i,r)=>{for(var n=r>1?void 0:r?mO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&pO(e,i,n),n},Fn,ji,re,Bt,Xt,vy;const yy=(vy=class{constructor(t,e,i,r){g(this,Bt),p(this,"self"),p(this,"authToken"),g(this,Fn,void 0),p(this,"viewType"),g(this,ji,void 0),g(this,re,void 0);const{socket:n}=i,s=t.getValue("authToken");this.self=e,f(this,re,t),this.viewType=r,this.authToken=s,f(this,Fn,n),f(this,ji,i),e.config.viewType!==Mt.Chat&&this.setupEvents()}get peerId(){return a(this,re).getValue("peerId")}get telemetry(){return a(this,re).getValue("telemetry")}get logger(){return a(this,re).getValue("logger")}get mediaJoined(){return a(this,re).getValue("connectionHandler").mediaJoined}static init(t,e,i,r,n){return u(this,null,function*(){const s=ht(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield tt.__init__(t,i,r,n,n.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const m=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(m)}),t.getValue("callstats").devices("AUDIO",m==null?void 0:m.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",m==null?void 0:m.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",m==null?void 0:m.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:ke.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Kg(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new yy(t,d,e,n.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:r,audioEnabled:n,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(r.canProduceAudio===G.Allowed&&n)try{yield a(this,Bt,Xt).shareMic(e),this.self.audioEnabled||a(this,Bt,Xt).pauseMic()}catch(d){this.self.disableAudio()}if(r.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Bt,Xt).shareWebcam(i);d&&d.id!==i.id&&a(this,re).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Bt,Xt).shareWebcam(d)),this.self.videoEnabled||a(this,Bt,Xt).pauseWebcam()}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Bt,Xt))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}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(t){return u(this,null,function*(){a(this,re).getValue("callstats").callEnded(),a(this,Bt,Xt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,re).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,re).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(e=Jr()),a(this,Fn).updateURL(e),a(this,re).getValue("telemetry").resetPeerId(e),ht().setHeader("dyte-tracing-id",e),Ki.remapContext(e,a(this,re)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ji).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ji).on(id.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,re).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,e.patch)})}),a(this,ji).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ji).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ji).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,re).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:r})=>{var n;const s=(n=i==null?void 0:i.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),a(this,re).getValue("peerSessionStore").on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,re).getValue("callstats").audioOff())})),a(this,re).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,re).getValue("callstats").videoOff())})),a(this,re).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,ji).joinRoom(this.self);a(this,ji).socket.flush();const i=Ku(e.stageType);if(a(this,re).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,re).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,i;if(t==="rejected"){try{(e=a(this,Fn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,re).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,re).notify("stageStatus");try{(i=a(this,Fn))==null||i.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}fy(a(this,re)),yield a(this,re).getValue("roomSocketHandler").cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:r,viewType:n,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,re).getAllValues(),{sfu:d}=c;try{if(n===Mt.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}gy(a(this,re),d,{socket:a(this,Fn),peerId:r})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}=this.self.permissions,{roomJoined:v}=(i=yield(e=a(this,Bt,Xt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}))!=null?i:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new I("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,re).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Mt.Webinar)&&a(this,Bt,Xt)&&(a(this,Bt,Xt).mediaJoined&&t!=="disconnected"&&(yield a(this,Bt,Xt).leaveRoom()),!(t==="stageLeft"&&e===Mt.Livestream)&&(a(this,Bt,Xt).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()})}},Fn=new WeakMap,ji=new WeakMap,re=new WeakMap,Bt=new WeakSet,Xt=function(){return a(this,re).getValue("roomNodeClient")},vy);let Br=yy;Un([E.trace("SelfController.resetSelf")],Br.prototype,"resetSelf",1),Un([E.trace("SelfController.setupEvents")],Br.prototype,"setupEvents",1),Un([E.trace("SelfController.joinRoom")],Br.prototype,"joinRoom",1),Un([E.trace("SelfController.leaveRoom")],Br.prototype,"leaveRoom",1),Un([E.trace("SelfController.joinMediaRoom")],Br.prototype,"joinMediaRoom",1),Un([E.trace("SelfController.leaveMediaRoom")],Br.prototype,"leaveMediaRoom",1),Un([E.trace("SelfController.init")],Br,"init",1);var gl;class gO{constructor(e){g(this,gl,void 0),f(this,gl,e)}on(e,i){let r;e===F.roomPeerCount?r=ff.fromBinary.bind(ff):r=Of.fromBinary.bind(Of),a(this,gl).on(e,({payload:n})=>{const s=r(n);return i(s)})}}gl=new WeakMap;var fl,vl;class fO{constructor(e,i){g(this,fl,void 0),g(this,vl,void 0),f(this,fl,i),f(this,vl,e)}get logger(){return a(this,vl).getValue("logger")}on(e,i){let r,n;switch(e){case F.transcript:{r=ku.fromBinary.bind(ku),n=ku.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,fl).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}fl=new WeakMap,vl=new WeakMap;var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,mp=(t,e,i,r)=>{for(var n=r>1?void 0:r?yO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&vO(e,i,n),n},Wr,Go;class yl{constructor(e,i){g(this,Wr,void 0),g(this,Go,void 0),f(this,Wr,i),f(this,Go,e)}get logger(){return a(this,Go).getValue("logger")}get telemetry(){return a(this,Go).getValue("telemetry")}getPolls(){return a(this,Wr).sendMessagePromise(Xi.getPolls)}createPoll(e,i,r=!1,n=!1){const s={anonymous:r,hideVotes:n,question:e,options:i};return a(this,Wr).sendMessage(Xi.createPoll,SA.toBinary(s))}votePoll(e,i){const r={index:i,pollId:e};return a(this,Wr).sendMessage(Xi.votePoll,EA.toBinary(r))}on(e,i){let r,n;switch(e){case Xi.updatePoll:case Xi.createPoll:case Xi.votePoll:{r=Vu.fromBinary.bind(Vu),n=Vu.create();break}}a(this,Wr).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Wr).removeListeners(e)}}Wr=new WeakMap,Go=new WeakMap,mp([E.trace("PollSocketHandler.getPolls")],yl.prototype,"getPolls",1),mp([E.trace("PollSocketHandler.createPoll")],yl.prototype,"createPoll",1),mp([E.trace("PollSocketHandler.votePoll")],yl.prototype,"votePoll",1);var SO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,EO=(t,e,i,r)=>{for(var n=r>1?void 0:r?TO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&SO(e,i,n),n},di;class Sy{constructor(e,i){p(this,"socket"),g(this,di,void 0),f(this,di,e),this.socket=i,this.handleSocketEvents(),a(this,di).setValue("roomSocketHandler",this)}get telemetry(){return a(this,di).getValue("telemetry")}get logger(){return a(this,di).getValue("logger")}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch(i){this.logger.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const r={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(F.joinRoom,aP.toBinary(r));try{const{peer:s}=ts.fromBinary((yield n).payload);a(this,di).getValue("connectionHandler").socketJoined=!0,a(this,di).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,di).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,di).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:s}}catch(s){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:s}),new I("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return GP.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:r}=i,n=_c(i,["id"]);return H(V({},n),{userId:r})})}catch(e){return[]}})}getRoomPeers(e,i,r){return u(this,null,function*(){let n;try{const s={seachQuery:e,limit:i,offset:r},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,YC.toBinary(s));n=_u.fromBinary(o.payload)}catch(s){this.logger.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=_u.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=_u.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const r=yield this.socket.sendMessagePromise(F.getPeerInfo,Sf.toBinary({peerId:e}));i=ts.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return i})}getRoomState(){return u(this,null,function*(){let e=yf.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomInfo);e=yf.fromBinary(i.payload)}catch(i){this.logger.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=_f.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomStageState);e=_f.fromBinary(i.payload)}catch(i){this.logger.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,wa.toBinary(r))})}broadcastToMeetings(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,wa.toBinary(n))})}broadcastToPeers(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,wa.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,cP.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(F.kick,bf.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,cf.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,YP.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,XP.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const r={updatePeersPresets:[]};return e.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:i})}),this.socket.sendMessagePromise(id.updateUserPreset,CR.toBinary(r))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const i=wa.fromBinary(e);a(this,di).getValue("peerSessionStore").emit(R.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode broadcast message:",i)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const i=wa.fromBinary(e);a(this,di).getValue("peerSessionStore").emit(R.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode peer broadcast message:",i)}})}on(e,i){let r,n;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=ts.fromBinary.bind(ts),n=ts.create();break}case F.getWaitingRoomRequests:{r=(s,o)=>s?wf.fromBinary(s,o):{requests:[]},n=wf.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=xf.fromBinary.bind(xf);break}case id.updateUserPreset:{r=Cf.fromBinary.bind(Cf);break}case fi.peerJoinedBroadcast:case ii.peerJoinedBroadcast:{r=uf.fromBinary.bind(uf);break}case fi.selfJoinComplete:case ii.selfJoinComplete:{r=Tu.fromBinary.bind(Tu);break}case fi.globalPeerPinBroadcast:case ii.globalPeerPinBroadcast:{r=mf.fromBinary.bind(mf);break}case fi.selectedPeer:case ii.selectedPeer:{r=Su.fromBinary.bind(Su);break}case fi.selectedPeerDiff:case ii.selectedPeerDiff:{r=lf.fromBinary.bind(lf);break}case fi.leaveRoom:case ii.leaveRoom:{r=Eu.fromBinary.bind(Eu);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!r)return i(void 0);try{o=r(s)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const r=yield this.socket.sendMessagePromise(id.getUserPresets,TR.toBinary(i)),n=wR.fromBinary(r.payload).peerPresets[0],s=new TextDecoder().decode(n.preset),o=JSON.parse(s).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}})}}di=new WeakMap,EO([E.trace("RoomSocketHandler.joinRoom")],Sy.prototype,"joinRoom",1);var Zt;class kO{constructor(e){g(this,Zt,void 0),f(this,Zt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Zt).sendMessagePromise(F.getStageRequests);return e?Nu.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Zt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,Zt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Zt).sendMessage(F.grantStageAccess,dA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Zt).sendMessage(F.denyStageAccess,uA.toBinary(i))})}joinStage(){return a(this,Zt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Zt).sendMessagePromise(F.leaveStage,Vf.toBinary(i),void 0,F.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Zt).sendMessagePromise(F.leaveStage,Vf.toBinary(i))}on(e,i){let r;switch(e){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=Nf.fromBinary.bind(Nf);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=Nu.fromBinary.bind(Nu);break}case F.peerStageStatusUpdate:{r=gf.fromBinary.bind(gf);break}}a(this,Zt).on(e,({payload:n,id:s})=>{if(!n||!r)return i(void 0,s);const o=r(n);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Zt).sendMessagePromise(F.getPeerInfo,Sf.toBinary({peerId:e}));return ts.fromBinary(i.payload)})}}Zt=new WeakMap;var it,Sl;class bO{constructor(e,i){g(this,it,void 0),g(this,Sl,void 0),f(this,it,i),f(this,Sl,e)}get logger(){return a(this,Sl).getValue("logger")}addPlugin(e,i){a(this,it).sendMessage($.addPlugin,IM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,it).sendMessage($.removePlugin,PM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise($.getPlugins);return e?QM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,r){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage($.customPluginEventToRoom,UM.toBinary(n),r)}customPluginEventToPeers(e,i,r,n){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,it).sendMessage($.customPluginEventToPeers,BM.toBinary(s),n)}enablePluginForRoom(e,i){a(this,it).sendMessage($.enablePluginForRoom,MM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,r){a(this,it).sendMessage($.enablePluginForPeers,NM.toBinary({pluginId:e,peerIds:i}),r)}disablePluginForRoom(e,i){a(this,it).sendMessage($.disablePluginForRoom,DM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,r){a(this,it).sendMessage($.disablePluginForPeers,LM.toBinary({pluginId:e,peerIds:i}),r)}storeInsertKeys(e,i,r,n){const s={pluginId:e,storeName:i,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,it).sendMessage($.storeInsertKeys,Rf.toBinary(s),n)}storeGetKeys(e,i,r,n){const s={pluginId:e,storeName:i,getKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeGetKeys,GM.toBinary(s),n)}storeDeleteKeys(e,i,r,n){const s={pluginId:e,storeName:i,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeDeleteKeys,$M.toBinary(s),n)}storeDelete(e,i,r){a(this,it).sendMessage($.storeDelete,KM.toBinary({pluginId:e,storeName:i}),r)}getPluginDataOld(e,i){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,r){const n={pluginId:e,storeName:i,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,it).sendMessage($.storeInsertKeys,Rf.toBinary(n))}on(e,i){let r;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{r=Ou.fromBinary.bind(Ou);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{r=Mf.fromBinary.bind(Mf);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{r=Df.fromBinary.bind(Df);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{r=Af.fromBinary.bind(Af);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=r(n);return i(o,s)})}}it=new WeakMap,Sl=new WeakMap;var wO=Object.defineProperty,_O=(t,e,i)=>e in t?wO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,IO=(t,e,i)=>(_O(t,typeof e!="symbol"?e+"":e,i),i),gp=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(gp(t,e,"read from private field"),i?i.call(t):e.get(t)),_e=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},de=(t,e,i,r)=>(gp(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),Pe=(t,e,i)=>(gp(t,e,"access private method"),i),Tl={},CO={get exports(){return Tl},set exports(t){Tl=t}},Zs=typeof Reflect=="object"?Reflect:null,Ty=Zs&&typeof Zs.apply=="function"?Zs.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},El;Zs&&typeof Zs.ownKeys=="function"?El=Zs.ownKeys:Object.getOwnPropertySymbols?El=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:El=function(t){return Object.getOwnPropertyNames(t)};function PO(t){console&&console.warn&&console.warn(t)}var Ey=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}CO.exports=pe,Tl.once=DO,pe.EventEmitter=pe,pe.prototype._events=void 0,pe.prototype._eventsCount=0,pe.prototype._maxListeners=void 0;var ky=10;function kl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return ky},set:function(t){if(typeof t!="number"||t<0||Ey(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ky=t}}),pe.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},pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ey(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function by(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return by(this)},pe.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var r=t==="error",n=this._events;if(n!==void 0)r=r&&n.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=n[t];if(c===void 0)return!1;if(typeof c=="function")Ty(c,this,e);else for(var d=c.length,l=Py(c,d),i=0;i<d;++i)Ty(l[i],this,e);return!0};function wy(t,e,i,r){var n,s,o;if(kl(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),n=by(t),n>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,PO(c)}return t}pe.prototype.addListener=function(t,e){return wy(this,t,e,!1)},pe.prototype.on=pe.prototype.addListener,pe.prototype.prependListener=function(t,e){return wy(this,t,e,!0)};function RO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _y(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},n=RO.bind(r);return n.listener=i,r.wrapFn=n,n}pe.prototype.once=function(t,e){return kl(e),this.on(t,_y(this,t,e)),this},pe.prototype.prependOnceListener=function(t,e){return kl(e),this.prependListener(t,_y(this,t,e)),this},pe.prototype.removeListener=function(t,e){var i,r,n,s,o;if(kl(e),r=this._events,r===void 0)return this;if(i=r[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,n=s;break}if(n<0)return this;n===0?i.shift():MO(i,n),i.length===1&&(r[t]=i[0]),r.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},pe.prototype.off=pe.prototype.removeListener,pe.prototype.removeAllListeners=function(t){var e,i,r;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var n=Object.keys(i),s;for(r=0;r<n.length;++r)s=n[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function Iy(t,e,i){var r=t._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?i?[n.listener||n]:[n]:i?AO(n):Py(n,n.length)}pe.prototype.listeners=function(t){return Iy(this,t,!0)},pe.prototype.rawListeners=function(t){return Iy(this,t,!1)},pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Cy.call(t,e)},pe.prototype.listenerCount=Cy;function Cy(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}pe.prototype.eventNames=function(){return this._eventsCount>0?El(this._events):[]};function Py(t,e){for(var i=new Array(e),r=0;r<e;++r)i[r]=t[r];return i}function MO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function AO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function DO(t,e){return new Promise(function(i,r){function n(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),i([].slice.call(arguments))}Ry(t,e,s,{once:!0}),e!=="error"&&OO(t,n,{once:!0})})}function OO(t,e,i){typeof t.on=="function"&&Ry(t,"error",e,i)}function Ry(t,e,i,r){if(typeof t.on=="function")r.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){r.once&&t.removeEventListener(e,n),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class NO extends y{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 My=new NO;class Ay{static encode(e){return My.toBinary(e)}static decode(e){return My.fromBinary(new Uint8Array(e))}}function VO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var jr;class LO{constructor(e={}){IO(this,"opts"),_e(this,jr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,jr,0)}wait(){return u(this,null,function*(){de(this,jr,N(this,jr)+1);const e=VO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*JS(2,N(this,jr))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,jr)}reset(){de(this,jr,0)}}jr=new WeakMap;const Hr={debug:0,info:1,warn:2,error:3};var Bn,Wn;class xO{constructor(e){_e(this,Bn,void 0),_e(this,Wn,void 0),de(this,Bn,console),de(this,Wn,e)}debug(...e){Hr[N(this,Wn)]>Hr.debug||N(this,Bn).debug("[Sockrates]:",...e)}info(...e){Hr[N(this,Wn)]>Hr.info||N(this,Bn).info("[Sockrates]:",...e)}warn(...e){Hr[N(this,Wn)]>Hr.warn||N(this,Bn).warn("[Sockrates]:",...e)}error(...e){Hr[N(this,Wn)]>Hr.error||N(this,Bn).error("[Sockrates]:",...e)}}Bn=new WeakMap,Wn=new WeakMap;var Dy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Dy||{});const UO="2",FO="3";var Ne,ea,Re,We,Gr,rt,dr,qr,Pi,ta,lr,fp,Oy,qo,bl,vp,Ny,yp,Vy,wl,Sp,Tp,Ly,$o,_l,Jo,Il,Cl,Ep,ia,Ko,zo,Pl;class BO{constructor(e,i){var r;_e(this,fp),_e(this,qo),_e(this,vp),_e(this,yp),_e(this,wl),_e(this,Tp),_e(this,$o),_e(this,Jo),_e(this,Cl),_e(this,ia),_e(this,zo),_e(this,Ne,void 0),_e(this,ea,void 0),_e(this,Re,void 0),_e(this,We,void 0),_e(this,Gr,void 0),_e(this,rt,void 0),_e(this,dr,void 0),_e(this,qr,void 0),_e(this,Pi,void 0),_e(this,ta,void 0),_e(this,lr,void 0);var n,s,o,c,d,l,h,m,v;de(this,ea,e),de(this,Gr,[]),de(this,rt,new Tl),de(this,dr,!0),de(this,Pi,!1),de(this,Re,i!=null?i:{}),(n=N(this,Re)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,Re)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Re)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Re)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Re)).debug!=null||(d.debug=!0),(l=N(this,Re)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Re)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=N(this,Re)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(v=N(this,Re)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,qr,{code:void 0,reason:void 0}),de(this,We,(r=N(this,Re).logger)!=null?r:new xO(N(this,Re).debug?"debug":"info")),de(this,lr,new LO)}get readyState(){var e;return(e=N(this,Ne))==null?void 0:e.readyState}get url(){return N(this,ea)}updateURL(e){de(this,ea,e),Pe(this,Tp,Ly).call(this)}get config(){return N(this,Re)}get sendQueue(){return N(this,Gr)}flush(){if(!N(this,Re).queueOnDisconnect)return!1;const e=[];return N(this,Gr).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),de(this,Gr,e),N(this,Gr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,We).debug("Websocket was already connecting or connected.");return}if(N(this,dr)!==!1)return new Promise((i,r)=>{Pe(this,ia,Ko).call(this),Pe(this,zo,Pl).call(this);try{de(this,Ne,new WebSocket(Pe(this,fp,Oy).call(this,N(this,ea)))),N(this,Ne).binaryType="arraybuffer",N(this,We).debug("Connecting");const n=setTimeout(()=>{N(this,We).debug("Connection timeout. Closing socket"),de(this,dr,!0),Pe(this,zo,Pl).call(this),N(this,Ne).close(3001,"Connection Timeout"),N(this,Re).autoReconnect&&!N(this,Pi)&&(N(this,rt).emit("reconnecting"),Pe(this,$o,_l).call(this)),r(new Error("Connection timed out!"))},N(this,Re).connectionTimeout);N(this,Ne).onopen=()=>{N(this,We).debug(`Ready State: ${Dy[N(this,Ne).readyState]}`),n&&clearTimeout(n),Pe(this,Cl,Ep).call(this),de(this,qr,{code:void 0,reason:void 0}),N(this,rt).emit("connected"),N(this,Re).flushOnReconnect&&this.flush(),i()},N(this,Ne).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;r(c),N(this,We).debug("Socket closed. Close event:",{event:s}),N(this,We).debug(`Connection closed code: ${o}`),N(this,We).debug(`Connection closed reason: ${c}`),N(this,Pi)||Pe(this,wl,Sp).call(this,o,c)}catch(o){Pe(this,qo,bl).call(this,o)}},N(this,Ne).onerror=s=>{Pe(this,qo,bl).call(this,s)},N(this,Ne).onmessage=s=>Pe(this,vp,Ny).call(this,s)}catch(n){Pe(this,qo,bl).call(this,n,r)}})})}send(e,i,r,n){const s={event:e,id:i,payload:r,metadata:n};if(N(this,Re).queueOnDisconnect&&(!N(this,Ne)||N(this,Ne).readyState!==1))return N(this,We).debug("Queuing message since socket is not connected!",s),N(this,Gr).push(s),!1;const o=Ay.encode(s);return Pe(this,Jo,Il).call(this,o)}emit(e,i,r,n){return this.send(e,i,r,n)}sendRaw(e){return Pe(this,Jo,Il).call(this,e)}receive(e,i){return N(this,rt).on(e.toString(),i)}on(e,i){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,rt).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,rt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,rt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,rt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){de(this,dr,!1),Pe(this,ia,Ko).call(this),this.removeAllListeners(),de(this,qr,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,ea=new WeakMap,Re=new WeakMap,We=new WeakMap,Gr=new WeakMap,rt=new WeakMap,dr=new WeakMap,qr=new WeakMap,Pi=new WeakMap,ta=new WeakMap,lr=new WeakMap,fp=new WeakSet,Oy=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},qo=new WeakSet,bl=function(t,e){N(this,We).error("Error:",{error:t}),N(this,rt).emit("errored",{error:t}),e==null||e(t)},vp=new WeakSet,Ny=function(t){if(Pe(this,Cl,Ep).call(this),t.data===UO){N(this,We).debug("Received ping from server"),Pe(this,Jo,Il).call(this,FO);return}const e=Ay.decode(t.data),{id:i,payload:r}=e;N(this,We).debug("Received message",{event:e.event,messageID:i}),N(this,rt).emit(e.event.toString(),{id:i,payload:r})},yp=new WeakSet,Vy=function(){return N(this,Ne).readyState===1},wl=new WeakSet,Sp=function(t,e){de(this,qr,{reason:e,code:t}),N(this,rt).emit("disconnected",{code:t,reason:e})},Tp=new WeakSet,Ly=function(){const{reason:t,code:e}=N(this,qr);e&&e!==1e3&&N(this,dr)&&N(this,Re).autoReconnect&&!N(this,Pi)&&(N(this,We).debug(`Triggering reconnection due to ${t}.`),N(this,rt).emit("reconnecting"),Pe(this,$o,_l).call(this))},$o=new WeakSet,_l=function(t=!0){return u(this,null,function*(){if(t&&N(this,Pi)){N(this,We).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,Pi)||N(this,lr).reset(),N(this,Re).maxReconnectionAttempts!==null&&N(this,lr).getAttempts()>=N(this,Re).maxReconnectionAttempts){N(this,rt).emit("failed"),de(this,Pi,!1);return}de(this,Pi,!0),Pe(this,zo,Pl).call(this),Pe(this,ia,Ko).call(this);try{if(yield N(this,lr).wait(),N(this,dr)===!1)return;if(N(this,We).debug(`Reconnection attempt ${N(this,lr).getAttempts()}`),N(this,rt).emit("reconnectAttempt",{attempt:N(this,lr).getAttempts()}),yield this.connect(),!Pe(this,yp,Vy).call(this))throw Error("Reconnect Failed");de(this,Pi,!1),de(this,qr,{code:void 0,reason:void 0}),N(this,rt).emit("reconnected")}catch(e){N(this,We).debug("Failed to reconnect."),N(this,rt).emit("reconnectFailure",{attempt:N(this,lr).getAttempts()}),Pe(this,$o,_l).call(this,!1)}})},Jo=new WeakSet,Il=function(t){try{return N(this,Ne).send(t),!0}catch(e){return N(this,We).error(e.message),!1}},Cl=new WeakSet,Ep=function(){this.config.disconnectOnPingTimeout&&(N(this,We).debug("Resetting ping timeout"),Pe(this,ia,Ko).call(this),de(this,ta,setTimeout(()=>{var t;N(this,We).debug("Disconnecting the socket due to ping timeout"),de(this,dr,!0);const e=3002,i="Ping timeout";(t=N(this,Ne))==null||t.close(e,i),Pe(this,wl,Sp).call(this,e,i)},N(this,Re).pingTimeout)))},ia=new WeakSet,Ko=function(){N(this,ta)&&(clearTimeout(N(this,ta)),de(this,ta,void 0))},zo=new WeakSet,Pl=function(){N(this,Ne)&&(N(this,Ne).onopen=void 0,N(this,Ne).onerror=void 0,N(this,Ne).onmessage=void 0,N(this,Ne).onclose=void 0)};var WO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,Rl=(t,e,i,r)=>{for(var n=r>1?void 0:r?jO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&WO(e,i,n),n};const xy=65535,HO=3e3;var jn,Ve,Le,je,Ri,ft,Ml,kp,Al,bp,Uy;const Fy=(Uy=class{constructor(t,{peerId:e,meetingId:i,authToken:r,capabilities:n}){g(this,Le),g(this,Ml),g(this,Al),g(this,jn,void 0),g(this,Ve,void 0),p(this,"roomName"),p(this,"authToken"),p(this,"capabilities"),g(this,Ri,void 0),g(this,ft,void 0);var s;if(!e||!i||!r)throw new I("peerId, meetingId, or authToken can not be empty","0404");f(this,Ri,void 0),f(this,ft,t),this.capabilities=n,this.roomName=i,this.authToken=r,f(this,jn,U(this,Ml,kp).call(this,e)),f(this,Ve,new BO(a(this,jn),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Le,je).socketJoinAttempted}set joinAttempted(t){a(this,Le,je).socketJoinAttempted=t}get telemetry(){return a(this,ft).getValue("telemetry")}get logger(){return a(this,ft).getValue("logger")}get peerId(){return a(this,ft).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,jn,U(this,Ml,kp).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ve).updateURL(a(this,jn))}static getSocketEdgeDomain(t){return rn({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,jn)}connect(){return u(this,null,function*(){a(this,Le,je).socketJoinAttempted=!0,yield a(this,Ve).connect(),a(this,Le,je).socketJoinAttempted=!0,a(this,Le,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Le,je).socketJoinAttempted=!1,a(this,Ve).disconnect(),a(this,Le,je).socketJoinAttempted=!0,a(this,Le,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Ve).readyState===1}catch(t){return!1}}sendMessage(t,e,i){const r={};return a(this,ft).getValue("telemetry").injectContext(r),a(this,Ve).send(t,i!=null?i:U(this,Al,bp).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,i,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:n,protobuf:e,messageId:i,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:r,resp:n}){const s=n!=null?n:t;return new Promise((o,c)=>{const d=(S,k)=>{a(this,Ve).removeListener(s,S),a(this,Ve).removeListener(xy,k),a(this,Ve).removeListener(ii.errorResponse,k),a(this,Ve).removeListener(fi.errorResponse,k)},l=r!=null?r:U(this,Al,bp).call(this),h={};a(this,ft).getValue("telemetry").injectContext(h);const m=({id:S,payload:k})=>{if(l===S){let C;try{const b=jI.fromBinary(k);C=new Error(b.errorMessage)}catch(b){C=new Error("failed to parse error message",{cause:b});try{const M=HC.fromBinary(k);C=new Error(M.message)}catch(M){C=new Error("failed to parse error message",{cause:M})}}c(C),d(v,m)}},v=({id:S,payload:k})=>{l===S&&(o({id:S,payload:k}),d(v,m))};a(this,Ve).on(s,v),a(this,Ve).on(xy,m),a(this,Ve).on(ii.errorResponse,m),a(this,Ve).on(fi.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Ve).send(t,l,i,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Ve).on(t,e)}onStateEvent(t,e){a(this,Ve).on(t,e)}removeListener(t,e){a(this,Ve).removeListener(t,e)}removeListeners(t){a(this,Ve).removeListeners(t)}flush(){return a(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,Ri)&&(clearTimeout(a(this,Ri)),f(this,Ri,void 0)),a(this,Le,je).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:E.location.country});const{recv:r,send:n}=(i=a(this,Le,je).mediaState)!=null?i:{};r!=null&&r.state&&(r==null?void 0:r.state)!==Ms.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==Ms.CONNECTED?a(this,ft).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Le,je).joinAttempted}):f(this,Ri,setTimeout(()=>{a(this,ft).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Le,je).joinAttempted}),f(this,Ri,void 0)},HO)),a(this,Le,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),a(this,Le,je).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Le,je).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Le,je).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Le,je).mediaJoinAttempted}}),a(this,Ri)&&(clearTimeout(a(this,Ri)),f(this,Ri,void 0)),a(this,ft).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Le,je).mediaJoinAttempted}),a(this,Le,je).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),a(this,ft).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Le,je).updateSocketConnectionState("failed")}))}},jn=new WeakMap,Ve=new WeakMap,Le=new WeakSet,je=function(){return a(this,ft).getValue("connectionHandler")},Ri=new WeakMap,ft=new WeakMap,Ml=new WeakSet,kp=function(t){let e=Fy.getSocketEdgeDomain(a(this,ft).getValue("baseURI"));typeof Xn(a(this,ft),"socket_server_base")=="string"&&(e=Xn(a(this,ft),"socket_server_base"));const i=`wss://${e}`,r=new URL(`${i}/ws`),n=this.peerId,s=H(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},n!==t&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Qc[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Al=new WeakSet,bp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Uy);let Yo=Fy;Rl([E.trace("SocketService.connect")],Yo.prototype,"connect",1),Rl([E.trace("SocketService.disconnect")],Yo.prototype,"disconnect",1),Rl([E.trace("SocketService.sendMessagePromise")],Yo.prototype,"sendMessagePromise",1),Rl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Yo.prototype,"sendMessagePromiseWithTimeout",1);class GO{constructor(e){p(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var i;const r=fP.fromBinary(e),n=r.meetings.map(s=>{var o;return{id:s.id,title:s.title,participants:(o=s.participants)!=null?o:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(i=r.parentMeeting.participants)!=null?i:[]},meetings:n}}handleTransferPeerRaw({payload:e}){const i=jP.fromBinary(e);return{authToken:i.authToken,meetingId:i.meetingId}}handleMovedPeerRaw({payload:e}){const i=kf.fromBinary(e);return{meetingId:i.meetingId,customParticipantId:i.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Ef.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return DP.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:i}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,TP.toBinary({payloads:e}));return Ef.fromBinary(i).payloads.map(r=>({id:r.id,title:r.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const i=e.map(n=>({id:n})),r=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,MP.toBinary({payloads:i}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const i=yield this.socketService.sendMessagePromise(F.movePeers,UP.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(i.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(i){return{success:!1,error:i}}})}}var qO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,JO=(t,e,i,r)=>{for(var n=r>1?void 0:r?$O(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&qO(e,i,n),n},Hi;class By extends Wt{constructor(e){const i=e.getValue("logger");super(i),p(this,"meetings",[]),p(this,"parentMeeting",null),g(this,Hi,void 0),f(this,Hi,e)}get supportsConnectedMeetings(){return a(this,Hi).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.
20
20
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield a(this,Hi).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Hi).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Hi).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(n=>n.id)):Promise.resolve());return yield Promise.all(i),yield a(this,Hi).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Hi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r.map(s=>({id:s}))});return n.success&&this.moveSuccessHandler(e,i,r),n})}moveParticipantsWithCustomPreset(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Hi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r});return n.success&&this.moveSuccessHandler(e,i,r.map(s=>s.id)),n})}moveSuccessHandler(e,i,r){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>n.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>n.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(r.map(c=>n.get(c)));return H(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!r.includes(c.id));return H(V({},s),{participants:o})}return s})}}Hi=new WeakMap,JO([Dt({maxInvocations:60,period:60})],By.prototype,"getConnectedMeetings",1);var KO=Object.defineProperty,zO=Object.getOwnPropertyDescriptor,wp=(t,e,i,r)=>{for(var n=r>1?void 0:r?zO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&KO(e,i,n),n},Ie,Wy;const jy=(Wy=class{constructor(t){p(this,"connectedMeetings"),g(this,Ie,void 0),f(this,Ie,t),this.connectedMeetings=new By(t)}get telemetry(){return a(this,Ie).getValue("telemetry")}get logger(){return a(this,Ie).getValue("logger")}static init(t){const e=new jy(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Ie).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var r,n,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,Ie).getValue("self").videoEnabled,audio:a(this,Ie).getValue("self").audioEnabled};try{a(this,Ie).getValue("self").cleanupEvents(),yield a(this,Ie).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(r=a(this,Ie).getValue("meeting"))==null?void 0:r.meta)==null?void 0:n.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield $y.init(H(V({},a(this,Ie).getValue("options")),{cachedUserDetails:null,defaults:H(V(V({},a(this,Ie).getValue("options").defaults),c),{mediaHandler:a(this,Ie).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,Ie).getValue("self");d.self.setName(a(this,Ie).getValue("self").name),yield d.join(),l&&d.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: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(i=>({id:i.id,title:i.title,participants:i.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,Ie).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(r=>{i.set(r.id,r)}),e.forEach(r=>{i.has(r.id)?i.get(r.id).title=r.title:i.set(r.id,H(V({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,Ie).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(i=>i.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(i=>!e.includes(i.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Ie=new WeakMap,Wy);let Dl=jy;wp([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Dl.prototype,"getConnectedMeetings",1),wp([E.trace("ConnectedMeetingsController.setupEvents")],Dl.prototype,"setupEvents",1),wp([E.trace("ConnectedMeetingsController.switchMeeting")],Dl.prototype,"switchMeeting",1);var YO=Object.defineProperty,QO=Object.getOwnPropertyDescriptor,Ol=(t,e,i,r)=>{for(var n=r>1?void 0:r?QO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&YO(e,i,n),n};const ra=class{constructor(t,e,i){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=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=i.getValue("telemetry"),this.logger=i.getValue("logger")}static init(t){return u(this,null,function*(){var e,i;const{peerId:r,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(fy(t),ke.isSupported()===!1)throw new I("Browser not supported","0010",l,!0);const h=e1(t,{authToken:s,baseURL:n,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",r),t.setValue("apiClient",h);const m=new L1(t);t.setValue("connectionHandler",m);const v=ra.createSocketService(t),S=v.connect(),k=h.getUserDetails(),C=h.getPlugins();let b=Ae.HIVE,M,j="";try{yield ra.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield S}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:b,meetingTitle:j}=yield h.getRoomNodeData()),M=yield k,l.info(`SFU ${b} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:b})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const W=TD.init(M.preset,!t.getValue("modules").theme),w=WD.init(t,W.viewType,M.preset.permissions),te=ra.setupControllers(v,t,M,C,j,W,w);_1(W)&&((e=ra.createRoomNodeClient(t,v).initializeConnection(M.participant.name,o,!1,w))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),E.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ie}=yield te;return k_(),new ra(n,ie,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:r,overrides:n,meetingId:s,organizationId:o,logger:c}=t.getAllValues(),d=E_(s),l=H(V({entity:yu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:s},ke.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?rn({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${yu.PEER}_${i}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch(h){c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,r,n,s,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:m}=i,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:k}=e.getValue("roomNodeOptions"),{viewType:C,mediaConstraints:{audio:b}}=s;e.setValue("viewType",C),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=b.enableHighBitrate)!=null?c:!1,enableStereo:(d=b.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",ke.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let M,j,W,w,te,ie,ae,De,st;const ei=new fO(e,t),A=new GO(t);e.setValue("connectedMeetingsSocketHandler",A);const T=new yl(e,t),_=new ri(e,t),B=new kO(t),le=new Sy(e,t),Ke=new bO(e,t),x=new gO(t),P=new cn(e,t),me=yield Br.init(e,le,m,o,s),qn=yield rv.init(e,me.self,le,ei,n);if(h.participant&&(De=new nr(e,me.self,le,k)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield Zi.init(e,_,P,me.self,De.participants)),h.internals&&(te=yield Qu.init(e)),h.livestream&&s.viewType===Mt.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new Ev(e,me.self,x)),s.viewType!==Mt.Chat){if(h.poll&&(M=yield Yf.init(e,me.self,T)),h.recording&&(ie=new uv(e,me.self,le)),h.stage&&(W=new nv(e,B,le,me.self,De.participants)),h.plugin){if(!De)throw new I("The plugin module cannot be initialized without the `participant` module","0102");const ur=yield r;w=yield Fa.init(e,ur,Ke,_,j==null?void 0:j.chat,me.self,De.participants,n)}if(h.connectedMeetings&&(st=yield Dl.init(e)),h.pip){const ur=yield __._init(e,me.self);e.setValue("pip",ur)}}const $n={storesManager:new PD(e,Ke),pollController:M,selfController:me,metaController:qn,chatController:j,stageController:W,pluginController:w,recordingController:ie,internalsController:te,livestreamController:ae,participantController:De,connectedMeetingsController:st};return{theme:s,permissions:o,controllers:$n}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:r}=t.getAllValues(),{sfu:n}=r;return gy(t,n,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:r}=t.getAllValues(),n=["PING"];return new Yo(t,{peerId:e,meetingId:i,authToken:r,capabilities:n})}};let Qo=ra;Ol([E.trace("Controller.init")],Qo,"init",1),Ol([E.trace("setupFlagsmith")],Qo,"setupFlagsmith",1),Ol([E.trace("Controller.createRoomNodeClient")],Qo,"createRoomNodeClient",1),Ol([E.trace("Controller.createSocketService")],Qo,"createSocketService",1);class XO{constructor(){p(this,"battery"),p(this,"logger"),p(this,"init",e=>u(this,null,function*(){this.logger=e;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(i){e.error("Error getting battery",i)}})),p(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.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 e,i;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(i=this.battery)==null||i.removeEventListener("levelchange",this.updateLevelInfo))})}}const Hy=new XO;function ZO(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:i,orgId:r,participantId:n}=JSON.parse(atob(t.split(".")[1]));if(!i)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://${rn({servicePrefix:"rtk",baseURI:s})}`;return{meetingId:i,orgId:r,participantId:n,baseURI:s,apiBase:o}}catch(i){throw new I("Invalid auth token","0004")}}var Hn,na,sa,Nl,_p,Gy;class eN{constructor(){g(this,_p),g(this,Hn,new Audio),g(this,na,new MediaStream),g(this,sa,new Map),g(this,Nl,void 0),a(this,Hn).srcObject=a(this,na),a(this,Hn).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,sa).has(i.id)||(a(this,na).addTrack(i),a(this,sa).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Hn).setSinkId(e)}removeTrack(e){const i=a(this,sa).get(e);i&&(a(this,na).removeTrack(i),a(this,sa).delete(e))}play(){return u(this,null,function*(){return a(this,Hn).srcObject=a(this,na),a(this,Hn).play().catch(e=>{U(this,_p,Gy).call(this,e)})})}onError(e){f(this,Nl,e)}}Hn=new WeakMap,na=new WeakMap,sa=new WeakMap,Nl=new WeakMap,_p=new WeakSet,Gy=function(t){var e;(e=a(this,Nl))==null||e.call(this,t)};var aa;class tN extends eN{constructor(){super(),g(this,aa,void 0),f(this,aa,new Map)}addParticipantTrack(e,i){a(this,aa).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,aa).get(e);i&&this.removeTrack(i),a(this,aa).delete(e)}}aa=new WeakMap;var iN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,Vl=(t,e,i,r)=>{for(var n=r>1?void 0:r?rN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&iN(e,i,n),n},nt,Gn,qy;let $r=(qy=class{constructor(t,e){g(this,nt,void 0),g(this,Gn,void 0),f(this,Gn,t),f(this,nt,e)}get peerId(){return a(this,Gn).getValue("peerId")}static initMedia(t={},e=!1,i=void 0){var r;const n=(r=i==null?void 0:i.peerId)!=null?r:Jr(),s=Ki.createContext(n,{peerId:n}),o=s.getValue("logger");o.init(s);const c=new Av(o);return c.init(t,e,s),s.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,i,r,n,s,o,c;ke.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((r=(i=t==null?void 0:t.cachedUserDetails)==null?void 0:i.peerId)!=null?r:Jr()),{authToken:h,baseURI:m}=t,v=ZO(h,m),{meetingId:S}=v,k=_c(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const C=$r.setupContext(l,t,S,k),b=C.getValue("telemetry"),M=C.getValue("logger");QS(M),Hy.init(M),b.init(C,{roomName:S,userId:k.participantId,organizationId:k.orgId,peerId:l},(s=(n=t.modules)==null?void 0:n.tracing)!=null?s:!0),M.init(C),M.info("DyteClient::init::options",{dyteClientInitOptions:H(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
22
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield Qo.init(C),W=new $r(C,j);return C.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=Ki.createContext(t,e),c=V(V({},p_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",m_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",yi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.23"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new tN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,nt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Hy.cleanup(),a(this,Gn).getValue("peerSessionStore").reset(),(e=a(this,Gn).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,nt);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,nt).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,nt).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,nt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,nt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,nt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,nt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,nt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,nt).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,nt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,nt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,nt).stageController)==null?void 0:t.stage}get stores(){return a(this,nt).storesManager}get audio(){return a(this,Gn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,nt).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)})}},nt=new WeakMap,Gn=new WeakMap,qy);Vl([ut("0002"),Mr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],$r.prototype,"join",1),Vl([ut("0003")],$r.prototype,"leave",1),Vl([ut("0001"),Mr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],$r,"init",1),$r=Vl([ut("0000")],$r);const $y=$r;return $y}();
22
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield Qo.init(C),W=new $r(C,j);return C.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=Ki.createContext(t,e),c=V(V({},p_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",m_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",yi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.24"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new tN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,nt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Hy.cleanup(),a(this,Gn).getValue("peerSessionStore").reset(),(e=a(this,Gn).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,nt);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,nt).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,nt).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,nt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,nt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,nt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,nt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,nt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,nt).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,nt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,nt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,nt).stageController)==null?void 0:t.stage}get stores(){return a(this,nt).storesManager}get audio(){return a(this,Gn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,nt).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)})}},nt=new WeakMap,Gn=new WeakMap,qy);Vl([ut("0002"),Mr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],$r.prototype,"join",1),Vl([ut("0003")],$r.prototype,"leave",1),Vl([ut("0001"),Mr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],$r,"init",1),$r=Vl([ut("0000")],$r);const $y=$r;return $y}();
package/dist/index.cjs.js CHANGED
@@ -20,4 +20,4 @@ ${t}`}const na={maxInvocations:5,period:1};function Ft(t,e){return function(i,r,
20
20
  maxEnergy: ${a(this,Sn)}`),n===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||n<a(this,Mr))&&f(this,Mr,n),(!a(this,Sn)||n>a(this,Sn))&&f(this,Sn,n),{energy:(n-a(this,Mr))/(a(this,Sn)-a(this,Mr))*10||0,isVoice:r})},Cd=new WeakSet,Nh=function(t){return t<5},Vh=new WeakSet,by=function(t=a(this,$s)){var e;if(!a(this,Fi)||!t){a(this,Js).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Fi)}`);return}const i={producerId:a(this,Fi),energy:Math.round(t),silent:U(e=al,Cd,Nh).call(e,t)};f(this,qo,i.silent),this.reportRequest(i)},gu=new WeakSet,Ag=function(t){const e=Math.log10(t);return Math.round(e)},g(Lh,Cd),g(Lh,gu);const gO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),r=i.writable.getWriter(),n=48e3,s=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const m=new Float32Array(s*o),v=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:m});c+=s/n*1e6,yield r.ready,yield r.write(v)}catch{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([i]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch{}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const r=i.createOscillator();r.frequency.value=0,r.type="sine";const n=i.createGain();n.gain.value=0,r.connect(n);const s=i.createMediaStreamDestination();n.connect(s),r.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch{return}},fO=(t=!1)=>{var e,i;const r=new MediaStream().getVideoTracks()[0],n=document.createElement("canvas");n.height=(e=r==null?void 0:r.getSettings().height)!=null?e:720,n.width=(i=r==null?void 0:r.getSettings().width)!=null?i:1280;const s=n.getContext("2d");s.fillStyle="black",s.fillRect(0,0,n.width,n.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,n.width,n.height)},1e3);const o=n.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,me=(t,e,i,r)=>{for(var n=r>1?void 0:r?yO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&vO(e,i,n),n};const Ht=["video/VP9","video/VP8"];var Lc,xc,yt,J,eo,qi,At,ds,ls,us,Uc,hi,vr,to,hs,ps,Dt,Gt,nn,ms,fu,Dg,vu,Og,yu,Ng,Fc,Su,Tu,Eu,Vg,ku,Lg,bu,xg,wu,Ug,dt,St,gs,io,_u,Fg,Iu,Bg,Cu,Wg;const wy=(Eu=class{constructor(t,e,i){g(this,nn),g(this,fu),g(this,vu),g(this,yu),g(this,Fc),g(this,ku),g(this,bu),g(this,wu),g(this,dt),g(this,gs),g(this,_u),g(this,Iu),g(this,Cu),p(this,"context"),p(this,"authToken"),p(this,"e2ee"),g(this,Lc,void 0),g(this,xc,void 0),g(this,yt,void 0),g(this,J,void 0),g(this,eo,void 0),g(this,qi,void 0),g(this,At,void 0),g(this,ds,void 0),g(this,ls,void 0),g(this,us,void 0),g(this,Uc,void 0),g(this,hi,null),g(this,vr,void 0),g(this,to,void 0),g(this,hs,void 0),g(this,ps,void 0),g(this,Dt,void 0),g(this,Gt,void 0);var r,n;this.context=t;const{socket:s}=i;this.mediaJoined=!1,f(this,hs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ps,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,qi,e),f(this,yt,s),f(this,ds,!1),f(this,J,new hO(t,s,e)),f(this,At,a(this,J).events),f(this,vr,new Set),f(this,Dt,new Map),f(this,ls,!1),f(this,us,new sh(t.getValue("logger"))),e===De.CF&&!navigator.isReactNative&&f(this,Gt,new Lh(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Uc,op(()=>u(this,null,function*(){if(!a(this,nn,ms).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,xc),a(this,Lc),!0,!0);o&&(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,nn,ms).mediaJoined}set mediaJoined(t){a(this,nn,ms).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Dt).clear(),a(this,vr).clear(),f(this,hi,null),a(this,us).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,us,new sh)}joinRoom(t,e){return u(this,arguments,function*(i,r,n=!1,s=!1,o={}){a(this,nn,ms).mediaJoinAttempted=!0,f(this,ds,!0),n&&this.reset();try{return yield a(this,us).push(()=>U(this,fu,Dg).call(this,i,r,s,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,r,n=!1,s={}){return a(this,hi)?a(this,hi):(f(this,hi,(()=>u(this,null,function*(){try{yield U(this,Fc,Su).call(this,i,r,n,s)}catch(o){throw f(this,hi,null),o}}))()),a(this,hi))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,J).stopAllTransports(),f(this,ls,!1),a(this,nn,ms).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,yt).sendMessagePromise(a(this,At).leaveRoom,fI.toBinary(e));(t=nC.fromBinary(i.payload))!=null&&t.closed||this.logger.warn("weird state on peer closed and should not happen")}catch(i){this.logger.error("error on sending leave room request",{error:i})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()})}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,r)=>{const n=a(this,J).producerIdToConsumerIdMap.get(r.producerId);return n?(i.push(n),i):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),i)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,r=U(this,dt,St).call(this,i);if(r){const h=yield r;if(a(this,J).producers.has(h)){const m=a(this,J).producers.get(h);if(!m.closed)return yield m.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Ht.filter(h=>h!==e)),s=U(this,Cu,Wg).call(this,t,n),o=Zs(this.context,"disableSimulcast"),c=a(this,qi)===De.CF?Z.ENABLE_CF_SIMULCAST:Z.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,qi)}`),s.encodings=tD(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,qi)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(s.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Dt).delete(i)},l=a(this,J).createProducer(s,d);return U(this,gs,io).call(this,i,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const r=Ht.filter(n=>{var s,o;return((o=(s=a(this,eo).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,ps).get(n).size>0});return r.length===0&&r.push(Ht[0]),yield Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const r={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)},s=a(this,J).createProducer(r,n);U(this,gs,io).call(this,Se.SCREENSHARE_VIDEO,s.then(c=>c.id));let o;if(i){const c={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,gs,io).call(this,Se.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([s,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=U(this,dt,St).call(this,Se.MIC);if(e){const s=yield e;if(a(this,J).producers.has(s)){const o=a(this,J).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Gt)&&(a(this,Gt).audioTrack=t,a(this,Gt).producerId=s,a(this,Gt).start());return}yield a(this,J).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=U(this,Iu,Bg).call(this,t),r=()=>{a(this,Dt).delete(Se.MIC)},n=a(this,J).createProducer(i,r);U(this,gs,io).call(this,Se.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,Gt)&&(a(this,Gt).audioTrack=s.track,a(this,Gt).producerId=s.id,a(this,Gt).start())})}catch(e){throw new I(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,dt,St).call(this,Se.MIC),i=a(this,J).producers.get(e);if(!i){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Gt))==null||t.stop();const r={producerId:i.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,dt,St).call(this,Se.WEBCAM),e=yield U(this,dt,St).call(this,Se.WEBCAM_BACKUP),i=a(this,J).producers.get(t),r=a(this,J).producers.get(e);if(!i&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(o))};i&&(i.pause(),n(i)),r&&(r.pause(),n(r))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,dt,St).call(this,Se.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=Se.WEBCAM){const e=yield U(this,dt,St).call(this,t),i=a(this,J).producers.get(e);if(!i){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,i);const r={producerId:i.id,pause:!1};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(r))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,i=yield U(this,dt,St).call(this,e);U(this,_u,Fg).call(this,e),i&&(yield a(this,J).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,dt,St).call(this,Se.MIC);e&&(yield a(this,J).closeProducer(e)),(t=a(this,Gt))==null||t.stop(),a(this,Dt).delete(Se.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,dt,St).call(this,Se.SCREENSHARE_VIDEO),e=yield U(this,dt,St).call(this,Se.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,vr).clear(),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const i=yield U(this,dt,St).call(this,Se.WEBCAM),r=yield U(this,dt,St).call(this,Se.WEBCAM_BACKUP);yield a(this,J).closeProducer(i,{stopTrack:!1}),yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield U(this,dt,St).call(this,Se.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const i={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,yt).sendMessagePromise(a(this,At).globalPinPeer,MI.toBinary(e))}catch(i){this.logger.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,vr).add(t.consumerPeerId),a(this,vr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(r=>this.getConsumers().get(r));a(this,J).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,yt).on(a(this,At).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:r,producerState:n}=NC.fromBinary(t);if(r===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Bi.AUDIO?"audio/opus":"video/VP8"),n.kind===Bi.VIDEO&&!n.screenShare&&((i=(e=a(this,eo).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Ht[0]))>=0&&a(this,hs).get(Ht[0]).has(r)&&n.mimeType!==Ht[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:q(V({},n),{kind:n.kind===Bi.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,yt).on(a(this,At).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:r,pause:n,producerId:s}}=Mm.fromBinary(t),o=r===Bi.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${n} payload: ${JSON.stringify(Mm.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(o==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:n,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==n&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${n}`),n?(c.pause(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,yt).on(a(this,At).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Hu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,vr).delete(e),a(this,J).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,yt).on(a(this,At).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=xC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:e,producerId:i});const r=a(this,J).producerIdToConsumerIdMap.get(i);if(!r){this.logger.warn(`no consumer found for producer:${i}`);return}this.logger.info(`closing consumer ${r}, producer id: ${i}`),a(this,J).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,J).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:r})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,yt).on(a(this,At).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,ds)&&!a(this,ls)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,Uc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,i)=>{const r=a(this,J).consumers.get(i);r&&this.context.getValue("peerSessionStore").emit(R.CONSUMER_SCORE_UPDATE,{id:i,kind:r.kind,peerId:r.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,i)=>{const r=Array.from(a(this,J).producers.values()).find(n=>n.id===i);r&&this.context.getValue("peerSessionStore").emit(R.PRODUCER_SCORE_UPDATE,{id:i,kind:r.kind,appData:r.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,r,n,s;for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((r=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,ps).get(c).add(t);break}}for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((s=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,hs).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,hs).forEach(e=>e.delete(t)),a(this,ps).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===Ht[0])&&this.disableWebcam(i)}))}},Lc=new WeakMap,xc=new WeakMap,yt=new WeakMap,J=new WeakMap,eo=new WeakMap,qi=new WeakMap,At=new WeakMap,ds=new WeakMap,ls=new WeakMap,us=new WeakMap,Uc=new WeakMap,hi=new WeakMap,vr=new WeakMap,to=new WeakMap,hs=new WeakMap,ps=new WeakMap,Dt=new WeakMap,Gt=new WeakMap,nn=new WeakSet,ms=function(){return this.context.getValue("connectionHandler")},fu=new WeakSet,Dg=function(t,e,i,r){return u(this,null,function*(){f(this,xc,t);try{return a(this,hi)?yield a(this,hi):yield U(this,Fc,Su).call(this,t,e,i,r),U(this,yu,Ng).call(this,e),{roomJoined:yield U(this,vu,Og).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{f(this,hi,null)}})},vu=new WeakSet,Og=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,Lc,t.roomUuid),f(this,ls,!0),f(this,ds,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},yu=new WeakSet,Ng=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:q(V({},Ie.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(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Fc=new WeakSet,Su=function(t,e,i,r){return u(this,null,function*(){var n,s;try{(s=a(this,to))!=null||f(this,to,U(n=wy,Tu,Vg).call(n));const o=U(this,ku,Lg).call(this);yield U(this,bu,xg).call(this,t,e,i,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,wu,Ug).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},Tu=new WeakSet,Vg=function(){const{ipInfo:t}=ht();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},ku=new WeakSet,Lg=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=ZD(e);return f(this,eo,i),i},bu=new WeakSet,xg=function(t,e,i,r){return u(this,null,function*(){yield dy((n,s)=>u(this,null,function*(){if(!a(this,yt).isConnected){s(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,J).socketHandler.joinRoom(e,t,r,i,a(this,to))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},wu=new WeakSet,Ug=function(t){return u(this,null,function*(){if(!(a(this,qi)===De.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(fO(!1))),t.canProduceAudio===G.Allowed){const i=gO(!1);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},dt=new WeakSet,St=function(t){return a(this,Dt).get(t)},gs=new WeakSet,io=function(t,e){return a(this,Dt).set(t,e)},_u=new WeakSet,Fg=function(t){return a(this,Dt).delete(t)},Iu=new WeakSet,Bg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF}},Cu=new WeakSet,Wg=function(t,e){return{track:t,codecOptions:e?e.map(i=>({name:i.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(Eu,Tu),Eu);let le=wy;me([E.trace("MediaNodeClient.reset",{country:E.location.country})],le.prototype,"reset",1);me([E.trace("MediaNodeClient.joinRoom")],le.prototype,"joinRoom",1);me([E.trace("MediaNodeClient.leaveRoom")],le.prototype,"leaveRoom",1);me([E.trace("MediaNodeClient.activatePeers")],le.prototype,"activatePeers",1);me([E.trace("MediaNodeClient.createConsumers")],le.prototype,"createConsumers",1);me([E.trace("MediaNodeClient.closeConsumers")],le.prototype,"closeConsumers",1);me([E.trace("MediaNodeClient._shareWebcam")],le.prototype,"_shareWebcam",1);me([E.trace("MediaNodeClient.shareWebcam")],le.prototype,"shareWebcam",1);me([E.trace("MediaNodeClient.shareScreen")],le.prototype,"shareScreen",1);me([E.trace("MediaNodeClient.shareMic")],le.prototype,"shareMic",1);me([E.trace("MediaNodeClient.pauseMic")],le.prototype,"pauseMic",1);me([E.trace("MediaNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1);me([E.trace("MediaNodeClient.resumeMic")],le.prototype,"resumeMic",1);me([E.trace("MediaNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1);me([E.trace("MediaNodeClient.disableWebcam")],le.prototype,"disableWebcam",1);me([E.trace("HiveClient.disableMic")],le.prototype,"disableMic",1);me([E.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1);me([E.trace("MediaNodeClient.muteSelf")],le.prototype,"muteSelf",1);me([E.trace("MediaNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1);me([E.trace("MediaNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1);me([E.trace("MediaNodeClient.kickPeer")],le.prototype,"kick",1);me([E.trace("MediaNodeClient.kickAllPeers")],le.prototype,"kickAll",1);me([E.trace("MediaNodeClient.muteAll")],le.prototype,"muteAll",1);me([E.trace("MediaNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1);me([E.trace("MediaNodeClient.disableAudio")],le.prototype,"disableAudio",1);me([E.trace("MediaNodeClient.disableVideo")],le.prototype,"disableVideo",1);me([E.trace("MediaNodeClient.pinPeer")],le.prototype,"pinPeer",1);me([E.trace("MediaNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);function _y(t,e,i){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const n=new le(t,e,i);return t.setValue("roomNodeClient",n),n}function Iy(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var SO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,$n=(t,e,i,r)=>{for(var n=r>1?void 0:r?TO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&SO(e,i,n),n},sn,Ai,re,Ot,qt,jg;const Cy=(jg=class{constructor(t,e,i,r){g(this,Ot),p(this,"self"),p(this,"authToken"),g(this,sn,void 0),p(this,"viewType"),g(this,Ai,void 0),g(this,re,void 0);const{socket:n}=i,s=t.getValue("authToken");this.self=e,f(this,re,t),this.viewType=r,this.authToken=s,f(this,sn,n),f(this,Ai,i),e.config.viewType!==Ut.Chat&&this.setupEvents()}get peerId(){return a(this,re).getValue("peerId")}get telemetry(){return a(this,re).getValue("telemetry")}get logger(){return a(this,re).getValue("logger")}get mediaJoined(){return a(this,re).getValue("connectionHandler").mediaJoined}static init(t,e,i,r,n){return u(this,null,function*(){const s=ht(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield st.__init__(t,i,r,n,n.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const m=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(m)}),t.getValue("callstats").devices("AUDIO",m==null?void 0:m.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",m==null?void 0:m.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",m==null?void 0:m.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:_v(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Cy(t,d,e,n.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:r,audioEnabled:n,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(r.canProduceAudio===G.Allowed&&n)try{yield a(this,Ot,qt).shareMic(e),this.self.audioEnabled||a(this,Ot,qt).pauseMic()}catch{this.self.disableAudio()}if(r.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Ot,qt).shareWebcam(i);d&&d.id!==i.id&&a(this,re).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Ot,qt).shareWebcam(d)),this.self.videoEnabled||a(this,Ot,qt).pauseWebcam()}catch{this.self.disableVideo()}if(r.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Ot,qt))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch{this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}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(t){return u(this,null,function*(){a(this,re).getValue("callstats").callEnded(),a(this,Ot,qt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,re).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,re).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(e=Nn()),a(this,sn).updateURL(e),a(this,re).getValue("telemetry").resetPeerId(e),ht().setHeader("dyte-tracing-id",e),nr.remapContext(e,a(this,re)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ai).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ai).on(zc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,re).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,e.patch)})}),a(this,Ai).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ai).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ai).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,re).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:r})=>{var n;const s=(n=i==null?void 0:i.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),a(this,re).getValue("peerSessionStore").on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,re).getValue("callstats").audioOff())})),a(this,re).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,re).getValue("callstats").videoOff())})),a(this,re).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Ai).joinRoom(this.self);a(this,Ai).socket.flush();const i=hp(e.stageType);if(a(this,re).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,re).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,i;if(t==="rejected"){try{(e=a(this,sn))==null||e.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,re).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,re).notify("stageStatus");try{(i=a(this,sn))==null||i.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}Iy(a(this,re)),yield a(this,re).getValue("roomSocketHandler").cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:r,viewType:n,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,re).getAllValues(),{sfu:d}=c;try{if(n===Ut.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}_y(a(this,re),d,{socket:a(this,sn),peerId:r})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}=this.self.permissions,{roomJoined:v}=(i=yield(e=a(this,Ot,qt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}))!=null?i:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new I("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,re).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Ut.Webinar)&&a(this,Ot,qt)&&(a(this,Ot,qt).mediaJoined&&t!=="disconnected"&&(yield a(this,Ot,qt).leaveRoom()),!(t==="stageLeft"&&e===Ut.Livestream)&&(a(this,Ot,qt).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()})}},sn=new WeakMap,Ai=new WeakMap,re=new WeakMap,Ot=new WeakSet,qt=function(){return a(this,re).getValue("roomNodeClient")},jg);let $r=Cy;$n([E.trace("SelfController.resetSelf")],$r.prototype,"resetSelf",1);$n([E.trace("SelfController.setupEvents")],$r.prototype,"setupEvents",1);$n([E.trace("SelfController.joinRoom")],$r.prototype,"joinRoom",1);$n([E.trace("SelfController.leaveRoom")],$r.prototype,"leaveRoom",1);$n([E.trace("SelfController.joinMediaRoom")],$r.prototype,"joinMediaRoom",1);$n([E.trace("SelfController.leaveMediaRoom")],$r.prototype,"leaveMediaRoom",1);$n([E.trace("SelfController.init")],$r,"init",1);var Pd;class EO{constructor(e){g(this,Pd,void 0),f(this,Pd,e)}on(e,i){let r;e===F.roomPeerCount?r=Om.fromBinary.bind(Om):r=Gm.fromBinary.bind(Gm),a(this,Pd).on(e,({payload:n})=>{const s=r(n);return i(s)})}}Pd=new WeakMap;var Rd,Md;class kO{constructor(e,i){g(this,Rd,void 0),g(this,Md,void 0),f(this,Rd,i),f(this,Md,e)}get logger(){return a(this,Md).getValue("logger")}on(e,i){let r,n;switch(e){case F.transcript:{r=ql.fromBinary.bind(ql),n=ql.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Rd).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Rd=new WeakMap,Md=new WeakMap;var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,wp=(t,e,i,r)=>{for(var n=r>1?void 0:r?wO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&bO(e,i,n),n},Ar,Ao;class Ml{constructor(e,i){g(this,Ar,void 0),g(this,Ao,void 0),f(this,Ar,i),f(this,Ao,e)}get logger(){return a(this,Ao).getValue("logger")}get telemetry(){return a(this,Ao).getValue("telemetry")}getPolls(){return a(this,Ar).sendMessagePromise(Xi.getPolls)}createPoll(e,i,r=!1,n=!1){const s={anonymous:r,hideVotes:n,question:e,options:i};return a(this,Ar).sendMessage(Xi.createPoll,_A.toBinary(s))}votePoll(e,i){const r={index:i,pollId:e};return a(this,Ar).sendMessage(Xi.votePoll,CA.toBinary(r))}on(e,i){let r,n;switch(e){case Xi.updatePoll:case Xi.createPoll:case Xi.votePoll:{r=Ql.fromBinary.bind(Ql),n=Ql.create();break}}a(this,Ar).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Ar).removeListeners(e)}}Ar=new WeakMap,Ao=new WeakMap;wp([E.trace("PollSocketHandler.getPolls")],Ml.prototype,"getPolls",1);wp([E.trace("PollSocketHandler.createPoll")],Ml.prototype,"createPoll",1);wp([E.trace("PollSocketHandler.votePoll")],Ml.prototype,"votePoll",1);var _O=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,CO=(t,e,i,r)=>{for(var n=r>1?void 0:r?IO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&_O(e,i,n),n},si;class Py{constructor(e,i){p(this,"socket"),g(this,si,void 0),f(this,si,e),this.socket=i,this.handleSocketEvents(),a(this,si).setValue("roomSocketHandler",this)}get telemetry(){return a(this,si).getValue("telemetry")}get logger(){return a(this,si).getValue("logger")}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch{this.logger.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const r={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(F.joinRoom,hP.toBinary(r));try{const{peer:s}=vs.fromBinary((yield n).payload);a(this,si).getValue("connectionHandler").socketJoined=!0,a(this,si).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,si).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,si).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:s}}catch(s){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:s}),new I("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return YP.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:r}=i,n=gl(i,["id"]);return q(V({},n),{userId:r})})}catch{return[]}})}getRoomPeers(e,i,r){return u(this,null,function*(){let n;try{const s={seachQuery:e,limit:i,offset:r},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,iP.toBinary(s));n=$l.fromBinary(o.payload)}catch(s){this.logger.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=$l.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=$l.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const r=yield this.socket.sendMessagePromise(F.getPeerInfo,Lv.toBinary({peerId:e}));i=vs.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return i})}getRoomState(){return u(this,null,function*(){let e=Nm.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomInfo);e=Nm.fromBinary(i.payload)}catch(i){this.logger.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Um.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomStageState);e=Um.fromBinary(i.payload)}catch(i){this.logger.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,ba.toBinary(r))})}broadcastToMeetings(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,ba.toBinary(n))})}broadcastToPeers(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,ba.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,mP.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(F.kick,Uv.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,Ov.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,iR.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,nR.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const r={updatePeersPresets:[]};return e.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:i})}),this.socket.sendMessagePromise(zc.updateUserPreset,OR.toBinary(r))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const i=ba.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(R.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode broadcast message:",i)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const i=ba.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(R.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode peer broadcast message:",i)}})}on(e,i){let r,n;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=vs.fromBinary.bind(vs),n=vs.create();break}case F.getWaitingRoomRequests:{r=(s,o)=>s?xm.fromBinary(s,o):{requests:[]},n=xm.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Jm.fromBinary.bind(Jm);break}case zc.updateUserPreset:{r=Fm.fromBinary.bind(Fm);break}case ki.peerJoinedBroadcast:case oi.peerJoinedBroadcast:{r=Pm.fromBinary.bind(Pm);break}case ki.selfJoinComplete:case oi.selfJoinComplete:{r=ju.fromBinary.bind(ju);break}case ki.globalPeerPinBroadcast:case oi.globalPeerPinBroadcast:{r=Am.fromBinary.bind(Am);break}case ki.selectedPeer:case oi.selectedPeer:{r=Wu.fromBinary.bind(Wu);break}case ki.selectedPeerDiff:case oi.selectedPeerDiff:{r=Cm.fromBinary.bind(Cm);break}case ki.leaveRoom:case oi.leaveRoom:{r=Hu.fromBinary.bind(Hu);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!r)return i(void 0);try{o=r(s)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const r=yield this.socket.sendMessagePromise(zc.getUserPresets,IR.toBinary(i)),n=MR.fromBinary(r.payload).peerPresets[0],s=new TextDecoder().decode(n.preset),o=JSON.parse(s).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}})}}si=new WeakMap;CO([E.trace("RoomSocketHandler.joinRoom")],Py.prototype,"joinRoom",1);var Kt;class PO{constructor(e){g(this,Kt,void 0),f(this,Kt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Kt).sendMessagePromise(F.getStageRequests);return e?Yl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Kt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,Kt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.grantStageAccess,gA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.denyStageAccess,vA.toBinary(i))})}joinStage(){return a(this,Kt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i),void 0,F.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i))}on(e,i){let r;switch(e){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=qm.fromBinary.bind(qm);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=Yl.fromBinary.bind(Yl);break}case F.peerStageStatusUpdate:{r=Dm.fromBinary.bind(Dm);break}}a(this,Kt).on(e,({payload:n,id:s})=>{if(!n||!r)return i(void 0,s);const o=r(n);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Kt).sendMessagePromise(F.getPeerInfo,Lv.toBinary({peerId:e}));return vs.fromBinary(i.payload)})}}Kt=new WeakMap;var it,Ad;class RO{constructor(e,i){g(this,it,void 0),g(this,Ad,void 0),f(this,it,i),f(this,Ad,e)}get logger(){return a(this,Ad).getValue("logger")}addPlugin(e,i){a(this,it).sendMessage($.addPlugin,DM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,it).sendMessage($.removePlugin,NM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise($.getPlugins);return e?rA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,r){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage($.customPluginEventToRoom,GM.toBinary(n),r)}customPluginEventToPeers(e,i,r,n){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,it).sendMessage($.customPluginEventToPeers,$M.toBinary(s),n)}enablePluginForRoom(e,i){a(this,it).sendMessage($.enablePluginForRoom,LM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,r){a(this,it).sendMessage($.enablePluginForPeers,BM.toBinary({pluginId:e,peerIds:i}),r)}disablePluginForRoom(e,i){a(this,it).sendMessage($.disablePluginForRoom,UM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,r){a(this,it).sendMessage($.disablePluginForPeers,jM.toBinary({pluginId:e,peerIds:i}),r)}storeInsertKeys(e,i,r,n){const s={pluginId:e,storeName:i,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(s),n)}storeGetKeys(e,i,r,n){const s={pluginId:e,storeName:i,getKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeGetKeys,YM.toBinary(s),n)}storeDeleteKeys(e,i,r,n){const s={pluginId:e,storeName:i,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeDeleteKeys,XM.toBinary(s),n)}storeDelete(e,i,r){a(this,it).sendMessage($.storeDelete,eA.toBinary({pluginId:e,storeName:i}),r)}getPluginDataOld(e,i){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,r){const n={pluginId:e,storeName:i,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(n))}on(e,i){let r;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{r=Ju.fromBinary.bind(Ju);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{r=Wm.fromBinary.bind(Wm);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{r=Hm.fromBinary.bind(Hm);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{r=jm.fromBinary.bind(jm);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=r(n);return i(o,s)})}}it=new WeakMap,Ad=new WeakMap;var MO=Object.defineProperty,AO=(t,e,i)=>e in t?MO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,DO=(t,e,i)=>(AO(t,typeof e!="symbol"?e+"":e,i),i),_p=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(_p(t,e,"read from private field"),i?i.call(t):e.get(t)),we=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},de=(t,e,i,r)=>(_p(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),Re=(t,e,i)=>(_p(t,e,"access private method"),i),ol={},OO={get exports(){return ol},set exports(t){ol=t}},Ks=typeof Reflect=="object"?Reflect:null,Hg=Ks&&typeof Ks.apply=="function"?Ks.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},Dd;Ks&&typeof Ks.ownKeys=="function"?Dd=Ks.ownKeys:Object.getOwnPropertySymbols?Dd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Dd=function(t){return Object.getOwnPropertyNames(t)};function NO(t){console&&console.warn&&console.warn(t)}var Ry=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}OO.exports=pe;ol.once=UO;pe.EventEmitter=pe;pe.prototype._events=void 0;pe.prototype._eventsCount=0;pe.prototype._maxListeners=void 0;var Gg=10;function Al(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return Gg},set:function(t){if(typeof t!="number"||t<0||Ry(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Gg=t}});pe.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};pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ry(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function My(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return My(this)};pe.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var r=t==="error",n=this._events;if(n!==void 0)r=r&&n.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=n[t];if(c===void 0)return!1;if(typeof c=="function")Hg(c,this,e);else for(var d=c.length,l=Vy(c,d),i=0;i<d;++i)Hg(l[i],this,e);return!0};function Ay(t,e,i,r){var n,s,o;if(Al(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),n=My(t),n>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,NO(c)}return t}pe.prototype.addListener=function(t,e){return Ay(this,t,e,!1)};pe.prototype.on=pe.prototype.addListener;pe.prototype.prependListener=function(t,e){return Ay(this,t,e,!0)};function VO(){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 Dy(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},n=VO.bind(r);return n.listener=i,r.wrapFn=n,n}pe.prototype.once=function(t,e){return Al(e),this.on(t,Dy(this,t,e)),this};pe.prototype.prependOnceListener=function(t,e){return Al(e),this.prependListener(t,Dy(this,t,e)),this};pe.prototype.removeListener=function(t,e){var i,r,n,s,o;if(Al(e),r=this._events,r===void 0)return this;if(i=r[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,n=s;break}if(n<0)return this;n===0?i.shift():LO(i,n),i.length===1&&(r[t]=i[0]),r.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};pe.prototype.off=pe.prototype.removeListener;pe.prototype.removeAllListeners=function(t){var e,i,r;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var n=Object.keys(i),s;for(r=0;r<n.length;++r)s=n[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function Oy(t,e,i){var r=t._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?i?[n.listener||n]:[n]:i?xO(n):Vy(n,n.length)}pe.prototype.listeners=function(t){return Oy(this,t,!0)};pe.prototype.rawListeners=function(t){return Oy(this,t,!1)};pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Ny.call(t,e)};pe.prototype.listenerCount=Ny;function Ny(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}pe.prototype.eventNames=function(){return this._eventsCount>0?Dd(this._events):[]};function Vy(t,e){for(var i=new Array(e),r=0;r<e;++r)i[r]=t[r];return i}function LO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function xO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function UO(t,e){return new Promise(function(i,r){function n(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),i([].slice.call(arguments))}Ly(t,e,s,{once:!0}),e!=="error"&&FO(t,n,{once:!0})})}function FO(t,e,i){typeof t.on=="function"&&Ly(t,"error",e,i)}function Ly(t,e,i,r){if(typeof t.on=="function")r.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){r.once&&t.removeEventListener(e,n),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class BO extends y{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 qg=new BO;class xy{static encode(e){return qg.toBinary(e)}static decode(e){return qg.fromBinary(new Uint8Array(e))}}function WO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Dr;class jO{constructor(e={}){DO(this,"opts"),we(this,Dr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,Dr,0)}wait(){return u(this,null,function*(){de(this,Dr,N(this,Dr)+1);const e=WO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*QS(2,N(this,Dr))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,Dr)}reset(){de(this,Dr,0)}}Dr=new WeakMap;const yr={debug:0,info:1,warn:2,error:3};var Tn,En;class HO{constructor(e){we(this,Tn,void 0),we(this,En,void 0),de(this,Tn,console),de(this,En,e)}debug(...e){yr[N(this,En)]>yr.debug||N(this,Tn).debug("[Sockrates]:",...e)}info(...e){yr[N(this,En)]>yr.info||N(this,Tn).info("[Sockrates]:",...e)}warn(...e){yr[N(this,En)]>yr.warn||N(this,Tn).warn("[Sockrates]:",...e)}error(...e){yr[N(this,En)]>yr.error||N(this,Tn).error("[Sockrates]:",...e)}}Tn=new WeakMap,En=new WeakMap;var Uy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Uy||{});const GO="2",qO="3";var Le,Os,Pe,je,Or,rt,rr,Ur,Ei,Ns,Qi,xh,Fy,Do,Od,Uh,By,Fh,$g,cl,Bh,Wh,Wy,$o,Nd,Jo,dl,ll,jh,zs,Ko,zo,ul;class $O{constructor(e,i){var r;we(this,xh),we(this,Do),we(this,Uh),we(this,Fh),we(this,cl),we(this,Wh),we(this,$o),we(this,Jo),we(this,ll),we(this,zs),we(this,zo),we(this,Le,void 0),we(this,Os,void 0),we(this,Pe,void 0),we(this,je,void 0),we(this,Or,void 0),we(this,rt,void 0),we(this,rr,void 0),we(this,Ur,void 0),we(this,Ei,void 0),we(this,Ns,void 0),we(this,Qi,void 0);var n,s,o,c,d,l,h,m,v;de(this,Os,e),de(this,Or,[]),de(this,rt,new ol),de(this,rr,!0),de(this,Ei,!1),de(this,Pe,i!=null?i:{}),(n=N(this,Pe)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,Pe)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Pe)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Pe)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Pe)).debug!=null||(d.debug=!0),(l=N(this,Pe)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Pe)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=N(this,Pe)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(v=N(this,Pe)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,Ur,{code:void 0,reason:void 0}),de(this,je,(r=N(this,Pe).logger)!=null?r:new HO(N(this,Pe).debug?"debug":"info")),de(this,Qi,new jO)}get readyState(){var e;return(e=N(this,Le))==null?void 0:e.readyState}get url(){return N(this,Os)}updateURL(e){de(this,Os,e),Re(this,Wh,Wy).call(this)}get config(){return N(this,Pe)}get sendQueue(){return N(this,Or)}flush(){if(!N(this,Pe).queueOnDisconnect)return!1;const e=[];return N(this,Or).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),de(this,Or,e),N(this,Or)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,je).debug("Websocket was already connecting or connected.");return}if(N(this,rr)!==!1)return new Promise((i,r)=>{Re(this,zs,Ko).call(this),Re(this,zo,ul).call(this);try{de(this,Le,new WebSocket(Re(this,xh,Fy).call(this,N(this,Os)))),N(this,Le).binaryType="arraybuffer",N(this,je).debug("Connecting");const n=setTimeout(()=>{N(this,je).debug("Connection timeout. Closing socket"),de(this,rr,!0),Re(this,zo,ul).call(this),N(this,Le).close(3001,"Connection Timeout"),N(this,Pe).autoReconnect&&!N(this,Ei)&&(N(this,rt).emit("reconnecting"),Re(this,$o,Nd).call(this)),r(new Error("Connection timed out!"))},N(this,Pe).connectionTimeout);N(this,Le).onopen=()=>{N(this,je).debug(`Ready State: ${Uy[N(this,Le).readyState]}`),n&&clearTimeout(n),Re(this,ll,jh).call(this),de(this,Ur,{code:void 0,reason:void 0}),N(this,rt).emit("connected"),N(this,Pe).flushOnReconnect&&this.flush(),i()},N(this,Le).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;r(c),N(this,je).debug("Socket closed. Close event:",{event:s}),N(this,je).debug(`Connection closed code: ${o}`),N(this,je).debug(`Connection closed reason: ${c}`),N(this,Ei)||Re(this,cl,Bh).call(this,o,c)}catch(o){Re(this,Do,Od).call(this,o)}},N(this,Le).onerror=s=>{Re(this,Do,Od).call(this,s)},N(this,Le).onmessage=s=>Re(this,Uh,By).call(this,s)}catch(n){Re(this,Do,Od).call(this,n,r)}})})}send(e,i,r,n){const s={event:e,id:i,payload:r,metadata:n};if(N(this,Pe).queueOnDisconnect&&(!N(this,Le)||N(this,Le).readyState!==1))return N(this,je).debug("Queuing message since socket is not connected!",s),N(this,Or).push(s),!1;const o=xy.encode(s);return Re(this,Jo,dl).call(this,o)}emit(e,i,r,n){return this.send(e,i,r,n)}sendRaw(e){return Re(this,Jo,dl).call(this,e)}receive(e,i){return N(this,rt).on(e.toString(),i)}on(e,i){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,rt).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,rt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,rt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,rt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){de(this,rr,!1),Re(this,zs,Ko).call(this),this.removeAllListeners(),de(this,Ur,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Le).close(1e3,"Sockrates disconnect method called.")}}Le=new WeakMap,Os=new WeakMap,Pe=new WeakMap,je=new WeakMap,Or=new WeakMap,rt=new WeakMap,rr=new WeakMap,Ur=new WeakMap,Ei=new WeakMap,Ns=new WeakMap,Qi=new WeakMap,xh=new WeakSet,Fy=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Do=new WeakSet,Od=function(t,e){N(this,je).error("Error:",{error:t}),N(this,rt).emit("errored",{error:t}),e==null||e(t)},Uh=new WeakSet,By=function(t){if(Re(this,ll,jh).call(this),t.data===GO){N(this,je).debug("Received ping from server"),Re(this,Jo,dl).call(this,qO);return}const e=xy.decode(t.data),{id:i,payload:r}=e;N(this,je).debug("Received message",{event:e.event,messageID:i}),N(this,rt).emit(e.event.toString(),{id:i,payload:r})},Fh=new WeakSet,$g=function(){return N(this,Le).readyState===1},cl=new WeakSet,Bh=function(t,e){de(this,Ur,{reason:e,code:t}),N(this,rt).emit("disconnected",{code:t,reason:e})},Wh=new WeakSet,Wy=function(){const{reason:t,code:e}=N(this,Ur);e&&e!==1e3&&N(this,rr)&&N(this,Pe).autoReconnect&&!N(this,Ei)&&(N(this,je).debug(`Triggering reconnection due to ${t}.`),N(this,rt).emit("reconnecting"),Re(this,$o,Nd).call(this))},$o=new WeakSet,Nd=function(t=!0){return u(this,null,function*(){if(t&&N(this,Ei)){N(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,Ei)||N(this,Qi).reset(),N(this,Pe).maxReconnectionAttempts!==null&&N(this,Qi).getAttempts()>=N(this,Pe).maxReconnectionAttempts){N(this,rt).emit("failed"),de(this,Ei,!1);return}de(this,Ei,!0),Re(this,zo,ul).call(this),Re(this,zs,Ko).call(this);try{if(yield N(this,Qi).wait(),N(this,rr)===!1)return;if(N(this,je).debug(`Reconnection attempt ${N(this,Qi).getAttempts()}`),N(this,rt).emit("reconnectAttempt",{attempt:N(this,Qi).getAttempts()}),yield this.connect(),!Re(this,Fh,$g).call(this))throw Error("Reconnect Failed");de(this,Ei,!1),de(this,Ur,{code:void 0,reason:void 0}),N(this,rt).emit("reconnected")}catch{N(this,je).debug("Failed to reconnect."),N(this,rt).emit("reconnectFailure",{attempt:N(this,Qi).getAttempts()}),Re(this,$o,Nd).call(this,!1)}})},Jo=new WeakSet,dl=function(t){try{return N(this,Le).send(t),!0}catch(e){return N(this,je).error(e.message),!1}},ll=new WeakSet,jh=function(){this.config.disconnectOnPingTimeout&&(N(this,je).debug("Resetting ping timeout"),Re(this,zs,Ko).call(this),de(this,Ns,setTimeout(()=>{var t;N(this,je).debug("Disconnecting the socket due to ping timeout"),de(this,rr,!0);const e=3002,i="Ping timeout";(t=N(this,Le))==null||t.close(e,i),Re(this,cl,Bh).call(this,e,i)},N(this,Pe).pingTimeout)))},zs=new WeakSet,Ko=function(){N(this,Ns)&&(clearTimeout(N(this,Ns)),de(this,Ns,void 0))},zo=new WeakSet,ul=function(){N(this,Le)&&(N(this,Le).onopen=void 0,N(this,Le).onerror=void 0,N(this,Le).onmessage=void 0,N(this,Le).onclose=void 0)};var JO=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,Dl=(t,e,i,r)=>{for(var n=r>1?void 0:r?KO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&JO(e,i,n),n};const Jg=65535,zO=3e3;var an,Oe,Ne,xe,pi,lt,Bc,Pu,Wc,Ru,Kg;const jy=(Kg=class{constructor(t,{peerId:e,meetingId:i,authToken:r,capabilities:n}){g(this,Ne),g(this,Bc),g(this,Wc),g(this,an,void 0),g(this,Oe,void 0),p(this,"roomName"),p(this,"authToken"),p(this,"capabilities"),g(this,pi,void 0),g(this,lt,void 0);var s;if(!e||!i||!r)throw new I("peerId, meetingId, or authToken can not be empty","0404");f(this,pi,void 0),f(this,lt,t),this.capabilities=n,this.roomName=i,this.authToken=r,f(this,an,U(this,Bc,Pu).call(this,e)),f(this,Oe,new $O(a(this,an),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ne,xe).socketJoinAttempted}set joinAttempted(t){a(this,Ne,xe).socketJoinAttempted=t}get telemetry(){return a(this,lt).getValue("telemetry")}get logger(){return a(this,lt).getValue("logger")}get peerId(){return a(this,lt).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,an,U(this,Bc,Pu).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Oe).updateURL(a(this,an))}static getSocketEdgeDomain(t){return Dn({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,an)}connect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!0,yield a(this,Oe).connect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!1,a(this,Oe).disconnect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Oe).readyState===1}catch{return!1}}sendMessage(t,e,i){const r={};return a(this,lt).getValue("telemetry").injectContext(r),a(this,Oe).send(t,i!=null?i:U(this,Wc,Ru).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,i,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:n,protobuf:e,messageId:i,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:r,resp:n}){const s=n!=null?n:t;return new Promise((o,c)=>{const d=(S,k)=>{a(this,Oe).removeListener(s,S),a(this,Oe).removeListener(Jg,k),a(this,Oe).removeListener(oi.errorResponse,k),a(this,Oe).removeListener(ki.errorResponse,k)},l=r!=null?r:U(this,Wc,Ru).call(this),h={};a(this,lt).getValue("telemetry").injectContext(h);const m=({id:S,payload:k})=>{if(l===S){let C;try{const b=KI.fromBinary(k);C=new Error(b.errorMessage)}catch(b){C=new Error("failed to parse error message",{cause:b});try{const M=zC.fromBinary(k);C=new Error(M.message)}catch(M){C=new Error("failed to parse error message",{cause:M})}}c(C),d(v,m)}},v=({id:S,payload:k})=>{l===S&&(o({id:S,payload:k}),d(v,m))};a(this,Oe).on(s,v),a(this,Oe).on(Jg,m),a(this,Oe).on(oi.errorResponse,m),a(this,Oe).on(ki.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Oe).send(t,l,i,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Oe).on(t,e)}onStateEvent(t,e){a(this,Oe).on(t,e)}removeListener(t,e){a(this,Oe).removeListener(t,e)}removeListeners(t){a(this,Oe).removeListeners(t)}flush(){return a(this,Oe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,Ne,xe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:E.location.country});const{recv:r,send:n}=(i=a(this,Ne,xe).mediaState)!=null?i:{};r!=null&&r.state&&(r==null?void 0:r.state)!==ta.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==ta.CONNECTED?a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}):f(this,pi,setTimeout(()=>{a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}),f(this,pi,void 0)},zO)),a(this,Ne,xe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),a(this,Ne,xe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ne,xe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ne,xe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ne,xe).mediaJoinAttempted}}),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ne,xe).mediaJoinAttempted}),a(this,Ne,xe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Ne,xe).updateSocketConnectionState("failed")}))}},an=new WeakMap,Oe=new WeakMap,Ne=new WeakSet,xe=function(){return a(this,lt).getValue("connectionHandler")},pi=new WeakMap,lt=new WeakMap,Bc=new WeakSet,Pu=function(t){let e=jy.getSocketEdgeDomain(a(this,lt).getValue("baseURI"));typeof Zs(a(this,lt),"socket_server_base")=="string"&&(e=Zs(a(this,lt),"socket_server_base"));const i=`wss://${e}`,r=new URL(`${i}/ws`),n=this.peerId,s=q(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},n!==t&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>zd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Wc=new WeakSet,Ru=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Kg);let dc=jy;Dl([E.trace("SocketService.connect")],dc.prototype,"connect",1);Dl([E.trace("SocketService.disconnect")],dc.prototype,"disconnect",1);Dl([E.trace("SocketService.sendMessagePromise")],dc.prototype,"sendMessagePromise",1);Dl([E.trace("SocketService.sendMessagePromiseWithTimeout")],dc.prototype,"sendMessagePromiseWithTimeout",1);class YO{constructor(e){p(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var i;const r=kP.fromBinary(e),n=r.meetings.map(s=>{var o;return{id:s.id,title:s.title,participants:(o=s.participants)!=null?o:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(i=r.parentMeeting.participants)!=null?i:[]},meetings:n}}handleTransferPeerRaw({payload:e}){const i=KP.fromBinary(e);return{authToken:i.authToken,meetingId:i.meetingId}}handleMovedPeerRaw({payload:e}){const i=xv.fromBinary(e);return{meetingId:i.meetingId,customParticipantId:i.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Lm.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return UP.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:i}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,IP.toBinary({payloads:e}));return Lm.fromBinary(i).payloads.map(r=>({id:r.id,title:r.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const i=e.map(n=>({id:n})),r=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,LP.toBinary({payloads:i}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const i=yield this.socketService.sendMessagePromise(F.movePeers,GP.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(i.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(i){return{success:!1,error:i}}})}}var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ZO=(t,e,i,r)=>{for(var n=r>1?void 0:r?XO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&QO(e,i,n),n},Vi;class Hy extends Qt{constructor(e){const i=e.getValue("logger");super(i),p(this,"meetings",[]),p(this,"parentMeeting",null),g(this,Vi,void 0),f(this,Vi,e)}get supportsConnectedMeetings(){return a(this,Vi).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 Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Vi).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(n=>n.id)):Promise.resolve());return yield Promise.all(i),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r.map(s=>({id:s}))});return n.success&&this.moveSuccessHandler(e,i,r),n})}moveParticipantsWithCustomPreset(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r});return n.success&&this.moveSuccessHandler(e,i,r.map(s=>s.id)),n})}moveSuccessHandler(e,i,r){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>n.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>n.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(r.map(c=>n.get(c)));return q(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!r.includes(c.id));return q(V({},s),{participants:o})}return s})}}Vi=new WeakMap;ZO([Ft({maxInvocations:60,period:60})],Hy.prototype,"getConnectedMeetings",1);var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,Ip=(t,e,i,r)=>{for(var n=r>1?void 0:r?tN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&eN(e,i,n),n},ke,zg;const Gy=(zg=class{constructor(t){p(this,"connectedMeetings"),g(this,ke,void 0),f(this,ke,t),this.connectedMeetings=new Hy(t)}get telemetry(){return a(this,ke).getValue("telemetry")}get logger(){return a(this,ke).getValue("logger")}static init(t){const e=new Gy(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var r,n,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
22
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,ke).getValue("self").videoEnabled,audio:a(this,ke).getValue("self").audioEnabled};try{a(this,ke).getValue("self").cleanupEvents(),yield a(this,ke).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(r=a(this,ke).getValue("meeting"))==null?void 0:r.meta)==null?void 0:n.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield $y.init(q(V({},a(this,ke).getValue("options")),{cachedUserDetails:null,defaults:q(V(V({},a(this,ke).getValue("options").defaults),c),{mediaHandler:a(this,ke).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,ke).getValue("self");d.self.setName(a(this,ke).getValue("self").name),yield d.join(),l&&d.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: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(i=>({id:i.id,title:i.title,participants:i.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,ke).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(r=>{i.set(r.id,r)}),e.forEach(r=>{i.has(r.id)?i.get(r.id).title=r.title:i.set(r.id,q(V({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(i=>i.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(i=>!e.includes(i.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ke=new WeakMap,zg);let Ol=Gy;Ip([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Ol.prototype,"getConnectedMeetings",1);Ip([E.trace("ConnectedMeetingsController.setupEvents")],Ol.prototype,"setupEvents",1);Ip([E.trace("ConnectedMeetingsController.switchMeeting")],Ol.prototype,"switchMeeting",1);var iN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,Nl=(t,e,i,r)=>{for(var n=r>1?void 0:r?rN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&iN(e,i,n),n};const Vs=class{constructor(t,e,i){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=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=i.getValue("telemetry"),this.logger=i.getValue("logger")}static init(t){return u(this,null,function*(){var e,i;const{peerId:r,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(Iy(t),Ie.isSupported()===!1)throw new I("Browser not supported","0010",l,!0);const h=a1(t,{authToken:s,baseURL:n,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",r),t.setValue("apiClient",h);const m=new j1(t);t.setValue("connectionHandler",m);const v=Vs.createSocketService(t),S=v.connect(),k=h.getUserDetails(),C=h.getPlugins();let b=De.HIVE,M,j="";try{yield Vs.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield S}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:b,meetingTitle:j}=yield h.getRoomNodeData()),M=yield k,l.info(`SFU ${b} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:b})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const W=ID.init(M.preset,!t.getValue("modules").theme),w=JD.init(t,W.viewType,M.preset.permissions),te=Vs.setupControllers(v,t,M,C,j,W,w);A1(W)&&((e=Vs.createRoomNodeClient(t,v).initializeConnection(M.participant.name,o,!1,w))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),E.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ie}=yield te;return P_(),new Vs(n,ie,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:r,overrides:n,meetingId:s,organizationId:o,logger:c}=t.getAllValues(),d=C_(s),l=q(V({entity:Bu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?Dn({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${Bu.PEER}_${i}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch{c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,r,n,s,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:m}=i,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:k}=e.getValue("roomNodeOptions"),{viewType:C,mediaConstraints:{audio:b}}=s;e.setValue("viewType",C),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=b.enableHighBitrate)!=null?c:!1,enableStereo:(d=b.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let M,j,W,w,te,ie,ae,Me,Xe;const Wt=new kO(e,t),A=new YO(t);e.setValue("connectedMeetingsSocketHandler",A);const T=new Ml(e,t),_=new ci(e,t),B=new PO(t),oe=new Py(e,t),He=new RO(e,t),x=new EO(t),P=new Ln(e,t),ue=yield $r.init(e,oe,m,o,s),Jr=yield zv.init(e,ue.self,oe,Wt,n);if(h.participant&&(Me=new ur(e,ue.self,oe,k)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield sr.init(e,_,P,ue.self,Me.participants)),h.internals&&(te=yield mp.init(e)),h.livestream&&s.viewType===Ut.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new ny(e,ue.self,x)),s.viewType!==Ut.Chat){if(h.poll&&(M=yield qv.init(e,ue.self,T)),h.recording&&(ie=new Zv(e,ue.self,oe)),h.stage&&(W=new Yv(e,B,oe,ue.self,Me.participants)),h.plugin){if(!Me)throw new I("The plugin module cannot be initialized without the `participant` module","0102");const Gi=yield r;w=yield sc.init(e,Gi,He,_,j==null?void 0:j.chat,ue.self,Me.participants,n)}if(h.connectedMeetings&&(Xe=yield Ol.init(e)),h.pip){const Gi=yield A_._init(e,ue.self);e.setValue("pip",Gi)}}const Kr={storesManager:new ND(e,He),pollController:M,selfController:ue,metaController:Jr,chatController:j,stageController:W,pluginController:w,recordingController:ie,internalsController:te,livestreamController:ae,participantController:Me,connectedMeetingsController:Xe};return{theme:s,permissions:o,controllers:Kr}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:r}=t.getAllValues(),{sfu:n}=r;return _y(t,n,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:r}=t.getAllValues(),n=["PING"];return new dc(t,{peerId:e,meetingId:i,authToken:r,capabilities:n})}};let lc=Vs;Nl([E.trace("Controller.init")],lc,"init",1);Nl([E.trace("setupFlagsmith")],lc,"setupFlagsmith",1);Nl([E.trace("Controller.createRoomNodeClient")],lc,"createRoomNodeClient",1);Nl([E.trace("Controller.createSocketService")],lc,"createSocketService",1);class nN{constructor(){p(this,"battery"),p(this,"logger"),p(this,"init",e=>u(this,null,function*(){this.logger=e;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(i){e.error("Error getting battery",i)}})),p(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.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 e,i;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(i=this.battery)==null||i.removeEventListener("levelchange",this.updateLevelInfo))})}}const Yg=new nN;function sN(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:i,orgId:r,participantId:n}=JSON.parse(atob(t.split(".")[1]));if(!i)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://${Dn({servicePrefix:"rtk",baseURI:s})}`;return{meetingId:i,orgId:r,participantId:n,baseURI:s,apiBase:o}}catch{throw new I("Invalid auth token","0004")}}var kn,Ls,xs,hl,Hh,qy;class aN{constructor(){g(this,Hh),g(this,kn,new Audio),g(this,Ls,new MediaStream),g(this,xs,new Map),g(this,hl,void 0),a(this,kn).srcObject=a(this,Ls),a(this,kn).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,xs).has(i.id)||(a(this,Ls).addTrack(i),a(this,xs).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,kn).setSinkId(e)}removeTrack(e){const i=a(this,xs).get(e);i&&(a(this,Ls).removeTrack(i),a(this,xs).delete(e))}play(){return u(this,null,function*(){return a(this,kn).srcObject=a(this,Ls),a(this,kn).play().catch(e=>{U(this,Hh,qy).call(this,e)})})}onError(e){f(this,hl,e)}}kn=new WeakMap,Ls=new WeakMap,xs=new WeakMap,hl=new WeakMap,Hh=new WeakSet,qy=function(t){var e;(e=a(this,hl))==null||e.call(this,t)};var Us;class oN extends aN{constructor(){super(),g(this,Us,void 0),f(this,Us,new Map)}addParticipantTrack(e,i){a(this,Us).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,Us).get(e);i&&this.removeTrack(i),a(this,Us).delete(e)}}Us=new WeakMap;var cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,Vl=(t,e,i,r)=>{for(var n=r>1?void 0:r?dN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&cN(e,i,n),n},et,on,Qg;let Hr=(Qg=class{constructor(t,e){g(this,et,void 0),g(this,on,void 0),f(this,on,t),f(this,et,e)}get peerId(){return a(this,on).getValue("peerId")}static initMedia(t={},e=!1,i=void 0){var r;const n=(r=i==null?void 0:i.peerId)!=null?r:Nn(),s=nr.createContext(n,{peerId:n}),o=s.getValue("logger");o.init(s);const c=new cy(o);return c.init(t,e,s),s.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,i,r,n,s,o,c;Ie.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((r=(i=t==null?void 0:t.cachedUserDetails)==null?void 0:i.peerId)!=null?r:Nn()),{authToken:h,baseURI:m}=t,v=sN(h,m),{meetingId:S}=v,k=gl(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const C=Hr.setupContext(l,t,S,k),b=C.getValue("telemetry"),M=C.getValue("logger");tT(M),Yg.init(M),b.init(C,{roomName:S,userId:k.participantId,organizationId:k.orgId,peerId:l},(s=(n=t.modules)==null?void 0:n.tracing)!=null?s:!0),M.init(C),M.info("DyteClient::init::options",{dyteClientInitOptions:q(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
23
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield lc.init(C),W=new Hr(C,j);return C.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=nr.createContext(t,e),c=V(V({},S_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",T_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.23"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new oN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Yg.cleanup(),a(this,on).getValue("peerSessionStore").reset(),(e=a(this,on).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,on).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,on=new WeakMap,Qg);Vl([gt("0002"),qr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hr.prototype,"join",1);Vl([gt("0003")],Hr.prototype,"leave",1);Vl([gt("0001"),qr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hr,"init",1);Hr=Vl([gt("0000")],Hr);const $y=Hr;module.exports=$y;
23
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield lc.init(C),W=new Hr(C,j);return C.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=nr.createContext(t,e),c=V(V({},S_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",T_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.24"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new oN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Yg.cleanup(),a(this,on).getValue("peerSessionStore").reset(),(e=a(this,on).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,on).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,on=new WeakMap,Qg);Vl([gt("0002"),qr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hr.prototype,"join",1);Vl([gt("0003")],Hr.prototype,"leave",1);Vl([gt("0001"),qr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hr,"init",1);Hr=Vl([gt("0000")],Hr);const $y=Hr;module.exports=$y;
package/dist/index.es.js CHANGED
@@ -30351,7 +30351,7 @@ let si = (Bg = class {
30351
30351
  video: true
30352
30352
  };
30353
30353
  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", (c = e.overrides) != null ? c : {}), n.setValue("env", yC({ baseURI: i.baseURI })), n.setValue("defaults", d), n.setValue("onError", e.onError || (() => {
30354
- })), n.setValue("cachedUserDetails", _s(e.cachedUserDetails)), n.setValue("sdkVersion", "3.1.0-staging.23"), (u = e.modules) != null && u.experimentalAudioPlayback && n.setValue("audioPlayback", new sO()), n;
30354
+ })), n.setValue("cachedUserDetails", _s(e.cachedUserDetails)), n.setValue("sdkVersion", "3.1.0-staging.24"), (u = e.modules) != null && u.experimentalAudioPlayback && n.setValue("audioPlayback", new sO()), n;
30355
30355
  }
30356
30356
  join() {
30357
30357
  return l(this, null, function* () {
package/dist/index.rn.js CHANGED
@@ -19,4 +19,4 @@ slogScale: ${n}, isVoice: ${r}, minEnergy: ${a(this,Mr)},
19
19
  maxEnergy: ${a(this,Sn)}`),n===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||n<a(this,Mr))&&f(this,Mr,n),(!a(this,Sn)||n>a(this,Sn))&&f(this,Sn,n),{energy:(n-a(this,Mr))/(a(this,Sn)-a(this,Mr))*10||0,isVoice:r})},Cd=new WeakSet,Nh=function(t){return t<5},Vh=new WeakSet,by=function(t=a(this,$s)){var e;if(!a(this,Fi)||!t){a(this,Js).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Fi)}`);return}const i={producerId:a(this,Fi),energy:Math.round(t),silent:U(e=al,Cd,Nh).call(e,t)};f(this,qo,i.silent),this.reportRequest(i)},gu=new WeakSet,Ag=function(t){const e=Math.log10(t);return Math.round(e)},g(Lh,Cd),g(Lh,gu);const gO=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),r=i.writable.getWriter(),n=48e3,s=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const m=new Float32Array(s*o),v=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:m});c+=s/n*1e6,yield r.ready,yield r.write(v)}catch(m){d&&clearInterval(d),r.releaseLock(),i.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([i]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),i.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch(i){}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const r=i.createOscillator();r.frequency.value=0,r.type="sine";const n=i.createGain();n.gain.value=0,r.connect(n);const s=i.createMediaStreamDestination();n.connect(s),r.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch(i){return}},fO=(t=!1)=>{var e,i;const r=new MediaStream().getVideoTracks()[0],n=document.createElement("canvas");n.height=(e=r==null?void 0:r.getSettings().height)!=null?e:720,n.width=(i=r==null?void 0:r.getSettings().width)!=null?i:1280;const s=n.getContext("2d");s.fillStyle="black",s.fillRect(0,0,n.width,n.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,n.width,n.height)},1e3);const o=n.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,me=(t,e,i,r)=>{for(var n=r>1?void 0:r?yO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&vO(e,i,n),n};const Ht=["video/VP9","video/VP8"];var Lc,xc,yt,J,eo,qi,At,ds,ls,us,Uc,hi,vr,to,hs,ps,Dt,Gt,nn,ms,fu,Dg,vu,Og,yu,Ng,Fc,Su,Tu,Eu,Vg,ku,Lg,bu,xg,wu,Ug,dt,St,gs,io,_u,Fg,Iu,Bg,Cu,Wg;const wy=(Eu=class{constructor(t,e,i){g(this,nn),g(this,fu),g(this,vu),g(this,yu),g(this,Fc),g(this,ku),g(this,bu),g(this,wu),g(this,dt),g(this,gs),g(this,_u),g(this,Iu),g(this,Cu),p(this,"context"),p(this,"authToken"),p(this,"e2ee"),g(this,Lc,void 0),g(this,xc,void 0),g(this,yt,void 0),g(this,J,void 0),g(this,eo,void 0),g(this,qi,void 0),g(this,At,void 0),g(this,ds,void 0),g(this,ls,void 0),g(this,us,void 0),g(this,Uc,void 0),g(this,hi,null),g(this,vr,void 0),g(this,to,void 0),g(this,hs,void 0),g(this,ps,void 0),g(this,Dt,void 0),g(this,Gt,void 0);var r,n;this.context=t;const{socket:s}=i;this.mediaJoined=!1,f(this,hs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ps,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,qi,e),f(this,yt,s),f(this,ds,!1),f(this,J,new hO(t,s,e)),f(this,At,a(this,J).events),f(this,vr,new Set),f(this,Dt,new Map),f(this,ls,!1),f(this,us,new sh(t.getValue("logger"))),e===De.CF&&!navigator.isReactNative&&f(this,Gt,new Lh(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Uc,op(()=>u(this,null,function*(){if(!a(this,nn,ms).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,xc),a(this,Lc),!0,!0);o&&(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,nn,ms).mediaJoined}set mediaJoined(t){a(this,nn,ms).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Dt).clear(),a(this,vr).clear(),f(this,hi,null),a(this,us).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,us,new sh)}joinRoom(t,e){return u(this,arguments,function*(i,r,n=!1,s=!1,o={}){a(this,nn,ms).mediaJoinAttempted=!0,f(this,ds,!0),n&&this.reset();try{return yield a(this,us).push(()=>U(this,fu,Dg).call(this,i,r,s,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,r,n=!1,s={}){return a(this,hi)?a(this,hi):(f(this,hi,(()=>u(this,null,function*(){try{yield U(this,Fc,Su).call(this,i,r,n,s)}catch(o){throw f(this,hi,null),o}}))()),a(this,hi))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,J).stopAllTransports(),f(this,ls,!1),a(this,nn,ms).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,yt).sendMessagePromise(a(this,At).leaveRoom,fI.toBinary(e));(t=nC.fromBinary(i.payload))!=null&&t.closed||this.logger.warn("weird state on peer closed and should not happen")}catch(i){this.logger.error("error on sending leave room request",{error:i})}this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()})}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,r)=>{const n=a(this,J).producerIdToConsumerIdMap.get(r.producerId);return n?(i.push(n),i):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),i)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,r=U(this,dt,St).call(this,i);if(r){const h=yield r;if(a(this,J).producers.has(h)){const m=a(this,J).producers.get(h);if(!m.closed)return yield m.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Ht.filter(h=>h!==e)),s=U(this,Cu,Wg).call(this,t,n),o=Zs(this.context,"disableSimulcast"),c=a(this,qi)===De.CF?Z.ENABLE_CF_SIMULCAST:Z.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,qi)}`),s.encodings=tD(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,qi)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(s.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Dt).delete(i)},l=a(this,J).createProducer(s,d);return U(this,gs,io).call(this,i,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const i=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(i)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(t,i);const r=Ht.filter(n=>{var s,o;return((o=(s=a(this,eo).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,ps).get(n).size>0});return r.length===0&&r.push(Ht[0]),yield Promise.all(r.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const r={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)},s=a(this,J).createProducer(r,n);U(this,gs,io).call(this,Se.SCREENSHARE_VIDEO,s.then(c=>c.id));let o;if(i){const c={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,gs,io).call(this,Se.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([s,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=U(this,dt,St).call(this,Se.MIC);if(e){const s=yield e;if(a(this,J).producers.has(s)){const o=a(this,J).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Gt)&&(a(this,Gt).audioTrack=t,a(this,Gt).producerId=s,a(this,Gt).start());return}yield a(this,J).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=U(this,Iu,Bg).call(this,t),r=()=>{a(this,Dt).delete(Se.MIC)},n=a(this,J).createProducer(i,r);U(this,gs,io).call(this,Se.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,Gt)&&(a(this,Gt).audioTrack=s.track,a(this,Gt).producerId=s.id,a(this,Gt).start())})}catch(e){throw new I(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,dt,St).call(this,Se.MIC),i=a(this,J).producers.get(e);if(!i){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Gt))==null||t.stop();const r={producerId:i.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,dt,St).call(this,Se.WEBCAM),e=yield U(this,dt,St).call(this,Se.WEBCAM_BACKUP),i=a(this,J).producers.get(t),r=a(this,J).producers.get(e);if(!i&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(o))};i&&(i.pause(),n(i)),r&&(r.pause(),n(r))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,dt,St).call(this,Se.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=Se.WEBCAM){const e=yield U(this,dt,St).call(this,t),i=a(this,J).producers.get(e);if(!i){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,i);const r={producerId:i.id,pause:!1};a(this,yt).sendMessage(a(this,At).toggleProducer,yc.toBinary(r))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,i=yield U(this,dt,St).call(this,e);U(this,_u,Fg).call(this,e),i&&(yield a(this,J).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,dt,St).call(this,Se.MIC);e&&(yield a(this,J).closeProducer(e)),(t=a(this,Gt))==null||t.stop(),a(this,Dt).delete(Se.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,dt,St).call(this,Se.SCREENSHARE_VIDEO),e=yield U(this,dt,St).call(this,Se.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,vr).clear(),a(this,Dt).delete(Se.SCREENSHARE_VIDEO),a(this,Dt).delete(Se.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const i=yield U(this,dt,St).call(this,Se.WEBCAM),r=yield U(this,dt,St).call(this,Se.WEBCAM_BACKUP);yield a(this,J).closeProducer(i,{stopTrack:!1}),yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield U(this,dt,St).call(this,Se.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const i={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,yt).sendMessagePromise(a(this,At).globalPinPeer,MI.toBinary(e))}catch(i){this.logger.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,vr).add(t.consumerPeerId),a(this,vr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(r=>this.getConsumers().get(r));a(this,J).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,yt).on(a(this,At).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:r,producerState:n}=NC.fromBinary(t);if(r===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===Bi.AUDIO?"audio/opus":"video/VP8"),n.kind===Bi.VIDEO&&!n.screenShare&&((i=(e=a(this,eo).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Ht[0]))>=0&&a(this,hs).get(Ht[0]).has(r)&&n.mimeType!==Ht[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:q(V({},n),{kind:n.kind===Bi.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,yt).on(a(this,At).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:r,pause:n,producerId:s}}=Mm.fromBinary(t),o=r===Bi.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${n} payload: ${JSON.stringify(Mm.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(o==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:n,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==n&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${n}`),n?(c.pause(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,yt).on(a(this,At).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Hu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,vr).delete(e),a(this,J).consumers.forEach(i=>{i.peerId===e&&i.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,yt).on(a(this,At).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=xC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:e,producerId:i});const r=a(this,J).producerIdToConsumerIdMap.get(i);if(!r){this.logger.warn(`no consumer found for producer:${i}`);return}this.logger.info(`closing consumer ${r}, producer id: ${i}`),a(this,J).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,J).producerIdToConsumerIdMap.delete(i),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:r})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,yt).on(a(this,At).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,ds)&&!a(this,ls)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,Uc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,i)=>{const r=a(this,J).consumers.get(i);r&&this.context.getValue("peerSessionStore").emit(R.CONSUMER_SCORE_UPDATE,{id:i,kind:r.kind,peerId:r.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,i)=>{const r=Array.from(a(this,J).producers.values()).find(n=>n.id===i);r&&this.context.getValue("peerSessionStore").emit(R.PRODUCER_SCORE_UPDATE,{id:i,kind:r.kind,appData:r.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,r,n,s;for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((r=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,ps).get(c).add(t);break}}for(let o=0;o<=Ht.length;o+=1){const c=Ht[o];if(((s=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Ht.length-1){a(this,hs).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,hs).forEach(e=>e.delete(t)),a(this,ps).forEach((e,i)=>{e.delete(t),!(e.size!==0||i===Ht[0])&&this.disableWebcam(i)}))}},Lc=new WeakMap,xc=new WeakMap,yt=new WeakMap,J=new WeakMap,eo=new WeakMap,qi=new WeakMap,At=new WeakMap,ds=new WeakMap,ls=new WeakMap,us=new WeakMap,Uc=new WeakMap,hi=new WeakMap,vr=new WeakMap,to=new WeakMap,hs=new WeakMap,ps=new WeakMap,Dt=new WeakMap,Gt=new WeakMap,nn=new WeakSet,ms=function(){return this.context.getValue("connectionHandler")},fu=new WeakSet,Dg=function(t,e,i,r){return u(this,null,function*(){f(this,xc,t);try{return a(this,hi)?yield a(this,hi):yield U(this,Fc,Su).call(this,t,e,i,r),U(this,yu,Ng).call(this,e),{roomJoined:yield U(this,vu,Og).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{f(this,hi,null)}})},vu=new WeakSet,Og=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,Lc,t.roomUuid),f(this,ls,!0),f(this,ds,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},yu=new WeakSet,Ng=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:q(V({},Ie.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(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Fc=new WeakSet,Su=function(t,e,i,r){return u(this,null,function*(){var n,s;try{(s=a(this,to))!=null||f(this,to,U(n=wy,Tu,Vg).call(n));const o=U(this,ku,Lg).call(this);yield U(this,bu,xg).call(this,t,e,i,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,wu,Ug).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},Tu=new WeakSet,Vg=function(){const{ipInfo:t}=ht();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},ku=new WeakSet,Lg=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=ZD(e);return f(this,eo,i),i},bu=new WeakSet,xg=function(t,e,i,r){return u(this,null,function*(){yield dy((n,s)=>u(this,null,function*(){if(!a(this,yt).isConnected){s(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,J).socketHandler.joinRoom(e,t,r,i,a(this,to))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},wu=new WeakSet,Ug=function(t){return u(this,null,function*(){if(!(a(this,qi)===De.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(fO(!1))),t.canProduceAudio===G.Allowed){const i=gO(!1);i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},dt=new WeakSet,St=function(t){return a(this,Dt).get(t)},gs=new WeakSet,io=function(t,e){return a(this,Dt).set(t,e)},_u=new WeakSet,Fg=function(t){return a(this,Dt).delete(t)},Iu=new WeakSet,Bg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,qi)!==De.CF}},Cu=new WeakSet,Wg=function(t,e){return{track:t,codecOptions:e?e.map(i=>({name:i.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(Eu,Tu),Eu);let le=wy;me([E.trace("MediaNodeClient.reset",{country:E.location.country})],le.prototype,"reset",1);me([E.trace("MediaNodeClient.joinRoom")],le.prototype,"joinRoom",1);me([E.trace("MediaNodeClient.leaveRoom")],le.prototype,"leaveRoom",1);me([E.trace("MediaNodeClient.activatePeers")],le.prototype,"activatePeers",1);me([E.trace("MediaNodeClient.createConsumers")],le.prototype,"createConsumers",1);me([E.trace("MediaNodeClient.closeConsumers")],le.prototype,"closeConsumers",1);me([E.trace("MediaNodeClient._shareWebcam")],le.prototype,"_shareWebcam",1);me([E.trace("MediaNodeClient.shareWebcam")],le.prototype,"shareWebcam",1);me([E.trace("MediaNodeClient.shareScreen")],le.prototype,"shareScreen",1);me([E.trace("MediaNodeClient.shareMic")],le.prototype,"shareMic",1);me([E.trace("MediaNodeClient.pauseMic")],le.prototype,"pauseMic",1);me([E.trace("MediaNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1);me([E.trace("MediaNodeClient.resumeMic")],le.prototype,"resumeMic",1);me([E.trace("MediaNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1);me([E.trace("MediaNodeClient.disableWebcam")],le.prototype,"disableWebcam",1);me([E.trace("HiveClient.disableMic")],le.prototype,"disableMic",1);me([E.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1);me([E.trace("MediaNodeClient.muteSelf")],le.prototype,"muteSelf",1);me([E.trace("MediaNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1);me([E.trace("MediaNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1);me([E.trace("MediaNodeClient.kickPeer")],le.prototype,"kick",1);me([E.trace("MediaNodeClient.kickAllPeers")],le.prototype,"kickAll",1);me([E.trace("MediaNodeClient.muteAll")],le.prototype,"muteAll",1);me([E.trace("MediaNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1);me([E.trace("MediaNodeClient.disableAudio")],le.prototype,"disableAudio",1);me([E.trace("MediaNodeClient.disableVideo")],le.prototype,"disableVideo",1);me([E.trace("MediaNodeClient.pinPeer")],le.prototype,"pinPeer",1);me([E.trace("MediaNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);function _y(t,e,i){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const n=new le(t,e,i);return t.setValue("roomNodeClient",n),n}function Iy(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var SO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,$n=(t,e,i,r)=>{for(var n=r>1?void 0:r?TO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&SO(e,i,n),n},sn,Ai,re,Ot,qt,jg;const Cy=(jg=class{constructor(t,e,i,r){g(this,Ot),p(this,"self"),p(this,"authToken"),g(this,sn,void 0),p(this,"viewType"),g(this,Ai,void 0),g(this,re,void 0);const{socket:n}=i,s=t.getValue("authToken");this.self=e,f(this,re,t),this.viewType=r,this.authToken=s,f(this,sn,n),f(this,Ai,i),e.config.viewType!==Ut.Chat&&this.setupEvents()}get peerId(){return a(this,re).getValue("peerId")}get telemetry(){return a(this,re).getValue("telemetry")}get logger(){return a(this,re).getValue("logger")}get mediaJoined(){return a(this,re).getValue("connectionHandler").mediaJoined}static init(t,e,i,r,n){return u(this,null,function*(){const s=ht(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield st.__init__(t,i,r,n,n.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const m=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(m)}),t.getValue("callstats").devices("AUDIO",m==null?void 0:m.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",m==null?void 0:m.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",m==null?void 0:m.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:_v(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Cy(t,d,e,n.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:r,audioEnabled:n,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(r.canProduceAudio===G.Allowed&&n)try{yield a(this,Ot,qt).shareMic(e),this.self.audioEnabled||a(this,Ot,qt).pauseMic()}catch(d){this.self.disableAudio()}if(r.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Ot,qt).shareWebcam(i);d&&d.id!==i.id&&a(this,re).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Ot,qt).shareWebcam(d)),this.self.videoEnabled||a(this,Ot,qt).pauseWebcam()}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Ot,qt))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}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(t){return u(this,null,function*(){a(this,re).getValue("callstats").callEnded(),a(this,Ot,qt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,re).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,re).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,re).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(e=Nn()),a(this,sn).updateURL(e),a(this,re).getValue("telemetry").resetPeerId(e),ht().setHeader("dyte-tracing-id",e),nr.remapContext(e,a(this,re)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,re).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ai).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ai).on(zc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,re).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,e.patch)})}),a(this,Ai).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ai).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ai).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,re).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:r})=>{var n;const s=(n=i==null?void 0:i.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),a(this,re).getValue("peerSessionStore").on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,re).getValue("callstats").audioOff())})),a(this,re).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,re).getValue("callstats").videoOff())})),a(this,re).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,re).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Ai).joinRoom(this.self);a(this,Ai).socket.flush();const i=hp(e.stageType);if(a(this,re).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,re).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,i;if(t==="rejected"){try{(e=a(this,sn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,re).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,re).notify("stageStatus");try{(i=a(this,sn))==null||i.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}Iy(a(this,re)),yield a(this,re).getValue("roomSocketHandler").cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:r,viewType:n,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,re).getAllValues(),{sfu:d}=c;try{if(n===Ut.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}_y(a(this,re),d,{socket:a(this,sn),peerId:r})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}=this.self.permissions,{roomJoined:v}=(i=yield(e=a(this,Ot,qt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}))!=null?i:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new I("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,re).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Ut.Webinar)&&a(this,Ot,qt)&&(a(this,Ot,qt).mediaJoined&&t!=="disconnected"&&(yield a(this,Ot,qt).leaveRoom()),!(t==="stageLeft"&&e===Ut.Livestream)&&(a(this,Ot,qt).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()})}},sn=new WeakMap,Ai=new WeakMap,re=new WeakMap,Ot=new WeakSet,qt=function(){return a(this,re).getValue("roomNodeClient")},jg);let $r=Cy;$n([E.trace("SelfController.resetSelf")],$r.prototype,"resetSelf",1);$n([E.trace("SelfController.setupEvents")],$r.prototype,"setupEvents",1);$n([E.trace("SelfController.joinRoom")],$r.prototype,"joinRoom",1);$n([E.trace("SelfController.leaveRoom")],$r.prototype,"leaveRoom",1);$n([E.trace("SelfController.joinMediaRoom")],$r.prototype,"joinMediaRoom",1);$n([E.trace("SelfController.leaveMediaRoom")],$r.prototype,"leaveMediaRoom",1);$n([E.trace("SelfController.init")],$r,"init",1);var Pd;class EO{constructor(e){g(this,Pd,void 0),f(this,Pd,e)}on(e,i){let r;e===F.roomPeerCount?r=Om.fromBinary.bind(Om):r=Gm.fromBinary.bind(Gm),a(this,Pd).on(e,({payload:n})=>{const s=r(n);return i(s)})}}Pd=new WeakMap;var Rd,Md;class kO{constructor(e,i){g(this,Rd,void 0),g(this,Md,void 0),f(this,Rd,i),f(this,Md,e)}get logger(){return a(this,Md).getValue("logger")}on(e,i){let r,n;switch(e){case F.transcript:{r=ql.fromBinary.bind(ql),n=ql.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Rd).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Rd=new WeakMap,Md=new WeakMap;var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,wp=(t,e,i,r)=>{for(var n=r>1?void 0:r?wO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&bO(e,i,n),n},Ar,Ao;class Ml{constructor(e,i){g(this,Ar,void 0),g(this,Ao,void 0),f(this,Ar,i),f(this,Ao,e)}get logger(){return a(this,Ao).getValue("logger")}get telemetry(){return a(this,Ao).getValue("telemetry")}getPolls(){return a(this,Ar).sendMessagePromise(Xi.getPolls)}createPoll(e,i,r=!1,n=!1){const s={anonymous:r,hideVotes:n,question:e,options:i};return a(this,Ar).sendMessage(Xi.createPoll,_A.toBinary(s))}votePoll(e,i){const r={index:i,pollId:e};return a(this,Ar).sendMessage(Xi.votePoll,CA.toBinary(r))}on(e,i){let r,n;switch(e){case Xi.updatePoll:case Xi.createPoll:case Xi.votePoll:{r=Ql.fromBinary.bind(Ql),n=Ql.create();break}}a(this,Ar).on(e,({payload:s})=>{let o=n;try{o=r(s)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Ar).removeListeners(e)}}Ar=new WeakMap,Ao=new WeakMap;wp([E.trace("PollSocketHandler.getPolls")],Ml.prototype,"getPolls",1);wp([E.trace("PollSocketHandler.createPoll")],Ml.prototype,"createPoll",1);wp([E.trace("PollSocketHandler.votePoll")],Ml.prototype,"votePoll",1);var _O=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,CO=(t,e,i,r)=>{for(var n=r>1?void 0:r?IO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&_O(e,i,n),n},si;class Py{constructor(e,i){p(this,"socket"),g(this,si,void 0),f(this,si,e),this.socket=i,this.handleSocketEvents(),a(this,si).setValue("roomSocketHandler",this)}get telemetry(){return a(this,si).getValue("telemetry")}get logger(){return a(this,si).getValue("logger")}cleanup(){return u(this,null,function*(){var e;try{(e=this.socket)==null||e.disconnect()}catch(i){this.logger.error("roomSocketHandler::cleanup")}})}joinRoom(e){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const r={capabilities:[],peer:{displayName:(i=e.name)!=null?i:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(F.joinRoom,hP.toBinary(r));try{const{peer:s}=vs.fromBinary((yield n).payload);a(this,si).getValue("connectionHandler").socketJoined=!0,a(this,si).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,si).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,si).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:s}}catch(s){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:s}),new I("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return YP.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var i=e,{id:r}=i,n=gl(i,["id"]);return q(V({},n),{userId:r})})}catch(e){return[]}})}getRoomPeers(e,i,r){return u(this,null,function*(){let n;try{const s={seachQuery:e,limit:i,offset:r},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,iP.toBinary(s));n=$l.fromBinary(o.payload)}catch(s){this.logger.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=$l.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=$l.fromBinary(i.payload)}catch(i){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:i})}return e})}getPeerInfo(e){return u(this,null,function*(){let i;try{const r=yield this.socket.sendMessagePromise(F.getPeerInfo,Lv.toBinary({peerId:e}));i=vs.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return i})}getRoomState(){return u(this,null,function*(){let e=Nm.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomInfo);e=Nm.fromBinary(i.payload)}catch(i){this.logger.error("getRoomState::binary_decode_error",{error:i})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Um.create();try{const i=yield this.socket.sendMessagePromise(F.getRoomStageState);e=Um.fromBinary(i.payload)}catch(i){this.logger.error("getRoomStageState::binary_decode_error",{error:i})}return e})}broadcastMessage(e,i){return u(this,null,function*(){const r={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,ba.toBinary(r))})}broadcastToMeetings(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,ba.toBinary(n))})}broadcastToPeers(e,i,r){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:i,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,ba.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,mP.toBinary({}))})}kick(e){return u(this,null,function*(){const i={peerIds:[e]};this.socket.sendMessage(F.kick,Uv.toBinary(i))})}kickAll(e=!1){return u(this,null,function*(){const i={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,Ov.toBinary(i))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,iR.toBinary(i))}rejectWaitingRoomRequest(e){const i={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,nR.toBinary(i))}updatePermissions(e,i){return u(this,null,function*(){const r={updatePeersPresets:[]};return e.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:i})}),this.socket.sendMessagePromise(zc.updateUserPreset,OR.toBinary(r))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const i=ba.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(R.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode broadcast message:",i)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const i=ba.fromBinary(e);a(this,si).getValue("peerSessionStore").emit(R.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(i.payload)),type:i.type,timestamp:i.timestamp})}catch(i){this.logger.error("failed to decode peer broadcast message:",i)}})}on(e,i){let r,n;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{r=vs.fromBinary.bind(vs),n=vs.create();break}case F.getWaitingRoomRequests:{r=(s,o)=>s?xm.fromBinary(s,o):{requests:[]},n=xm.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{r=Jm.fromBinary.bind(Jm);break}case zc.updateUserPreset:{r=Fm.fromBinary.bind(Fm);break}case ki.peerJoinedBroadcast:case oi.peerJoinedBroadcast:{r=Pm.fromBinary.bind(Pm);break}case ki.selfJoinComplete:case oi.selfJoinComplete:{r=ju.fromBinary.bind(ju);break}case ki.globalPeerPinBroadcast:case oi.globalPeerPinBroadcast:{r=Am.fromBinary.bind(Am);break}case ki.selectedPeer:case oi.selectedPeer:{r=Wu.fromBinary.bind(Wu);break}case ki.selectedPeerDiff:case oi.selectedPeerDiff:{r=Cm.fromBinary.bind(Cm);break}case ki.leaveRoom:case oi.leaveRoom:{r=Hu.fromBinary.bind(Hu);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!r)return i(void 0);try{o=r(s)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}getUserPermissions(e){return u(this,null,function*(){const i={userIds:[e]};try{const r=yield this.socket.sendMessagePromise(zc.getUserPresets,IR.toBinary(i)),n=MR.fromBinary(r.payload).peerPresets[0],s=new TextDecoder().decode(n.preset),o=JSON.parse(s).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}})}}si=new WeakMap;CO([E.trace("RoomSocketHandler.joinRoom")],Py.prototype,"joinRoom",1);var Kt;class PO{constructor(e){g(this,Kt,void 0),f(this,Kt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Kt).sendMessagePromise(F.getStageRequests);return e?Yl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Kt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,Kt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.grantStageAccess,gA.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Kt).sendMessage(F.denyStageAccess,vA.toBinary(i))})}joinStage(){return a(this,Kt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i),void 0,F.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Kt).sendMessagePromise(F.leaveStage,$m.toBinary(i))}on(e,i){let r;switch(e){case F.grantStageAccess:case F.denyStageAccess:{r=void 0;break}case F.getStagePeers:{r=qm.fromBinary.bind(qm);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{r=Yl.fromBinary.bind(Yl);break}case F.peerStageStatusUpdate:{r=Dm.fromBinary.bind(Dm);break}}a(this,Kt).on(e,({payload:n,id:s})=>{if(!n||!r)return i(void 0,s);const o=r(n);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Kt).sendMessagePromise(F.getPeerInfo,Lv.toBinary({peerId:e}));return vs.fromBinary(i.payload)})}}Kt=new WeakMap;var it,Ad;class RO{constructor(e,i){g(this,it,void 0),g(this,Ad,void 0),f(this,it,i),f(this,Ad,e)}get logger(){return a(this,Ad).getValue("logger")}addPlugin(e,i){a(this,it).sendMessage($.addPlugin,DM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,it).sendMessage($.removePlugin,NM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise($.getPlugins);return e?rA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,r){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage($.customPluginEventToRoom,GM.toBinary(n),r)}customPluginEventToPeers(e,i,r,n){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,it).sendMessage($.customPluginEventToPeers,$M.toBinary(s),n)}enablePluginForRoom(e,i){a(this,it).sendMessage($.enablePluginForRoom,LM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,r){a(this,it).sendMessage($.enablePluginForPeers,BM.toBinary({pluginId:e,peerIds:i}),r)}disablePluginForRoom(e,i){a(this,it).sendMessage($.disablePluginForRoom,UM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,r){a(this,it).sendMessage($.disablePluginForPeers,jM.toBinary({pluginId:e,peerIds:i}),r)}storeInsertKeys(e,i,r,n){const s={pluginId:e,storeName:i,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(s),n)}storeGetKeys(e,i,r,n){const s={pluginId:e,storeName:i,getKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeGetKeys,YM.toBinary(s),n)}storeDeleteKeys(e,i,r,n){const s={pluginId:e,storeName:i,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,it).sendMessage($.storeDeleteKeys,XM.toBinary(s),n)}storeDelete(e,i,r){a(this,it).sendMessage($.storeDelete,eA.toBinary({pluginId:e,storeName:i}),r)}getPluginDataOld(e,i){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,r){const n={pluginId:e,storeName:i,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,it).sendMessage($.storeInsertKeys,Bm.toBinary(n))}on(e,i){let r;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{r=Ju.fromBinary.bind(Ju);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{r=Wm.fromBinary.bind(Wm);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{r=Hm.fromBinary.bind(Hm);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{r=jm.fromBinary.bind(jm);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=r(n);return i(o,s)})}}it=new WeakMap,Ad=new WeakMap;var MO=Object.defineProperty,AO=(t,e,i)=>e in t?MO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,DO=(t,e,i)=>(AO(t,typeof e!="symbol"?e+"":e,i),i),_p=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},N=(t,e,i)=>(_p(t,e,"read from private field"),i?i.call(t):e.get(t)),we=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},de=(t,e,i,r)=>(_p(t,e,"write to private field"),r?r.call(t,i):e.set(t,i),i),Re=(t,e,i)=>(_p(t,e,"access private method"),i),ol={},OO={get exports(){return ol},set exports(t){ol=t}},Ks=typeof Reflect=="object"?Reflect:null,Hg=Ks&&typeof Ks.apply=="function"?Ks.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},Dd;Ks&&typeof Ks.ownKeys=="function"?Dd=Ks.ownKeys:Object.getOwnPropertySymbols?Dd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Dd=function(t){return Object.getOwnPropertyNames(t)};function NO(t){console&&console.warn&&console.warn(t)}var Ry=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}OO.exports=pe;ol.once=UO;pe.EventEmitter=pe;pe.prototype._events=void 0;pe.prototype._eventsCount=0;pe.prototype._maxListeners=void 0;var Gg=10;function Al(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return Gg},set:function(t){if(typeof t!="number"||t<0||Ry(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Gg=t}});pe.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};pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ry(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function My(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return My(this)};pe.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var r=t==="error",n=this._events;if(n!==void 0)r=r&&n.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=n[t];if(c===void 0)return!1;if(typeof c=="function")Hg(c,this,e);else for(var d=c.length,l=Vy(c,d),i=0;i<d;++i)Hg(l[i],this,e);return!0};function Ay(t,e,i,r){var n,s,o;if(Al(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),n=My(t),n>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,NO(c)}return t}pe.prototype.addListener=function(t,e){return Ay(this,t,e,!1)};pe.prototype.on=pe.prototype.addListener;pe.prototype.prependListener=function(t,e){return Ay(this,t,e,!0)};function VO(){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 Dy(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},n=VO.bind(r);return n.listener=i,r.wrapFn=n,n}pe.prototype.once=function(t,e){return Al(e),this.on(t,Dy(this,t,e)),this};pe.prototype.prependOnceListener=function(t,e){return Al(e),this.prependListener(t,Dy(this,t,e)),this};pe.prototype.removeListener=function(t,e){var i,r,n,s,o;if(Al(e),r=this._events,r===void 0)return this;if(i=r[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(n=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,n=s;break}if(n<0)return this;n===0?i.shift():LO(i,n),i.length===1&&(r[t]=i[0]),r.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};pe.prototype.off=pe.prototype.removeListener;pe.prototype.removeAllListeners=function(t){var e,i,r;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var n=Object.keys(i),s;for(r=0;r<n.length;++r)s=n[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function Oy(t,e,i){var r=t._events;if(r===void 0)return[];var n=r[e];return n===void 0?[]:typeof n=="function"?i?[n.listener||n]:[n]:i?xO(n):Vy(n,n.length)}pe.prototype.listeners=function(t){return Oy(this,t,!0)};pe.prototype.rawListeners=function(t){return Oy(this,t,!1)};pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Ny.call(t,e)};pe.prototype.listenerCount=Ny;function Ny(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}pe.prototype.eventNames=function(){return this._eventsCount>0?Dd(this._events):[]};function Vy(t,e){for(var i=new Array(e),r=0;r<e;++r)i[r]=t[r];return i}function LO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function xO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function UO(t,e){return new Promise(function(i,r){function n(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),i([].slice.call(arguments))}Ly(t,e,s,{once:!0}),e!=="error"&&FO(t,n,{once:!0})})}function FO(t,e,i){typeof t.on=="function"&&Ly(t,"error",e,i)}function Ly(t,e,i,r){if(typeof t.on=="function")r.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){r.once&&t.removeEventListener(e,n),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class BO extends y{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 qg=new BO;class xy{static encode(e){return qg.toBinary(e)}static decode(e){return qg.fromBinary(new Uint8Array(e))}}function WO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Dr;class jO{constructor(e={}){DO(this,"opts"),we(this,Dr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,Dr,0)}wait(){return u(this,null,function*(){de(this,Dr,N(this,Dr)+1);const e=WO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*QS(2,N(this,Dr))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return N(this,Dr)}reset(){de(this,Dr,0)}}Dr=new WeakMap;const yr={debug:0,info:1,warn:2,error:3};var Tn,En;class HO{constructor(e){we(this,Tn,void 0),we(this,En,void 0),de(this,Tn,console),de(this,En,e)}debug(...e){yr[N(this,En)]>yr.debug||N(this,Tn).debug("[Sockrates]:",...e)}info(...e){yr[N(this,En)]>yr.info||N(this,Tn).info("[Sockrates]:",...e)}warn(...e){yr[N(this,En)]>yr.warn||N(this,Tn).warn("[Sockrates]:",...e)}error(...e){yr[N(this,En)]>yr.error||N(this,Tn).error("[Sockrates]:",...e)}}Tn=new WeakMap,En=new WeakMap;var Uy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Uy||{});const GO="2",qO="3";var Le,Os,Pe,je,Or,rt,rr,Ur,Ei,Ns,Qi,xh,Fy,Do,Od,Uh,By,Fh,$g,cl,Bh,Wh,Wy,$o,Nd,Jo,dl,ll,jh,zs,Ko,zo,ul;class $O{constructor(e,i){var r;we(this,xh),we(this,Do),we(this,Uh),we(this,Fh),we(this,cl),we(this,Wh),we(this,$o),we(this,Jo),we(this,ll),we(this,zs),we(this,zo),we(this,Le,void 0),we(this,Os,void 0),we(this,Pe,void 0),we(this,je,void 0),we(this,Or,void 0),we(this,rt,void 0),we(this,rr,void 0),we(this,Ur,void 0),we(this,Ei,void 0),we(this,Ns,void 0),we(this,Qi,void 0);var n,s,o,c,d,l,h,m,v;de(this,Os,e),de(this,Or,[]),de(this,rt,new ol),de(this,rr,!0),de(this,Ei,!1),de(this,Pe,i!=null?i:{}),(n=N(this,Pe)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,Pe)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Pe)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Pe)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Pe)).debug!=null||(d.debug=!0),(l=N(this,Pe)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Pe)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=N(this,Pe)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(v=N(this,Pe)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,Ur,{code:void 0,reason:void 0}),de(this,je,(r=N(this,Pe).logger)!=null?r:new HO(N(this,Pe).debug?"debug":"info")),de(this,Qi,new jO)}get readyState(){var e;return(e=N(this,Le))==null?void 0:e.readyState}get url(){return N(this,Os)}updateURL(e){de(this,Os,e),Re(this,Wh,Wy).call(this)}get config(){return N(this,Pe)}get sendQueue(){return N(this,Or)}flush(){if(!N(this,Pe).queueOnDisconnect)return!1;const e=[];return N(this,Or).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),de(this,Or,e),N(this,Or)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,je).debug("Websocket was already connecting or connected.");return}if(N(this,rr)!==!1)return new Promise((i,r)=>{Re(this,zs,Ko).call(this),Re(this,zo,ul).call(this);try{de(this,Le,new WebSocket(Re(this,xh,Fy).call(this,N(this,Os)))),N(this,Le).binaryType="arraybuffer",N(this,je).debug("Connecting");const n=setTimeout(()=>{N(this,je).debug("Connection timeout. Closing socket"),de(this,rr,!0),Re(this,zo,ul).call(this),N(this,Le).close(3001,"Connection Timeout"),N(this,Pe).autoReconnect&&!N(this,Ei)&&(N(this,rt).emit("reconnecting"),Re(this,$o,Nd).call(this)),r(new Error("Connection timed out!"))},N(this,Pe).connectionTimeout);N(this,Le).onopen=()=>{N(this,je).debug(`Ready State: ${Uy[N(this,Le).readyState]}`),n&&clearTimeout(n),Re(this,ll,jh).call(this),de(this,Ur,{code:void 0,reason:void 0}),N(this,rt).emit("connected"),N(this,Pe).flushOnReconnect&&this.flush(),i()},N(this,Le).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;r(c),N(this,je).debug("Socket closed. Close event:",{event:s}),N(this,je).debug(`Connection closed code: ${o}`),N(this,je).debug(`Connection closed reason: ${c}`),N(this,Ei)||Re(this,cl,Bh).call(this,o,c)}catch(o){Re(this,Do,Od).call(this,o)}},N(this,Le).onerror=s=>{Re(this,Do,Od).call(this,s)},N(this,Le).onmessage=s=>Re(this,Uh,By).call(this,s)}catch(n){Re(this,Do,Od).call(this,n,r)}})})}send(e,i,r,n){const s={event:e,id:i,payload:r,metadata:n};if(N(this,Pe).queueOnDisconnect&&(!N(this,Le)||N(this,Le).readyState!==1))return N(this,je).debug("Queuing message since socket is not connected!",s),N(this,Or).push(s),!1;const o=xy.encode(s);return Re(this,Jo,dl).call(this,o)}emit(e,i,r,n){return this.send(e,i,r,n)}sendRaw(e){return Re(this,Jo,dl).call(this,e)}receive(e,i){return N(this,rt).on(e.toString(),i)}on(e,i){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,rt).on(e,i);return}this.receive(e,i)}removeAllListeners(){N(this,rt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){N(this,rt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,rt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){de(this,rr,!1),Re(this,zs,Ko).call(this),this.removeAllListeners(),de(this,Ur,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Le).close(1e3,"Sockrates disconnect method called.")}}Le=new WeakMap,Os=new WeakMap,Pe=new WeakMap,je=new WeakMap,Or=new WeakMap,rt=new WeakMap,rr=new WeakMap,Ur=new WeakMap,Ei=new WeakMap,Ns=new WeakMap,Qi=new WeakMap,xh=new WeakSet,Fy=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Do=new WeakSet,Od=function(t,e){N(this,je).error("Error:",{error:t}),N(this,rt).emit("errored",{error:t}),e==null||e(t)},Uh=new WeakSet,By=function(t){if(Re(this,ll,jh).call(this),t.data===GO){N(this,je).debug("Received ping from server"),Re(this,Jo,dl).call(this,qO);return}const e=xy.decode(t.data),{id:i,payload:r}=e;N(this,je).debug("Received message",{event:e.event,messageID:i}),N(this,rt).emit(e.event.toString(),{id:i,payload:r})},Fh=new WeakSet,$g=function(){return N(this,Le).readyState===1},cl=new WeakSet,Bh=function(t,e){de(this,Ur,{reason:e,code:t}),N(this,rt).emit("disconnected",{code:t,reason:e})},Wh=new WeakSet,Wy=function(){const{reason:t,code:e}=N(this,Ur);e&&e!==1e3&&N(this,rr)&&N(this,Pe).autoReconnect&&!N(this,Ei)&&(N(this,je).debug(`Triggering reconnection due to ${t}.`),N(this,rt).emit("reconnecting"),Re(this,$o,Nd).call(this))},$o=new WeakSet,Nd=function(t=!0){return u(this,null,function*(){if(t&&N(this,Ei)){N(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,Ei)||N(this,Qi).reset(),N(this,Pe).maxReconnectionAttempts!==null&&N(this,Qi).getAttempts()>=N(this,Pe).maxReconnectionAttempts){N(this,rt).emit("failed"),de(this,Ei,!1);return}de(this,Ei,!0),Re(this,zo,ul).call(this),Re(this,zs,Ko).call(this);try{if(yield N(this,Qi).wait(),N(this,rr)===!1)return;if(N(this,je).debug(`Reconnection attempt ${N(this,Qi).getAttempts()}`),N(this,rt).emit("reconnectAttempt",{attempt:N(this,Qi).getAttempts()}),yield this.connect(),!Re(this,Fh,$g).call(this))throw Error("Reconnect Failed");de(this,Ei,!1),de(this,Ur,{code:void 0,reason:void 0}),N(this,rt).emit("reconnected")}catch(e){N(this,je).debug("Failed to reconnect."),N(this,rt).emit("reconnectFailure",{attempt:N(this,Qi).getAttempts()}),Re(this,$o,Nd).call(this,!1)}})},Jo=new WeakSet,dl=function(t){try{return N(this,Le).send(t),!0}catch(e){return N(this,je).error(e.message),!1}},ll=new WeakSet,jh=function(){this.config.disconnectOnPingTimeout&&(N(this,je).debug("Resetting ping timeout"),Re(this,zs,Ko).call(this),de(this,Ns,setTimeout(()=>{var t;N(this,je).debug("Disconnecting the socket due to ping timeout"),de(this,rr,!0);const e=3002,i="Ping timeout";(t=N(this,Le))==null||t.close(e,i),Re(this,cl,Bh).call(this,e,i)},N(this,Pe).pingTimeout)))},zs=new WeakSet,Ko=function(){N(this,Ns)&&(clearTimeout(N(this,Ns)),de(this,Ns,void 0))},zo=new WeakSet,ul=function(){N(this,Le)&&(N(this,Le).onopen=void 0,N(this,Le).onerror=void 0,N(this,Le).onmessage=void 0,N(this,Le).onclose=void 0)};var JO=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,Dl=(t,e,i,r)=>{for(var n=r>1?void 0:r?KO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&JO(e,i,n),n};const Jg=65535,zO=3e3;var an,Oe,Ne,xe,pi,lt,Bc,Pu,Wc,Ru,Kg;const jy=(Kg=class{constructor(t,{peerId:e,meetingId:i,authToken:r,capabilities:n}){g(this,Ne),g(this,Bc),g(this,Wc),g(this,an,void 0),g(this,Oe,void 0),p(this,"roomName"),p(this,"authToken"),p(this,"capabilities"),g(this,pi,void 0),g(this,lt,void 0);var s;if(!e||!i||!r)throw new I("peerId, meetingId, or authToken can not be empty","0404");f(this,pi,void 0),f(this,lt,t),this.capabilities=n,this.roomName=i,this.authToken=r,f(this,an,U(this,Bc,Pu).call(this,e)),f(this,Oe,new $O(a(this,an),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ne,xe).socketJoinAttempted}set joinAttempted(t){a(this,Ne,xe).socketJoinAttempted=t}get telemetry(){return a(this,lt).getValue("telemetry")}get logger(){return a(this,lt).getValue("logger")}get peerId(){return a(this,lt).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,an,U(this,Bc,Pu).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Oe).updateURL(a(this,an))}static getSocketEdgeDomain(t){return Dn({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,an)}connect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!0,yield a(this,Oe).connect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!1,a(this,Oe).disconnect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Oe).readyState===1}catch(t){return!1}}sendMessage(t,e,i){const r={};return a(this,lt).getValue("telemetry").injectContext(r),a(this,Oe).send(t,i!=null?i:U(this,Wc,Ru).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,i,r){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:n,protobuf:e,messageId:i,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:r,resp:n}){const s=n!=null?n:t;return new Promise((o,c)=>{const d=(S,k)=>{a(this,Oe).removeListener(s,S),a(this,Oe).removeListener(Jg,k),a(this,Oe).removeListener(oi.errorResponse,k),a(this,Oe).removeListener(ki.errorResponse,k)},l=r!=null?r:U(this,Wc,Ru).call(this),h={};a(this,lt).getValue("telemetry").injectContext(h);const m=({id:S,payload:k})=>{if(l===S){let C;try{const b=KI.fromBinary(k);C=new Error(b.errorMessage)}catch(b){C=new Error("failed to parse error message",{cause:b});try{const M=zC.fromBinary(k);C=new Error(M.message)}catch(M){C=new Error("failed to parse error message",{cause:M})}}c(C),d(v,m)}},v=({id:S,payload:k})=>{l===S&&(o({id:S,payload:k}),d(v,m))};a(this,Oe).on(s,v),a(this,Oe).on(Jg,m),a(this,Oe).on(oi.errorResponse,m),a(this,Oe).on(ki.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Oe).send(t,l,i,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Oe).on(t,e)}onStateEvent(t,e){a(this,Oe).on(t,e)}removeListener(t,e){a(this,Oe).removeListener(t,e)}removeListeners(t){a(this,Oe).removeListeners(t)}flush(){return a(this,Oe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,Ne,xe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:E.location.country});const{recv:r,send:n}=(i=a(this,Ne,xe).mediaState)!=null?i:{};r!=null&&r.state&&(r==null?void 0:r.state)!==ta.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==ta.CONNECTED?a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}):f(this,pi,setTimeout(()=>{a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}),f(this,pi,void 0)},zO)),a(this,Ne,xe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),a(this,Ne,xe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ne,xe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ne,xe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ne,xe).mediaJoinAttempted}}),a(this,pi)&&(clearTimeout(a(this,pi)),f(this,pi,void 0)),a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ne,xe).mediaJoinAttempted}),a(this,Ne,xe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),a(this,lt).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Ne,xe).updateSocketConnectionState("failed")}))}},an=new WeakMap,Oe=new WeakMap,Ne=new WeakSet,xe=function(){return a(this,lt).getValue("connectionHandler")},pi=new WeakMap,lt=new WeakMap,Bc=new WeakSet,Pu=function(t){let e=jy.getSocketEdgeDomain(a(this,lt).getValue("baseURI"));typeof Zs(a(this,lt),"socket_server_base")=="string"&&(e=Zs(a(this,lt),"socket_server_base"));const i=`wss://${e}`,r=new URL(`${i}/ws`),n=this.peerId,s=q(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},n!==t&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>zd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},Wc=new WeakSet,Ru=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Kg);let dc=jy;Dl([E.trace("SocketService.connect")],dc.prototype,"connect",1);Dl([E.trace("SocketService.disconnect")],dc.prototype,"disconnect",1);Dl([E.trace("SocketService.sendMessagePromise")],dc.prototype,"sendMessagePromise",1);Dl([E.trace("SocketService.sendMessagePromiseWithTimeout")],dc.prototype,"sendMessagePromiseWithTimeout",1);class YO{constructor(e){p(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var i;const r=kP.fromBinary(e),n=r.meetings.map(s=>{var o;return{id:s.id,title:s.title,participants:(o=s.participants)!=null?o:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(i=r.parentMeeting.participants)!=null?i:[]},meetings:n}}handleTransferPeerRaw({payload:e}){const i=KP.fromBinary(e);return{authToken:i.authToken,meetingId:i.meetingId}}handleMovedPeerRaw({payload:e}){const i=xv.fromBinary(e);return{meetingId:i.meetingId,customParticipantId:i.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Lm.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return UP.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:i}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,IP.toBinary({payloads:e}));return Lm.fromBinary(i).payloads.map(r=>({id:r.id,title:r.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const i=e.map(n=>({id:n})),r=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,LP.toBinary({payloads:i}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const i=yield this.socketService.sendMessagePromise(F.movePeers,GP.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(i.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(i){return{success:!1,error:i}}})}}var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ZO=(t,e,i,r)=>{for(var n=r>1?void 0:r?XO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&QO(e,i,n),n},Vi;class Hy extends Qt{constructor(e){const i=e.getValue("logger");super(i),p(this,"meetings",[]),p(this,"parentMeeting",null),g(this,Vi,void 0),f(this,Vi,e)}get supportsConnectedMeetings(){return a(this,Vi).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.
20
20
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Vi).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(n=>n.id)):Promise.resolve());return yield Promise.all(i),yield a(this,Vi).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r.map(s=>({id:s}))});return n.success&&this.moveSuccessHandler(e,i,r),n})}moveParticipantsWithCustomPreset(e,i,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Vi).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:r});return n.success&&this.moveSuccessHandler(e,i,r.map(s=>s.id)),n})}moveSuccessHandler(e,i,r){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>n.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>n.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(r.map(c=>n.get(c)));return q(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!r.includes(c.id));return q(V({},s),{participants:o})}return s})}}Vi=new WeakMap;ZO([Ft({maxInvocations:60,period:60})],Hy.prototype,"getConnectedMeetings",1);var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,Ip=(t,e,i,r)=>{for(var n=r>1?void 0:r?tN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&eN(e,i,n),n},ke,zg;const Gy=(zg=class{constructor(t){p(this,"connectedMeetings"),g(this,ke,void 0),f(this,ke,t),this.connectedMeetings=new Hy(t)}get telemetry(){return a(this,ke).getValue("telemetry")}get logger(){return a(this,ke).getValue("logger")}static init(t){const e=new Gy(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var r,n,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,ke).getValue("self").videoEnabled,audio:a(this,ke).getValue("self").audioEnabled};try{a(this,ke).getValue("self").cleanupEvents(),yield a(this,ke).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(r=a(this,ke).getValue("meeting"))==null?void 0:r.meta)==null?void 0:n.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield $y.init(q(V({},a(this,ke).getValue("options")),{cachedUserDetails:null,defaults:q(V(V({},a(this,ke).getValue("options").defaults),c),{mediaHandler:a(this,ke).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,ke).getValue("self");d.self.setName(a(this,ke).getValue("self").name),yield d.join(),l&&d.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: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(i=>({id:i.id,title:i.title,participants:i.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,ke).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(r=>{i.set(r.id,r)}),e.forEach(r=>{i.has(r.id)?i.get(r.id).title=r.title:i.set(r.id,q(V({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(i=>i.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(i=>!e.includes(i.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ke=new WeakMap,zg);let Ol=Gy;Ip([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Ol.prototype,"getConnectedMeetings",1);Ip([E.trace("ConnectedMeetingsController.setupEvents")],Ol.prototype,"setupEvents",1);Ip([E.trace("ConnectedMeetingsController.switchMeeting")],Ol.prototype,"switchMeeting",1);var iN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,Nl=(t,e,i,r)=>{for(var n=r>1?void 0:r?rN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&iN(e,i,n),n};const Vs=class{constructor(t,e,i){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=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=i.getValue("telemetry"),this.logger=i.getValue("logger")}static init(t){return u(this,null,function*(){var e,i;const{peerId:r,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(Iy(t),Ie.isSupported()===!1)throw new I("Browser not supported","0010",l,!0);const h=a1(t,{authToken:s,baseURL:n,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",r),t.setValue("apiClient",h);const m=new j1(t);t.setValue("connectionHandler",m);const v=Vs.createSocketService(t),S=v.connect(),k=h.getUserDetails(),C=h.getPlugins();let b=De.HIVE,M,j="";try{yield Vs.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield S}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:b,meetingTitle:j}=yield h.getRoomNodeData()),M=yield k,l.info(`SFU ${b} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:b})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const W=ID.init(M.preset,!t.getValue("modules").theme),w=JD.init(t,W.viewType,M.preset.permissions),te=Vs.setupControllers(v,t,M,C,j,W,w);A1(W)&&((e=Vs.createRoomNodeClient(t,v).initializeConnection(M.participant.name,o,!1,w))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),E.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ie}=yield te;return P_(),new Vs(n,ie,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:r,overrides:n,meetingId:s,organizationId:o,logger:c}=t.getAllValues(),d=C_(s),l=q(V({entity:Bu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?Dn({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${Bu.PEER}_${i}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch(h){c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,r,n,s,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:m}=i,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:k}=e.getValue("roomNodeOptions"),{viewType:C,mediaConstraints:{audio:b}}=s;e.setValue("viewType",C),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=b.enableHighBitrate)!=null?c:!1,enableStereo:(d=b.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let M,j,W,w,te,ie,ae,Me,Xe;const Wt=new kO(e,t),A=new YO(t);e.setValue("connectedMeetingsSocketHandler",A);const T=new Ml(e,t),_=new ci(e,t),B=new PO(t),oe=new Py(e,t),He=new RO(e,t),x=new EO(t),P=new Ln(e,t),ue=yield $r.init(e,oe,m,o,s),Jr=yield zv.init(e,ue.self,oe,Wt,n);if(h.participant&&(Me=new ur(e,ue.self,oe,k)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield sr.init(e,_,P,ue.self,Me.participants)),h.internals&&(te=yield mp.init(e)),h.livestream&&s.viewType===Ut.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new ny(e,ue.self,x)),s.viewType!==Ut.Chat){if(h.poll&&(M=yield qv.init(e,ue.self,T)),h.recording&&(ie=new Zv(e,ue.self,oe)),h.stage&&(W=new Yv(e,B,oe,ue.self,Me.participants)),h.plugin){if(!Me)throw new I("The plugin module cannot be initialized without the `participant` module","0102");const Gi=yield r;w=yield sc.init(e,Gi,He,_,j==null?void 0:j.chat,ue.self,Me.participants,n)}if(h.connectedMeetings&&(Xe=yield Ol.init(e)),h.pip){const Gi=yield A_._init(e,ue.self);e.setValue("pip",Gi)}}const Kr={storesManager:new ND(e,He),pollController:M,selfController:ue,metaController:Jr,chatController:j,stageController:W,pluginController:w,recordingController:ie,internalsController:te,livestreamController:ae,participantController:Me,connectedMeetingsController:Xe};return{theme:s,permissions:o,controllers:Kr}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:r}=t.getAllValues(),{sfu:n}=r;return _y(t,n,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:r}=t.getAllValues(),n=["PING"];return new dc(t,{peerId:e,meetingId:i,authToken:r,capabilities:n})}};let lc=Vs;Nl([E.trace("Controller.init")],lc,"init",1);Nl([E.trace("setupFlagsmith")],lc,"setupFlagsmith",1);Nl([E.trace("Controller.createRoomNodeClient")],lc,"createRoomNodeClient",1);Nl([E.trace("Controller.createSocketService")],lc,"createSocketService",1);class nN{constructor(){p(this,"battery"),p(this,"logger"),p(this,"init",e=>u(this,null,function*(){this.logger=e;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(i){e.error("Error getting battery",i)}})),p(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.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 e,i;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(i=this.battery)==null||i.removeEventListener("levelchange",this.updateLevelInfo))})}}const Yg=new nN;function sN(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:i,orgId:r,participantId:n}=JSON.parse(atob(t.split(".")[1]));if(!i)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://${Dn({servicePrefix:"rtk",baseURI:s})}`;return{meetingId:i,orgId:r,participantId:n,baseURI:s,apiBase:o}}catch(i){throw new I("Invalid auth token","0004")}}var kn,Ls,xs,hl,Hh,qy;class aN{constructor(){g(this,Hh),g(this,kn,new Audio),g(this,Ls,new MediaStream),g(this,xs,new Map),g(this,hl,void 0),a(this,kn).srcObject=a(this,Ls),a(this,kn).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(i=>{a(this,xs).has(i.id)||(a(this,Ls).addTrack(i),a(this,xs).set(i.id,i))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,kn).setSinkId(e)}removeTrack(e){const i=a(this,xs).get(e);i&&(a(this,Ls).removeTrack(i),a(this,xs).delete(e))}play(){return u(this,null,function*(){return a(this,kn).srcObject=a(this,Ls),a(this,kn).play().catch(e=>{U(this,Hh,qy).call(this,e)})})}onError(e){f(this,hl,e)}}kn=new WeakMap,Ls=new WeakMap,xs=new WeakMap,hl=new WeakMap,Hh=new WeakSet,qy=function(t){var e;(e=a(this,hl))==null||e.call(this,t)};var Us;class oN extends aN{constructor(){super(),g(this,Us,void 0),f(this,Us,new Map)}addParticipantTrack(e,i){a(this,Us).set(e,i.id),this.playTracks([i])}removeParticipantTrack(e){const i=a(this,Us).get(e);i&&this.removeTrack(i),a(this,Us).delete(e)}}Us=new WeakMap;var cN=Object.defineProperty,dN=Object.getOwnPropertyDescriptor,Vl=(t,e,i,r)=>{for(var n=r>1?void 0:r?dN(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(r?o(e,i,n):o(n))||n);return r&&n&&cN(e,i,n),n},et,on,Qg;let Hr=(Qg=class{constructor(t,e){g(this,et,void 0),g(this,on,void 0),f(this,on,t),f(this,et,e)}get peerId(){return a(this,on).getValue("peerId")}static initMedia(t={},e=!1,i=void 0){var r;const n=(r=i==null?void 0:i.peerId)!=null?r:Nn(),s=nr.createContext(n,{peerId:n}),o=s.getValue("logger");o.init(s);const c=new cy(o);return c.init(t,e,s),s.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,i,r,n,s,o,c;Ie.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((r=(i=t==null?void 0:t.cachedUserDetails)==null?void 0:i.peerId)!=null?r:Nn()),{authToken:h,baseURI:m}=t,v=sN(h,m),{meetingId:S}=v,k=gl(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const C=Hr.setupContext(l,t,S,k),b=C.getValue("telemetry"),M=C.getValue("logger");tT(M),Yg.init(M),b.init(C,{roomName:S,userId:k.participantId,organizationId:k.orgId,peerId:l},(s=(n=t.modules)==null?void 0:n.tracing)!=null?s:!0),M.init(C),M.info("DyteClient::init::options",{dyteClientInitOptions:q(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
22
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield lc.init(C),W=new Hr(C,j);return C.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=nr.createContext(t,e),c=V(V({},S_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",T_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.23"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new oN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Yg.cleanup(),a(this,on).getValue("peerSessionStore").reset(),(e=a(this,on).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,on).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,on=new WeakMap,Qg);Vl([gt("0002"),qr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hr.prototype,"join",1);Vl([gt("0003")],Hr.prototype,"leave",1);Vl([gt("0001"),qr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hr,"init",1);Hr=Vl([gt("0000")],Hr);const $y=Hr;module.exports=$y;
22
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield lc.init(C),W=new Hr(C,j);return C.setValue("meeting",W),W})}static setupContext(t,e,i,r){var n,s;const o=nr.createContext(t,e),c=V(V({},S_),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",i),o.setValue("apiBase",r.apiBase),o.setValue("baseURI",r.baseURI),o.setValue("userId",r.participantId),o.setValue("organizationId",r.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",T_({baseURI:r.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",wi(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.0-staging.24"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new oN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Yg.cleanup(),a(this,on).getValue("peerSessionStore").reset(),(e=a(this,on).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:i}=a(this,et);return i.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,on).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,on=new WeakMap,Qg);Vl([gt("0002"),qr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Hr.prototype,"join",1);Vl([gt("0003")],Hr.prototype,"leave",1);Vl([gt("0001"),qr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Hr,"init",1);Hr=Vl([gt("0000")],Hr);const $y=Hr;module.exports=$y;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.1.0-staging.23",
3
+ "version": "1.1.0-staging.24",
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",