@cloudflare/realtimekit 1.0.2-staging.6 → 1.0.2-staging.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -19,4 +19,4 @@ slogScale: ${r}, isVoice: ${n}, minEnergy: ${a(this,An)},
19
19
  maxEnergy: ${a(this,Ir)}`),r===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,An)||r<a(this,An))&&v(this,An,r),(!a(this,Ir)||r>a(this,Ir))&&v(this,Ir,r),{energy:(r-a(this,An))/(a(this,Ir)-a(this,An))*10||0,isVoice:n})},Ud=new WeakSet,Ph=function(t){return t<5},Rh=new WeakSet,Mv=function(t=a(this,_s)){var e;if(!a(this,xi)||!t){z.hasFeature(ne.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&l.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xi)}`);return}const i={producerId:a(this,xi),energy:Math.round(t),silent:B(e=Fd,Ud,Ph).call(e,t)};v(this,fo,i.silent),this.reportRequest(i)},Mh=new WeakSet,Av=function(t){const e=Math.log10(t);return Math.round(e)},f(Ah,Ud),f(Ah,Mh);const UD=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),n=i.writable.getWriter(),r=48e3,s=128,o=1;let c=0,d=null;const h=()=>u(void 0,null,function*(){try{const g=new Float32Array(s*o),y=new window.AudioData({format:"f32",sampleRate:r,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:g});c+=s/r*1e6,yield n.ready,yield n.write(y)}catch(g){d&&clearInterval(d),n.releaseLock(),i.writable.abort()}});d=window.setInterval(h,100);const p=new MediaStream([i]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),n.releaseLock(),i.writable.abort()}),p}catch(i){}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const n=i.createOscillator();n.frequency.value=0,n.type="sine";const r=i.createGain();r.gain.value=0,n.connect(r);const s=i.createMediaStreamDestination();r.connect(s),n.start();const o=s.stream.getAudioTracks()[0];return o?(o.enabled=t,o):void 0}catch(i){return}},FD=(t=!1)=>{var e,i;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(e=n==null?void 0:n.getSettings().height)!=null?e:720,r.width=(i=n==null?void 0:n.getSettings().width)!=null?i:1280;const s=r.getContext("2d");s.fillStyle="black",s.fillRect(0,0,r.width,r.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,r.width,r.height)},1e3);const o=r.captureStream().getVideoTracks()[0];return o.enabled=t,o};var BD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,me=(t,e,i,n)=>{for(var r=n>1?void 0:n?WD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&BD(e,i,r),r};const Vi=["video/VP9","video/VP8"];var Bd,Wd,It,Q,vo,nn,xt,ws,Is,Cs,jd,Ei,Dn,yo,Ps,Rs,Vt,zt,Cr,Ms,Dh,Dv,Oh,Ov,Nh,Nv,Hd,Lh,xh,Vh,Lv,Uh,xv,Fh,Vv,Bh,Uv,mt,Ct,As,So,Wh,Fv,jh,Bv,Hh,Wv;const jv=(Vh=class{constructor(t,e,i){f(this,Cr),f(this,Dh),f(this,Oh),f(this,Nh),f(this,Hd),f(this,Uh),f(this,Fh),f(this,Bh),f(this,mt),f(this,As),f(this,Wh),f(this,jh),f(this,Hh),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),f(this,Bd,void 0),f(this,Wd,void 0),f(this,It,void 0),f(this,Q,void 0),f(this,vo,void 0),f(this,nn,void 0),f(this,xt,void 0),f(this,ws,void 0),f(this,Is,void 0),f(this,Cs,void 0),f(this,jd,void 0),f(this,Ei,null),f(this,Dn,void 0),f(this,yo,void 0),f(this,Ps,void 0),f(this,Rs,void 0),f(this,Vt,void 0),f(this,zt,void 0);var n,r;this.context=t;const{socket:s}=i;this.mediaJoined=!1,v(this,Ps,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Rs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,nn,e),v(this,It,s),v(this,ws,!1),v(this,Q,new LD(t,s,e)),v(this,xt,a(this,Q).events),v(this,Dn,new Set),v(this,Vt,new Map),v(this,Is,!1),v(this,Cs,new zu),e===Ne.CF&&!navigator.isReactNative&&v(this,zt,new Ah(a(this,Q).socketHandler.audioActivity.bind(a(this,Q).socketHandler))),this.e2ee=(r=(n=t.getValue("modules").e2ee)==null?void 0:n.enabled)!=null?r:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,jd,Hl(()=>u(this,null,function*(){if(!a(this,Cr,Ms).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Wd),a(this,Bd),!0,!0);o&&(P.emit(R.RESET_PRODUCER_STATE),P.emit(R.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return a(this,Cr,Ms).mediaJoined}set mediaJoined(t){a(this,Cr,Ms).mediaJoined=t}reset(){a(this,Q).closeAllProducers(),a(this,Q).closeAllConsumers(),a(this,Vt).clear(),a(this,Dn).clear(),v(this,Ei,null),a(this,Cs).stop(),a(this,Q).stopAllTransports(),a(this,Q).reset(),v(this,Cs,new zu)}joinRoom(t,e){return u(this,arguments,function*(i,n,r=!1,s=!1,o={}){a(this,Cr,Ms).mediaJoinAttempted=!0,v(this,ws,!0),r&&this.reset();try{return yield a(this,Cs).push(()=>B(this,Dh,Dv).call(this,i,n,s,o),"joinRoom")}catch(c){return l.error("Error in room joining process",{error:c}),P.emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,n,r=!1,s={}){return a(this,Ei)?a(this,Ei):(v(this,Ei,(()=>u(this,null,function*(){try{yield B(this,Hd,Lh).call(this,i,n,r,s)}catch(o){throw v(this,Ei,null),o}}))()),a(this,Ei))})}getConsumers(){return a(this,Q).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,Q).stopAllTransports(),v(this,Is,!1),a(this,Cr,Ms).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,It).sendMessagePromise(a(this,xt).leaveRoom,Lw.toBinary(e));(t=bI.fromBinary(i.payload))!=null&&t.closed||l.warn("weird state on peer closed and should not happen")}catch(i){l.error("error on sending leave room request",{error:i})}K.callEnded(),S.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,Q).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,n)=>{const r=a(this,Q).producerIdToConsumerIdMap.get(n.producerId);return r?(i.push(r),i):(l.warn(`consumer not found in close consumers: ${n.producerId}`),i)},[]);yield a(this,Q).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?be.WEBCAM:be.WEBCAM_BACKUP,n=B(this,mt,Ct).call(this,i);if(n){const h=yield n;if(a(this,Q).producers.has(h)){const p=a(this,Q).producers.get(h);if(!p.closed)return yield p.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const r=B(this,Hh,Wv).call(this,t,e),s=Br(this.context,"disableSimulcast"),o=a(this,nn)===Ne.CF?ne.ENABLE_CF_SIMULCAST:ne.ENABLE_HIVE_SIMULCAST;!s&&z.hasFeature(o)?(l.info(`Simulcast enabled for SFU: ${a(this,nn)}`),r.encodings=T1(t)):l.info(`Simulcast disabled for webcam producer, SFU: ${a(this,nn)}`),z.hasFeature(ne.TRACK_HINT)&&(r.track.contentHint=z.getValue(ne.TRACK_HINT));const c=()=>{l.info("Disabling video due to the producer closure"),a(this,Vt).delete(i)},d=a(this,Q).createProducer(r,c);return B(this,As,So).call(this,i,d.then(h=>h.id)),d.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(z.hasFeature(ne.FORCE_VIDEO_CODEC)){const e=z.getValue(ne.FORCE_VIDEO_CODEC).toString();if(e)return l.debug(`Calling _shareWebcam with forced video codec: ${e}`),this._shareWebcam(t,e)}return yield Promise.all(Vi.map(e=>{var i,n;return((n=(i=a(this,vo).sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(r=>r.mimeType===e))>=0&&a(this,Rs).get(e).size>0?(l.debug(`Calling _shareWebcam with video codec: ${e}`),this._shareWebcam(t,e)):t})),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const n={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},r=()=>{l.info("Disabling screenShare due to the producer closure"),a(this,Vt).delete(be.SCREENSHARE_VIDEO),a(this,Vt).delete(be.SCREENSHARE_AUDIO)},s=a(this,Q).createProducer(n,r);B(this,As,So).call(this,be.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,nn)!==Ne.CF},d=()=>{};o=a(this,Q).createProducer(c,d),B(this,As,So).call(this,be.SCREENSHARE_AUDIO,o.then(h=>h.id))}yield Promise.all([s,o||Promise.resolve()]),K.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new Lt("track undefined");const e=B(this,mt,Ct).call(this,be.MIC);if(e){const s=yield e;if(a(this,Q).producers.has(s)){const o=a(this,Q).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,zt)&&(a(this,zt).audioTrack=t,a(this,zt).producerId=s,a(this,zt).start());return}yield a(this,Q).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=B(this,jh,Bv).call(this,t),n=()=>{a(this,Vt).delete(be.MIC)},r=a(this,Q).createProducer(i,n);B(this,As,So).call(this,be.MIC,r.then(s=>s.id)),yield r.then(s=>{a(this,zt)&&(a(this,zt).audioTrack=s.track,a(this,zt).producerId=s.id,a(this,zt).start())})}catch(e){throw new w(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield B(this,mt,Ct).call(this,be.MIC),i=a(this,Q).producers.get(e);if(!i){l.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){l.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,zt))==null||t.stop();const n={producerId:i.id,pause:!0};a(this,It).sendMessage(a(this,xt).toggleProducer,Pc.toBinary(n))})}pauseWebcam(){return u(this,null,function*(){const t=yield B(this,mt,Ct).call(this,be.WEBCAM),e=yield B(this,mt,Ct).call(this,be.WEBCAM_BACKUP),i=a(this,Q).producers.get(t),n=a(this,Q).producers.get(e);if(!i&&!n){l.error("pauseWebcam::could_not_find_webcam_producer");return}const r=s=>{const o={producerId:s.id,pause:!0};a(this,It).sendMessage(a(this,xt).toggleProducer,Pc.toBinary(o))};i&&(i.pause(),r(i)),n&&(n.pause(),r(n))})}resumeMic(){return u(this,null,function*(){const t=yield B(this,mt,Ct).call(this,be.MIC),e=a(this,Q).producers.get(t);if(!e){l.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){l.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,It).sendMessage(a(this,xt).toggleProducer,Pc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=be.WEBCAM){const e=yield B(this,mt,Ct).call(this,t),i=a(this,Q).producers.get(e);if(!i){l.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){l.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,i);const n={producerId:i.id,pause:!1};a(this,It).sendMessage(a(this,xt).toggleProducer,Pc.toBinary(n))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?be.WEBCAM:be.WEBCAM_BACKUP,i=yield B(this,mt,Ct).call(this,e);B(this,Wh,Fv).call(this,e),i&&(yield a(this,Q).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield B(this,mt,Ct).call(this,be.MIC);e&&(yield a(this,Q).closeProducer(e)),(t=a(this,zt))==null||t.stop(),a(this,Vt).delete(be.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),K.screenShareStop();const t=yield B(this,mt,Ct).call(this,be.SCREENSHARE_VIDEO),e=yield B(this,mt,Ct).call(this,be.SCREENSHARE_AUDIO);t&&(yield a(this,Q).closeProducer(t)),e&&(yield a(this,Q).closeProducer(e)),a(this,Dn).clear(),a(this,Vt).delete(be.SCREENSHARE_VIDEO),a(this,Vt).delete(be.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 B(this,mt,Ct).call(this,be.WEBCAM),n=yield B(this,mt,Ct).call(this,be.WEBCAM_BACKUP);yield a(this,Q).closeProducer(i,{stopTrack:!1}),yield a(this,Q).closeProducer(n,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield B(this,mt,Ct).call(this,be.SCREENSHARE_VIDEO);yield a(this,Q).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,Q).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,Q).socketHandler.kickPeer(e)}kickAll(){a(this,Q).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,Q).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,Q).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,Q).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,Q).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,It).sendMessagePromise(a(this,xt).globalPinPeer,zw.toBinary(e))}catch(i){l.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,Q).producers.get(t.producerId)&&a(this,Dn).add(t.consumerPeerId),a(this,Dn).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(n=>this.getConsumers().get(n));a(this,Q).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,It).on(a(this,xt).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:n,producerState:r}=ZI.fromBinary(t);if(n===this.peerId)return;if(r!=null&&r.mimeType||(r.mimeType=r.kind===Ri.AUDIO?"audio/opus":"video/VP8"),r.kind===Ri.VIDEO&&!r.screenShare&&((i=(e=a(this,vo).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===Vi[0]))>=0&&a(this,Ps).get(Vi[0]).has(n)&&r.mimeType!==Vi[0]){l.warn(`Ignoring producer: ${r.producerId}`);return}l.info(`producer created broadcast: ${n}, producer state: ${r}`),P.emit(R.NEW_PRODUCER,{peerId:n,producer:H(x({},r),{kind:r.kind===Ri.AUDIO?"audio":"video",producingPeerId:n})})}catch(n){l.error("error in peer-producer-create-broadcast",{error:n})}}),a(this,It).on(a(this,xt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:n,pause:r,producerId:s}}=Wg.fromBinary(t),o=n===Ri.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${r} payload: ${JSON.stringify(Wg.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&r&&P.emit(o==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),e===this.peerId)return;P.emit(R.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:r,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==r&&(l.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${r}`),r?(c.pause(),P.emit(R.CONSUMER_PAUSED,{id:c.id})):(c.resume(),P.emit(R.CONSUMER_RESUMED,{id:c.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),a(this,It).on(a(this,xt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Yl.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),a(this,Dn).delete(e),a(this,Q).consumers.forEach(i=>{i.peerId===e&&i.close()}),P.emit(R.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),a(this,It).on(a(this,xt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=iC.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),P.emit(R.PRODUCER_CLOSED,{peerId:e,producerId:i});const n=a(this,Q).producerIdToConsumerIdMap.get(i);if(!n){l.warn(`no consumer found for producer:${i}`);return}l.info(`closing consumer ${n}, producer id: ${i}`),a(this,Q).closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),a(this,Q).producerIdToConsumerIdMap.delete(i),P.emit(R.CONSUMER_CLOSED,{id:n})}).catch(r=>{l.error("error closing consumer",{error:r})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),a(this,It).on(a(this,xt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,ws)&&!a(this,Is)||(l.warn("media hub termination broadcast received, rejoining room"),P.emit(R.ROOM_NODE_DISCONNECTED),a(this,jd).call(this))})})}handleCallstatsEvents(){K.onConsumerScore(t=>{t.forEach((e,i)=>{const n=a(this,Q).consumers.get(i);n&&P.emit(R.CONSUMER_SCORE_UPDATE,{id:i,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),K.onProducerScore(t=>{t.forEach((e,i)=>{const n=Array.from(a(this,Q).producers.values()).find(r=>r.id===i);n&&P.emit(R.PRODUCER_SCORE_UPDATE,{id:i,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,n,r,s;for(let o=0;o<=Vi.length;o+=1){const c=Vi[o];if(((n=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Vi.length-1){a(this,Rs).get(c).add(t);break}}for(let o=0;o<=Vi.length;o+=1){const c=Vi[o];if(((s=(r=e==null?void 0:e.sender)==null?void 0:r.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Vi.length-1){a(this,Ps).get(c).add(t);break}}}handlePeerLeaving(t){z.hasFeature(ne.FORCE_VIDEO_CODEC)||(a(this,Ps).forEach(e=>e.delete(t)),a(this,Rs).forEach((e,i)=>{e.delete(t),e.size===0&&this.disableWebcam(i)}))}},Bd=new WeakMap,Wd=new WeakMap,It=new WeakMap,Q=new WeakMap,vo=new WeakMap,nn=new WeakMap,xt=new WeakMap,ws=new WeakMap,Is=new WeakMap,Cs=new WeakMap,jd=new WeakMap,Ei=new WeakMap,Dn=new WeakMap,yo=new WeakMap,Ps=new WeakMap,Rs=new WeakMap,Vt=new WeakMap,zt=new WeakMap,Cr=new WeakSet,Ms=function(){return this.context.getValue("connectionHandler")},Dh=new WeakSet,Dv=function(t,e,i,n){return u(this,null,function*(){v(this,Wd,t);try{return a(this,Ei)?yield a(this,Ei):yield B(this,Hd,Lh).call(this,t,e,i,n),B(this,Nh,Nv).call(this,e),{roomJoined:yield B(this,Oh,Ov).call(this)}}catch(r){return l.error("Failed to complete room join",{error:r}),{roomJoined:!1}}finally{v(this,Ei,null)}})},Oh=new WeakSet,Ov=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,Q).socketHandler.notifySelfJoinComplete();return v(this,Bd,t.roomUuid),v(this,Is,!0),v(this,ws,!1),!0}catch(t){return l.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},Nh=new WeakSet,Nv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:H(x({},Ie.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};K.roomJoined(e)}catch(e){l.error("Error reporting room joined analytics",{error:e})}},0)},Hd=new WeakSet,Lh=function(t,e,i,n){return u(this,null,function*(){var r,s;try{(s=a(this,yo))!=null||v(this,yo,B(r=jv,xh,Lv).call(r));const o=B(this,Uh,xv).call(this);yield B(this,Fh,Vv).call(this,t,e,i,o),yield a(this,Q).setupTransports({send:!0,recv:!0}),yield B(this,Bh,Uv).call(this,n)}catch(o){throw l.error("Failed to initialize connection",{error:o}),o}})},xh=new WeakSet,Lv=function(){const{ipInfo:t}=ut();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},Uh=new WeakSet,xv=function(){var t;const e=(t=z.getValue(ne.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=kD(e);return v(this,vo,i),i},Fh=new WeakSet,Vv=function(t,e,i,n){return u(this,null,function*(){yield cv((r,s)=>u(this,null,function*(){if(!a(this,It).isConnected){s(new Error("Socket is not connected"));return}r>0&&l.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${r}`});try{yield a(this,Q).socketHandler.joinRoom(e,t,n,i,a(this,yo))}catch(o){throw l.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:z.hasFeature(ne.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},Bh=new WeakSet,Uv=function(t){return u(this,null,function*(){if(!(a(this,nn)===Ne.HIVE||!z.hasFeature(ne.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===q.Allowed&&e.push(this.shareWebcam(FD())),t.canProduceAudio===q.Allowed){const i=UD();i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){l.warn("Failed to precreate producers",{error:e})}})},mt=new WeakSet,Ct=function(t){return a(this,Vt).get(t)},As=new WeakSet,So=function(t,e){return a(this,Vt).set(t,e)},Wh=new WeakSet,Fv=function(t){return a(this,Vt).delete(t)},jh=new WeakSet,Bv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,nn)!==Ne.CF}},Hh=new WeakSet,Wv=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},f(Vh,xh),Vh);let ue=jv;me([S.trace("MediaNodeClient.reset",{country:S.location.country})],ue.prototype,"reset",1),me([S.trace("MediaNodeClient.joinRoom")],ue.prototype,"joinRoom",1),me([S.trace("MediaNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1),me([S.trace("MediaNodeClient.activatePeers")],ue.prototype,"activatePeers",1),me([S.trace("MediaNodeClient.createConsumers")],ue.prototype,"createConsumers",1),me([S.trace("MediaNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1),me([S.trace("MediaNodeClient._shareWebcam")],ue.prototype,"_shareWebcam",1),me([S.trace("MediaNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1),me([S.trace("MediaNodeClient.shareScreen")],ue.prototype,"shareScreen",1),me([S.trace("MediaNodeClient.shareMic")],ue.prototype,"shareMic",1),me([S.trace("MediaNodeClient.pauseMic")],ue.prototype,"pauseMic",1),me([S.trace("MediaNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1),me([S.trace("MediaNodeClient.resumeMic")],ue.prototype,"resumeMic",1),me([S.trace("MediaNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1),me([S.trace("MediaNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1),me([S.trace("HiveClient.disableMic")],ue.prototype,"disableMic",1),me([S.trace("HiveClient.disableScreenShare")],ue.prototype,"disableScreenShare",1),me([S.trace("MediaNodeClient.muteSelf")],ue.prototype,"muteSelf",1),me([S.trace("MediaNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1),me([S.trace("MediaNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1),me([S.trace("MediaNodeClient.kickPeer")],ue.prototype,"kick",1),me([S.trace("MediaNodeClient.kickAllPeers")],ue.prototype,"kickAll",1),me([S.trace("MediaNodeClient.muteAll")],ue.prototype,"muteAll",1),me([S.trace("MediaNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1),me([S.trace("MediaNodeClient.disableAudio")],ue.prototype,"disableAudio",1),me([S.trace("MediaNodeClient.disableVideo")],ue.prototype,"disableVideo",1),me([S.trace("MediaNodeClient.pinPeer")],ue.prototype,"pinPeer",1),me([S.trace("MediaNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);function Hv(t,e,i){const n=t.getValue("roomNodeClient");if(n){if(n)return n;throw new Error("Room node client already set up.")}const r=new ue(t,e,i);return t.setValue("roomNodeClient",r),r}function qv(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var jD=Object.defineProperty,HD=Object.getOwnPropertyDescriptor,Pr=(t,e,i,n)=>{for(var r=n>1?void 0:n?HD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&jD(e,i,r),r},Rr,Ui,Pt,Ut,Yt,Gv;const $v=(Gv=class{constructor(t,e,i,n){f(this,Ut),m(this,"self"),m(this,"authToken"),f(this,Rr,void 0),m(this,"viewType"),f(this,Ui,void 0),f(this,Pt,void 0);const{socket:r}=i,s=t.getValue("authToken");this.self=e,v(this,Pt,t),this.viewType=n,this.authToken=s,v(this,Rr,r),v(this,Ui,i),e.config.viewType!==Rt.Chat&&this.setupEvents()}get peerId(){return a(this,Pt).getValue("peerId")}get mediaJoined(){return a(this,Pt).getValue("connectionHandler").mediaJoined}static init(t,e,i,n,r){return u(this,null,function*(){const s=ut(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield et.__init__(t,i,n,r,r.name,c);if(navigator.product!=="ReactNative"){const h=!z.hasFeature(ne.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),K.devices("AUDIO",p==null?void 0:p.filter(g=>g.kind==="audioinput")),K.devices("VIDEO",p==null?void 0:p.filter(g=>g.kind==="videoinput")),K.devices("SPEAKER",p==null?void 0:p.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield K.initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:z.getAllFlags(),logger:l,apiHostnames:bg(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new $v(t,d,e,r.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:n,audioEnabled:r,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(n.canProduceAudio===q.Allowed&&r)try{yield a(this,Ut,Yt).shareMic(e),this.self.audioEnabled||a(this,Ut,Yt).pauseMic()}catch(d){this.self.disableAudio()}if(n.canProduceVideo===q.Allowed&&s)try{const d=yield a(this,Ut,Yt).shareWebcam(i);d&&d.id!==i.id&&z.hasFeature(ne.EXP_RESHARE)&&(yield a(this,Ut,Yt).shareWebcam(d)),this.self.videoEnabled||a(this,Ut,Yt).pauseWebcam()}catch(d){this.self.disableVideo()}if(n.canProduceScreenshare===q.Allowed&&o)try{yield(t=a(this,Ut,Yt))==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(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){K.callEnded(),a(this,Ut,Yt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){P.on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),P.on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),P.on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),P.on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),P.on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),P.on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&z.hasFeature(ne.REFRESH_ID_ON_DISCONNECTION)&&(e=Nr()),a(this,Rr).updateURL(e),S.resetPeerId(e),ut().setHeader("dyte-tracing-id",e),Yn.remapContext(e,a(this,Pt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),P.on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ui).on(W.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ui).on(Nc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&P.emit(R.UPDATE_PERMISSIONS,e.patch)})}),a(this,Ui).on(W.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ui).on(W.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ui).on(W.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),P.onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),P.on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:n})=>{var r;const s=(r=i==null?void 0:i.screenShare)!=null?r:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:n})}),P.on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),K.audioOff())})),P.on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),K.videoOff())})),P.onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),P.on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Ui).joinRoom(this.self);a(this,Ui).socket.flush();const i=wu(e.stageType);if(a(this,Pt).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,Pt).notify("stageStatus")}catch(e){throw l.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,Rr))==null||e.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,Pt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,Pt).notify("stageStatus");try{(i=a(this,Rr))==null||i.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}qv(a(this,Pt)),hd.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:n,viewType:r,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,Pt).getAllValues(),{sfu:d}=c;try{if(r===Rt.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}Hv(a(this,Pt),d,{socket:a(this,Rr),peerId:n})}const{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}=this.self.permissions,{roomJoined:y}=(i=yield(e=a(this,Ut,Yt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}))!=null?i:{};if(!y)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(h){throw l.error("Error:SelfController.mediaRoomJoin",{error:h}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,Pt).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Rt.Webinar)&&a(this,Ut,Yt)&&(a(this,Ut,Yt).mediaJoined&&t!=="disconnected"&&(yield a(this,Ut,Yt).leaveRoom()),!(t==="stageLeft"&&e===Rt.Livestream)&&(a(this,Ut,Yt).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()})}},Rr=new WeakMap,Ui=new WeakMap,Pt=new WeakMap,Ut=new WeakSet,Yt=function(){return a(this,Pt).getValue("roomNodeClient")},Gv);let On=$v;Pr([S.trace("SelfController.resetSelf")],On.prototype,"resetSelf",1),Pr([S.trace("SelfController.setupEvents")],On.prototype,"setupEvents",1),Pr([S.trace("SelfController.joinRoom")],On.prototype,"joinRoom",1),Pr([S.trace("SelfController.leaveRoom")],On.prototype,"leaveRoom",1),Pr([S.trace("SelfController.joinMediaRoom")],On.prototype,"joinMediaRoom",1),Pr([S.trace("SelfController.leaveMediaRoom")],On.prototype,"leaveMediaRoom",1),Pr([S.trace("SelfController.init")],On,"init",1);var qd;class qD{constructor(e){f(this,qd,void 0),v(this,qd,e)}on(e,i){let n;e===W.roomPeerCount?n=qg.fromBinary.bind(qg):n=cf.fromBinary.bind(cf),a(this,qd).on(e,({payload:r})=>{const s=n(r);return i(s)})}}qd=new WeakMap;var Gd;class GD{constructor(e){f(this,Gd,void 0),v(this,Gd,e)}on(e,i){let n,r;switch(e){case W.transcript:{n=Ql.fromBinary.bind(Ql),r=Ql.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Gd).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Gd=new WeakMap;var $D=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,qh=(t,e,i,n)=>{for(var r=n>1?void 0:n?JD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&$D(e,i,r),r},Nn;class $d{constructor(e){f(this,Nn,void 0),v(this,Nn,e)}getPolls(){return a(this,Nn).sendMessagePromise($i.getPolls)}createPoll(e,i,n=!1,r=!1){const s={anonymous:n,hideVotes:r,question:e,options:i};return a(this,Nn).sendMessage($i.createPoll,qM.toBinary(s))}votePoll(e,i){const n={index:i,pollId:e};return a(this,Nn).sendMessage($i.votePoll,$M.toBinary(n))}on(e,i){let n,r;switch(e){case $i.updatePoll:case $i.createPoll:case $i.votePoll:{n=lu.fromBinary.bind(lu),r=lu.create();break}}a(this,Nn).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Nn).removeListeners(e)}}Nn=new WeakMap,qh([S.trace("PollSocketHandler.getPolls")],$d.prototype,"getPolls",1),qh([S.trace("PollSocketHandler.createPoll")],$d.prototype,"createPoll",1),qh([S.trace("PollSocketHandler.votePoll")],$d.prototype,"votePoll",1);var Qt;class KD{constructor(e){f(this,Qt,void 0),v(this,Qt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Qt).sendMessagePromise(W.getStageRequests);return e?du.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Qt).sendMessage(W.requestStageAccess)}cancelRequestAccess(){a(this,Qt).sendMessage(W.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Qt).sendMessage(W.grantStageAccess,NM.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Qt).sendMessage(W.denyStageAccess,xM.toBinary(i))})}joinStage(){return a(this,Qt).sendMessagePromise(W.joinStage,void 0,void 0,W.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Qt).sendMessagePromise(W.leaveStage,lf.toBinary(i),void 0,W.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Qt).sendMessagePromise(W.leaveStage,lf.toBinary(i))}on(e,i){let n;switch(e){case W.grantStageAccess:case W.denyStageAccess:{n=void 0;break}case W.getStagePeers:{n=df.fromBinary.bind(df);break}case W.getStageRequests:case W.requestStageAccess:case W.cancelStageRequest:{n=du.fromBinary.bind(du);break}case W.peerStageStatusUpdate:{n=Hg.fromBinary.bind(Hg);break}}a(this,Qt).on(e,({payload:r,id:s})=>{if(!r||!n)return i(void 0,s);const o=n(r);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Qt).sendMessagePromise(W.getPeerInfo,Jg.toBinary({peerId:e}));return Hr.fromBinary(i.payload)})}}Qt=new WeakMap;var tt;class zD{constructor(e){f(this,tt,void 0),v(this,tt,e)}addPlugin(e,i){a(this,tt).sendMessage(Y.addPlugin,QR.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,tt).sendMessage(Y.removePlugin,ZR.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,tt).sendMessagePromise(Y.getPlugins);return e?kM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,n){const r={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,tt).sendMessage(Y.customPluginEventToRoom,dM.toBinary(r),n)}customPluginEventToPeers(e,i,n,r){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(n))};a(this,tt).sendMessage(Y.customPluginEventToPeers,uM.toBinary(s),r)}enablePluginForRoom(e,i){a(this,tt).sendMessage(Y.enablePluginForRoom,tM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,n){a(this,tt).sendMessage(Y.enablePluginForPeers,sM.toBinary({pluginId:e,peerIds:i}),n)}disablePluginForRoom(e,i){a(this,tt).sendMessage(Y.disablePluginForRoom,nM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,n){a(this,tt).sendMessage(Y.disablePluginForPeers,oM.toBinary({pluginId:e,peerIds:i}),n)}storeInsertKeys(e,i,n,r){const s={pluginId:e,storeName:i,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,tt).sendMessage(Y.storeInsertKeys,rf.toBinary(s),r)}storeGetKeys(e,i,n,r){const s={pluginId:e,storeName:i,getKeys:n.map(o=>({storeKey:o.key}))};a(this,tt).sendMessage(Y.storeGetKeys,gM.toBinary(s),r)}storeDeleteKeys(e,i,n,r){const s={pluginId:e,storeName:i,deleteKeys:n.map(o=>({storeKey:o.key}))};a(this,tt).sendMessage(Y.storeDeleteKeys,vM.toBinary(s),r)}storeDelete(e,i,n){a(this,tt).sendMessage(Y.storeDelete,SM.toBinary({pluginId:e,storeName:i}),n)}getPluginDataOld(e,i){l.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,n){const r={pluginId:e,storeName:i,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};a(this,tt).sendMessage(Y.storeInsertKeys,rf.toBinary(r))}on(e,i){let n;switch(e){case Y.addPlugin:case Y.enablePluginForPeers:case Y.enablePluginForRoom:{n=cu.fromBinary.bind(cu);break}case Y.removePlugin:case Y.disablePluginForPeers:case Y.disablePluginForRoom:{n=sf.fromBinary.bind(sf);break}case Y.customPluginEventToPeers:case Y.customPluginEventToRoom:{n=of.fromBinary.bind(of);break}case Y.storeInsertKeys:case Y.storeGetKeys:case Y.storeDeleteKeys:case Y.storeDelete:{n=af.fromBinary.bind(af);break}}a(this,tt).on(e,({payload:r,id:s})=>{const o=n(r);return i(o,s)})}}tt=new WeakMap;var YD=Object.defineProperty,QD=(t,e,i)=>e in t?YD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,XD=(t,e,i)=>(QD(t,typeof e!="symbol"?e+"":e,i),i),Gh=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},L=(t,e,i)=>(Gh(t,e,"read from private field"),i?i.call(t):e.get(t)),Pe=(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)},he=(t,e,i,n)=>(Gh(t,e,"write to private field"),n?n.call(t,i):e.set(t,i),i),Ae=(t,e,i)=>(Gh(t,e,"access private method"),i),Jd={},ZD={get exports(){return Jd},set exports(t){Jd=t}},Ds=typeof Reflect=="object"?Reflect:null,Jv=Ds&&typeof Ds.apply=="function"?Ds.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},Kd;Ds&&typeof Ds.ownKeys=="function"?Kd=Ds.ownKeys:Object.getOwnPropertySymbols?Kd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Kd=function(t){return Object.getOwnPropertyNames(t)};function eO(t){console&&console.warn&&console.warn(t)}var Kv=Number.isNaN||function(t){return t!==t};function ge(){ge.init.call(this)}ZD.exports=ge,Jd.once=rO,ge.EventEmitter=ge,ge.prototype._events=void 0,ge.prototype._eventsCount=0,ge.prototype._maxListeners=void 0;var zv=10;function zd(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ge,"defaultMaxListeners",{enumerable:!0,get:function(){return zv},set:function(t){if(typeof t!="number"||t<0||Kv(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");zv=t}}),ge.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},ge.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Kv(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 Yv(t){return t._maxListeners===void 0?ge.defaultMaxListeners:t._maxListeners}ge.prototype.getMaxListeners=function(){return Yv(this)},ge.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var n=t==="error",r=this._events;if(r!==void 0)n=n&&r.error===void 0;else if(!n)return!1;if(n){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=r[t];if(c===void 0)return!1;if(typeof c=="function")Jv(c,this,e);else for(var d=c.length,h=ty(c,d),i=0;i<d;++i)Jv(h[i],this,e);return!0};function Qv(t,e,i,n){var r,s,o;if(zd(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]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),r=Yv(t),r>0&&o.length>r&&!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,eO(c)}return t}ge.prototype.addListener=function(t,e){return Qv(this,t,e,!1)},ge.prototype.on=ge.prototype.addListener,ge.prototype.prependListener=function(t,e){return Qv(this,t,e,!0)};function tO(){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 Xv(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},r=tO.bind(n);return r.listener=i,n.wrapFn=r,r}ge.prototype.once=function(t,e){return zd(e),this.on(t,Xv(this,t,e)),this},ge.prototype.prependOnceListener=function(t,e){return zd(e),this.prependListener(t,Xv(this,t,e)),this},ge.prototype.removeListener=function(t,e){var i,n,r,s,o;if(zd(e),n=this._events,n===void 0)return this;if(i=n[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,r=s;break}if(r<0)return this;r===0?i.shift():iO(i,r),i.length===1&&(n[t]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},ge.prototype.off=ge.prototype.removeListener,ge.prototype.removeAllListeners=function(t){var e,i,n;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 r=Object.keys(i),s;for(n=0;n<r.length;++n)s=r[n],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(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Zv(t,e,i){var n=t._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?i?[r.listener||r]:[r]:i?nO(r):ty(r,r.length)}ge.prototype.listeners=function(t){return Zv(this,t,!0)},ge.prototype.rawListeners=function(t){return Zv(this,t,!1)},ge.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):ey.call(t,e)},ge.prototype.listenerCount=ey;function ey(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}ge.prototype.eventNames=function(){return this._eventsCount>0?Kd(this._events):[]};function ty(t,e){for(var i=new Array(e),n=0;n<e;++n)i[n]=t[n];return i}function iO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function nO(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function rO(t,e){return new Promise(function(i,n){function r(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",r),i([].slice.call(arguments))}iy(t,e,s,{once:!0}),e!=="error"&&sO(t,r,{once:!0})})}function sO(t,e,i){typeof t.on=="function"&&iy(t,"error",e,i)}function iy(t,e,i,n){if(typeof t.on=="function")n.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function r(s){n.once&&t.removeEventListener(e,r),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class aO extends T{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 ny=new aO;class ry{static encode(e){return ny.toBinary(e)}static decode(e){return ny.fromBinary(new Uint8Array(e))}}function oO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Ln;class cO{constructor(e={}){XD(this,"opts"),Pe(this,Ln,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},he(this,Ln,0)}wait(){return u(this,null,function*(){he(this,Ln,L(this,Ln)+1);const e=oO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*yS(2,L(this,Ln))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return L(this,Ln)}reset(){he(this,Ln,0)}}Ln=new WeakMap;const xn={debug:0,info:1,warn:2,error:3};var Mr,Ar;class dO{constructor(e){Pe(this,Mr,void 0),Pe(this,Ar,void 0),he(this,Mr,console),he(this,Ar,e)}debug(...e){xn[L(this,Ar)]>xn.debug||L(this,Mr).debug("[Sockrates]:",...e)}info(...e){xn[L(this,Ar)]>xn.info||L(this,Mr).info("[Sockrates]:",...e)}warn(...e){xn[L(this,Ar)]>xn.warn||L(this,Mr).warn("[Sockrates]:",...e)}error(...e){xn[L(this,Ar)]>xn.error||L(this,Mr).error("[Sockrates]:",...e)}}Mr=new WeakMap,Ar=new WeakMap;var sy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(sy||{});const lO="2",uO="3";var Ve,Os,De,He,Vn,it,rn,Un,ki,Ns,sn,$h,ay,To,Yd,Jh,oy,Kh,cy,Qd,zh,Yh,dy,Eo,Xd,ko,Zd,el,Qh,Ls,bo,_o,tl;class hO{constructor(e,i){var n;Pe(this,$h),Pe(this,To),Pe(this,Jh),Pe(this,Kh),Pe(this,Qd),Pe(this,Yh),Pe(this,Eo),Pe(this,ko),Pe(this,el),Pe(this,Ls),Pe(this,_o),Pe(this,Ve,void 0),Pe(this,Os,void 0),Pe(this,De,void 0),Pe(this,He,void 0),Pe(this,Vn,void 0),Pe(this,it,void 0),Pe(this,rn,void 0),Pe(this,Un,void 0),Pe(this,ki,void 0),Pe(this,Ns,void 0),Pe(this,sn,void 0);var r,s,o,c,d,h,p,g,y;he(this,Os,e),he(this,Vn,[]),he(this,it,new Jd),he(this,rn,!0),he(this,ki,!1),he(this,De,i!=null?i:{}),(r=L(this,De)).autoReconnect!=null||(r.autoReconnect=!0),(s=L(this,De)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=L(this,De)).pingTimeout!=null||(o.pingTimeout=3e4),(c=L(this,De)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=L(this,De)).debug!=null||(d.debug=!0),(h=L(this,De)).maxReconnectionAttempts!=null||(h.maxReconnectionAttempts=10),(p=L(this,De)).disconnectOnPingTimeout!=null||(p.disconnectOnPingTimeout=!0),(g=L(this,De)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(y=L(this,De)).flushOnReconnect!=null||(y.flushOnReconnect=!1),he(this,Un,{code:void 0,reason:void 0}),he(this,He,(n=L(this,De).logger)!=null?n:new dO(L(this,De).debug?"debug":"info")),he(this,sn,new cO)}get readyState(){var e;return(e=L(this,Ve))==null?void 0:e.readyState}get url(){return L(this,Os)}updateURL(e){he(this,Os,e),Ae(this,Yh,dy).call(this)}get config(){return L(this,De)}get sendQueue(){return L(this,Vn)}flush(){if(!L(this,De).queueOnDisconnect)return!1;const e=[];return L(this,Vn).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),he(this,Vn,e),L(this,Vn)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,He).debug("Websocket was already connecting or connected.");return}if(L(this,rn)!==!1)return new Promise((i,n)=>{Ae(this,Ls,bo).call(this),Ae(this,_o,tl).call(this);try{he(this,Ve,new WebSocket(Ae(this,$h,ay).call(this,L(this,Os)))),L(this,Ve).binaryType="arraybuffer",L(this,He).debug("Connecting");const r=setTimeout(()=>{L(this,He).debug("Connection timeout. Closing socket"),he(this,rn,!0),Ae(this,_o,tl).call(this),L(this,Ve).close(3001,"Connection Timeout"),L(this,De).autoReconnect&&!L(this,ki)&&(L(this,it).emit("reconnecting"),Ae(this,Eo,Xd).call(this)),n(new Error("Connection timed out!"))},L(this,De).connectionTimeout);L(this,Ve).onopen=()=>{L(this,He).debug(`Ready State: ${sy[L(this,Ve).readyState]}`),r&&clearTimeout(r),Ae(this,el,Qh).call(this),he(this,Un,{code:void 0,reason:void 0}),L(this,it).emit("connected"),L(this,De).flushOnReconnect&&this.flush(),i()},L(this,Ve).onclose=s=>{try{r&&clearTimeout(r);const{code:o,reason:c}=s;n(c),L(this,He).debug("Socket closed. Close event:",{event:s}),L(this,He).debug(`Connection closed code: ${o}`),L(this,He).debug(`Connection closed reason: ${c}`),L(this,ki)||Ae(this,Qd,zh).call(this,o,c)}catch(o){Ae(this,To,Yd).call(this,o)}},L(this,Ve).onerror=s=>{Ae(this,To,Yd).call(this,s)},L(this,Ve).onmessage=s=>Ae(this,Jh,oy).call(this,s)}catch(r){Ae(this,To,Yd).call(this,r,n)}})})}send(e,i,n,r){const s={event:e,id:i,payload:n,metadata:r};if(L(this,De).queueOnDisconnect&&(!L(this,Ve)||L(this,Ve).readyState!==1))return L(this,He).debug("Queuing message since socket is not connected!",s),L(this,Vn).push(s),!1;const o=ry.encode(s);return Ae(this,ko,Zd).call(this,o)}emit(e,i,n,r){return this.send(e,i,n,r)}sendRaw(e){return Ae(this,ko,Zd).call(this,e)}receive(e,i){return L(this,it).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")){L(this,it).on(e,i);return}this.receive(e,i)}removeAllListeners(){L(this,it).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){L(this,it).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,it).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){he(this,rn,!1),Ae(this,Ls,bo).call(this),this.removeAllListeners(),he(this,Un,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,Ve).close(1e3,"Sockrates disconnect method called.")}}Ve=new WeakMap,Os=new WeakMap,De=new WeakMap,He=new WeakMap,Vn=new WeakMap,it=new WeakMap,rn=new WeakMap,Un=new WeakMap,ki=new WeakMap,Ns=new WeakMap,sn=new WeakMap,$h=new WeakSet,ay=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)://.")},To=new WeakSet,Yd=function(t,e){L(this,He).error("Error:",{error:t}),L(this,it).emit("errored",{error:t}),e==null||e(t)},Jh=new WeakSet,oy=function(t){if(Ae(this,el,Qh).call(this),t.data===lO){L(this,He).debug("Received ping from server"),Ae(this,ko,Zd).call(this,uO);return}const e=ry.decode(t.data),{id:i,payload:n}=e;L(this,He).debug("Received message",{event:e.event,messageID:i}),L(this,it).emit(e.event.toString(),{id:i,payload:n})},Kh=new WeakSet,cy=function(){return L(this,Ve).readyState===1},Qd=new WeakSet,zh=function(t,e){he(this,Un,{reason:e,code:t}),L(this,it).emit("disconnected",{code:t,reason:e})},Yh=new WeakSet,dy=function(){const{reason:t,code:e}=L(this,Un);e&&e!==1e3&&L(this,rn)&&L(this,De).autoReconnect&&!L(this,ki)&&(L(this,He).debug(`Triggering reconnection due to ${t}.`),L(this,it).emit("reconnecting"),Ae(this,Eo,Xd).call(this))},Eo=new WeakSet,Xd=function(t=!0){return u(this,null,function*(){if(t&&L(this,ki)){L(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,ki)||L(this,sn).reset(),L(this,De).maxReconnectionAttempts!==null&&L(this,sn).getAttempts()>=L(this,De).maxReconnectionAttempts){L(this,it).emit("failed"),he(this,ki,!1);return}he(this,ki,!0),Ae(this,_o,tl).call(this),Ae(this,Ls,bo).call(this);try{if(yield L(this,sn).wait(),L(this,rn)===!1)return;if(L(this,He).debug(`Reconnection attempt ${L(this,sn).getAttempts()}`),L(this,it).emit("reconnectAttempt",{attempt:L(this,sn).getAttempts()}),yield this.connect(),!Ae(this,Kh,cy).call(this))throw Error("Reconnect Failed");he(this,ki,!1),he(this,Un,{code:void 0,reason:void 0}),L(this,it).emit("reconnected")}catch(e){L(this,He).debug("Failed to reconnect."),L(this,it).emit("reconnectFailure",{attempt:L(this,sn).getAttempts()}),Ae(this,Eo,Xd).call(this,!1)}})},ko=new WeakSet,Zd=function(t){try{return L(this,Ve).send(t),!0}catch(e){return L(this,He).error(e.message),!1}},el=new WeakSet,Qh=function(){this.config.disconnectOnPingTimeout&&(L(this,He).debug("Resetting ping timeout"),Ae(this,Ls,bo).call(this),he(this,Ns,setTimeout(()=>{var t;L(this,He).debug("Disconnecting the socket due to ping timeout"),he(this,rn,!0);const e=3002,i="Ping timeout";(t=L(this,Ve))==null||t.close(e,i),Ae(this,Qd,zh).call(this,e,i)},L(this,De).pingTimeout)))},Ls=new WeakSet,bo=function(){L(this,Ns)&&(clearTimeout(L(this,Ns)),he(this,Ns,void 0))},_o=new WeakSet,tl=function(){L(this,Ve)&&(L(this,Ve).onopen=void 0,L(this,Ve).onerror=void 0,L(this,Ve).onmessage=void 0,L(this,Ve).onclose=void 0)};var pO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,il=(t,e,i,n)=>{for(var r=n>1?void 0:n?mO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&pO(e,i,r),r};const ly=65535,gO=3e3;var Dr,Ue,Fe,qe,bi,Fn,nl,Xh,rl,Zh,uy;const hy=(uy=class{constructor(t,{peerId:e,meetingId:i,authToken:n,capabilities:r}){f(this,Fe),f(this,nl),f(this,rl),f(this,Dr,void 0),f(this,Ue,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),f(this,bi,void 0),f(this,Fn,void 0);var s;if(!e||!i||!n)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,bi,void 0),v(this,Fn,t),this.capabilities=r,this.roomName=i,this.authToken=n,v(this,Dr,B(this,nl,Xh).call(this,e)),v(this,Ue,new hO(a(this,Dr),{autoReconnect:!0,disconnectOnPingTimeout:(s=r.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Fe,qe).socketJoinAttempted}set joinAttempted(t){a(this,Fe,qe).socketJoinAttempted=t}get peerId(){return a(this,Fn).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,Dr,B(this,nl,Xh).call(this,t)),l.debug("SocketService:: Connection URL updated.")),a(this,Ue).updateURL(a(this,Dr))}static getSocketEdgeDomain(t){return Wr({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,Dr)}connect(){return u(this,null,function*(){a(this,Fe,qe).socketJoinAttempted=!0,yield a(this,Ue).connect(),a(this,Fe,qe).socketJoinAttempted=!0,a(this,Fe,qe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Fe,qe).socketJoinAttempted=!1,a(this,Ue).disconnect(),a(this,Fe,qe).socketJoinAttempted=!0,a(this,Fe,qe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Ue).readyState===1}catch(t){return!1}}sendMessage(t,e,i){const n={};return S.injectContext(n),a(this,Ue).send(t,i!=null?i:B(this,rl,Zh).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,i,n){const r=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:r,protobuf:e,messageId:i,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:n,resp:r}){const s=r!=null?r:t;return new Promise((o,c)=>{const d=(E,b)=>{a(this,Ue).removeListener(s,E),a(this,Ue).removeListener(ly,b),a(this,Ue).removeListener(Zt.errorResponse,b),a(this,Ue).removeListener(li.errorResponse,b)},h=n!=null?n:B(this,rl,Zh).call(this),p={};S.injectContext(p);const g=({id:E,payload:b})=>{if(h===E){let N;try{const M=pI.fromBinary(b);N=new Error(M.errorMessage)}catch(M){N=new Error("failed to parse error message",{cause:M});try{const U=mC.fromBinary(b);N=new Error(U.message)}catch(U){N=new Error("failed to parse error message",{cause:U})}}c(N),d(y,g)}},y=({id:E,payload:b})=>{h===E&&(o({id:E,payload:b}),d(y,g))};a(this,Ue).on(s,y),a(this,Ue).on(ly,g),a(this,Ue).on(Zt.errorResponse,g),a(this,Ue).on(li.errorResponse,g),setTimeout(()=>{d(y,g),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Ue).send(t,h,i,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){a(this,Ue).on(t,e)}onStateEvent(t,e){a(this,Ue).on(t,e)}removeListener(t,e){a(this,Ue).removeListener(t,e)}removeListeners(t){a(this,Ue).removeListeners(t)}flush(){return a(this,Ue).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),a(this,bi)&&(clearTimeout(a(this,bi)),v(this,bi,void 0)),a(this,Fe,qe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:n,send:r}=(i=a(this,Fe,qe).mediaState)!=null?i:{};n!=null&&n.state&&(n==null?void 0:n.state)!==gs.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==gs.CONNECTED?P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Fe,qe).joinAttempted}):v(this,bi,setTimeout(()=>{P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Fe,qe).joinAttempted}),v(this,bi,void 0)},gO)),a(this,Fe,qe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),a(this,Fe,qe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Fe,qe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Fe,qe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Fe,qe).mediaJoinAttempted}}),a(this,bi)&&(clearTimeout(a(this,bi)),v(this,bi,void 0)),P.emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Fe,qe).mediaJoinAttempted}),a(this,Fe,qe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),P.emit(R.SOCKET_SERVICE_FAILED),a(this,Fe,qe).updateSocketConnectionState("failed")}))}},Dr=new WeakMap,Ue=new WeakMap,Fe=new WeakSet,qe=function(){return a(this,Fn).getValue("connectionHandler")},bi=new WeakMap,Fn=new WeakMap,nl=new WeakSet,Xh=function(t){let e=hy.getSocketEdgeDomain(a(this,Fn).getValue("baseURI"));typeof Br(a(this,Fn),"socket_server_base")=="string"&&(e=Br(a(this,Fn),"socket_server_base"));const i=`wss://${e}`,n=new URL(`${i}/ws`),r=this.peerId,s=H(x({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},r!==t&&{oldPeerID:r}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Rc[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{n.searchParams.append(o,c.toString())}),n.href},rl=new WeakSet,Zh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},uy);let wo=hy;il([S.trace("SocketService.connect")],wo.prototype,"connect",1),il([S.trace("SocketService.disconnect")],wo.prototype,"disconnect",1),il([S.trace("SocketService.sendMessagePromise")],wo.prototype,"sendMessagePromise",1),il([S.trace("SocketService.sendMessagePromiseWithTimeout")],wo.prototype,"sendMessagePromiseWithTimeout",1);const Or=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const i=WC.fromBinary(t),n=i.meetings.map(r=>{var s;return{id:r.id,title:r.title,participants:(s=r.participants)!=null?s:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(e=i.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=pP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=Yg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return zg.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return nP.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Or.socketService.sendMessagePromise(W.getConnectedRoomsDump);return Or.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Or.socketService.sendMessagePromise(W.createConnectedRooms,GC.toBinary({payloads:t}));return zg.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),i=yield Or.socketService.sendMessagePromise(W.deleteConnectedRooms,tP.toBinary({payloads:e}));return Or.handleConnectedRoomsDeletedRaw(i)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Or.socketService.sendMessagePromise(W.movePeers,dP.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Le=Or;m(Le,"socketService"),m(Le,"currentMeetingId");var fO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,sl=(t,e,i,n)=>{for(var r=n>1?void 0:n?vO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&fO(e,i,r),r};const xs=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),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}static init(t){return u(this,null,function*(){var e,i;const{peerId:n,apiBase:r,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(P.reset(),hd.cleanup(),qv(t),Ie.isSupported()===!1)throw new w("Browser not supported","0010",!0);const h=wA(t,{authToken:s,baseURL:r,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",n),t.setValue("apiClient",h);const p=new o1;t.setValue("connectionHandler",p);const g=xs.createSocketService(t),y=g.connect(),E=h.getUserDetails(),b=h.getPlugins();let N=Ne.HIVE,M,U="";try{yield xs.setupFlagsmith(t)}catch(se){l.error("Failed to setup flagsmith",{error:se})}try{yield y}catch(se){l.error("[Controller]: Failed to connect to socket server:",{error:se})}try{({sfu:N,meetingTitle:U}=yield h.getRoomNodeData()),M=yield E,l.info(`SFU ${N} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:N})}catch(se){l.error("Failed to get room metadata",{error:se})}const $=G1.init(M.preset,!t.getValue("modules").theme),J=hD.init(t,$.viewType,M.preset.permissions),I=xs.setupControllers(g,t,M,b,U,$,J);YA($)&&((e=xs.createRoomNodeClient(t,g).initializeConnection(M.participant.name,o,!1,J))==null||e.catch(se=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:se})})),S.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ae}=yield I;return J_(),new xs(r,ae)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:n,overrides:r,meetingId:s,organizationId:o}=t.getAllValues(),c=G_(s),d=H(x({entity:$l.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=r==null?void 0:r.whitelabelled_flags_endpoint)==null||e?Wr({servicePrefix:"flags",baseURI:n}):"edge.api.flagsmith.com";yield z.identify(`${$l.PEER}_${i}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,l),l.info("flagsmith::allFlags",{flags:JSON.stringify(z.getAllFlags())},!0)}catch(h){l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,n,r,s,o){return u(this,null,function*(){var c,d,h;const p=e.getValue("modules"),{participant:g}=i,y=e.getValue("defaults"),{sfu:E}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:N}}=s;e.setValue("viewType",b),e.setValue("defaults",x({mediaConfiguration:{audio:{enableHighBitrate:(c=N.enableHighBitrate)!=null?c:!1,enableStereo:(d=N.enableStereo)!=null?d:!1}}},y)),e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let M,U,$,J,I,ae,se,Se;const nt=new GD(t);Le.socketService=t;const gt=new $d(t),Ft=new ei(t),A=new KD(t),k=hd.create(t,e),_=new zD(t),j=new qD(t),Re=new tr(t),fe=yield On.init(e,k,g,o,s),F=yield Af.init(e,fe.self,k,nt,r);if(p.participant&&(Se=new Qi(e,fe.self,k,E)),(h=p.e2ee)!=null&&h.enabled&&p.e2ee.manager.init(l,P),p.chat&&(U=yield Ji.init(e,Ft,Re,fe.self,Se.participants)),p.internals&&(I=yield Ru.init()),p.livestream&&s.viewType===Rt.Livestream&&z.hasFeature(ne.LIVESTREAM)&&(se=new zf(fe.self,j)),s.viewType!==Rt.Chat){if(p.poll&&(M=yield wf.init(e,fe.self,gt)),p.recording&&(ae=new Ff(e,fe.self,k)),p.stage&&($=new Df(e,A,k,fe.self,Se.participants)),p.plugin){if(!Se)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const Ge=yield n;J=yield ma.init(e,Ge,_,Ft,U==null?void 0:U.chat,fe.self,Se.participants,r)}if(p.pip){const Ge=yield Y_._init(e,fe.self);e.setValue("pip",Ge)}}const C={storesManager:new Z1(e,_),pollController:M,selfController:fe,metaController:F,chatController:U,stageController:$,pluginController:J,recordingController:ae,internalsController:I,livestreamController:se,participantController:Se};return{theme:s,permissions:o,controllers:C}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:n}=t.getAllValues(),{sfu:r}=n;return Hv(t,r,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:n}=t.getAllValues(),r=["PING"];return new wo(t,{peerId:e,meetingId:i,authToken:n,capabilities:r})}};let Io=xs;sl([S.trace("Controller.init")],Io,"init",1),sl([S.trace("setupFlagsmith")],Io,"setupFlagsmith",1),sl([S.trace("Controller.createRoomNodeClient")],Io,"createRoomNodeClient",1),sl([S.trace("Controller.createSocketService")],Io,"createSocketService",1);var yO=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,TO=(t,e,i,n)=>{for(var r=n>1?void 0:n?SO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&yO(e,i,r),r},al,ep;class py extends Bt{constructor(e,i){super(),f(this,al,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),f(this,ep,void 0),v(this,ep,e),v(this,al,i.self)}get supportsConnectedMeetings(){return a(this,al).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Le.currentMeetingId}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 Le.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Le.createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Le.updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(r=>r.id)):Promise.resolve());return yield Promise.all(i),yield Le.disableConnectedRooms(e)})}moveParticipants(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Le.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n.map(s=>({id:s}))});return r.success&&this.moveSuccessHandler(e,i,n),r})}moveParticipantsWithCustomPreset(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Le.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n});return r.success&&this.moveSuccessHandler(e,i,n.map(s=>s.id)),r})}moveSuccessHandler(e,i,n){const r=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>r.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>r.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(n.map(c=>r.get(c)));return H(x({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!n.includes(c.id));return H(x({},s),{participants:o})}return s})}}al=new WeakMap,ep=new WeakMap,TO([At({maxInvocations:60,period:60})],py.prototype,"getConnectedMeetings",1);var EO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,tp=(t,e,i,n)=>{for(var r=n>1?void 0:n?kO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&EO(e,i,r),r},Co,_i,ip,np;const Bn=(ip=class{constructor(t,e,i){m(this,"connectedMeetings"),f(this,Co,void 0),f(this,_i,void 0),f(this,np,void 0),v(this,np,t),v(this,Co,i),this.connectedMeetings=new py(t,e),this.setCurrentMeeting(e)}static init(t,e,i){return Bn.instance||(Bn.instance=new Bn(t,e,i)),Bn.instance.connectedMeetings.supportsConnectedMeetings&&(Bn.instance.setupEvents(),e.self.once("roomJoined",()=>Bn.instance.getConnectedMeetings())),Bn.instance}setCurrentMeeting(t){v(this,_i,t),Le.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Le.socketService&&(Le.socketService.on(W.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Le.socketService.on(W.transferPeer,this.handleTransferPeer.bind(this)),Le.socketService.on(W.movedPeer,this.handleMovedPeer.bind(this)),Le.socketService.on(W.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Le.socketService.on(W.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Le.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var n,r,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.`);l.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,_i).self.videoEnabled,audio:a(this,_i).self.audioEnabled};try{a(this,_i).self.cleanupEvents(),yield a(this,_i).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(r=(n=a(this,_i))==null?void 0:n.meta)==null?void 0:r.meetingId}`,{error:h})}Le.socketService=void 0,l.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield vy.init(H(x({},a(this,Co)),{cachedUserDetails:null,defaults:H(x(x({},a(this,Co).defaults),c),{mediaHandler:a(this,_i).self}),authToken:e}));l.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:h}=a(this,_i).self;d.self.setName(a(this,_i).self.name),yield d.join(),h&&d.self.hide()}catch(h){l.error("ConnectedMeetingsController.joinRoom",{error:h})}return l.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),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Le.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 Le.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Le.handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(n=>{i.set(n.id,n)}),e.forEach(n=>{i.has(n.id)?i.get(n.id).title=n.title:i.set(n.id,H(x({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Le.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})}},Co=new WeakMap,_i=new WeakMap,np=new WeakMap,m(ip,"instance"),ip);let ol=Bn;tp([S.trace("ConnectedMeetingsController.getConnectedMeetings")],ol.prototype,"getConnectedMeetings",1),tp([S.trace("ConnectedMeetingsController.setupEvents")],ol.prototype,"setupEvents",1),tp([S.trace("ConnectedMeetingsController.switchMeeting")],ol.prototype,"switchMeeting",1);class bO{constructor(){m(this,"battery"),m(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(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 my=new bO;function _O(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:n,participantId:r}=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://api.${s}`;return{meetingId:i,orgId:n,participantId:r,baseURI:s,apiBase:o}}catch(i){throw l.error("constants::decodeAuthToken",{error:i,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var wO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,cl=(t,e,i,n)=>{for(var r=n>1?void 0:n?IO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&wO(e,i,r),r},ot,dl,ll,rp,gy,fy;let Wn=(fy=class{constructor(t,e){f(this,rp),f(this,ot,void 0),f(this,dl,void 0),f(this,ll,void 0),v(this,ll,t),v(this,ot,e)}static init(t){return u(this,null,function*(){var e,i,n,r,s,o,c;j_(),Ie.init();const d=(i=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?i:Nr();my.init();const{authToken:h,baseURI:p}=t,g=_O(h,p),{meetingId:y}=g,E=rc(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Wn.setupContext(d,t,y,E);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=E.participantId,S.meetingMetadata.organizationId=E.orgId,S.init(b,(r=(n=t.modules)==null?void 0:n.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:H(x({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
22
- ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const N=yield Io.init(b),M=new Wn(b,N);return B(c=M,rp,gy).call(c,t),M})}static setupContext(t,e,i,n){var r;const s=Yn.createContext(t,e),o=x(x({},x_),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",i),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(r=e.overrides)!=null?r:{}),s.setValue("env",V_({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",hi(e.cachedUserDetails)),s.setValue("sdkVersion","3.0.2-staging.6"),s}join(){return u(this,null,function*(){const{selfController:t}=a(this,ot);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){my.cleanup();const{selfController:e}=a(this,ot);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,ot).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,ot).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,ot).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,ot).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,ot).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,ot).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,ot).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,dl))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,ot).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,ot).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,ot).stageController)==null?void 0:t.stage}get stores(){return a(this,ot).storesManager}get __internals__(){var t;return(t=a(this,ot).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)})}},ot=new WeakMap,dl=new WeakMap,ll=new WeakMap,rp=new WeakSet,gy=function(t){v(this,dl,ol.init(a(this,ll),this,t))},fy);cl([lt("0002"),_n.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Wn.prototype,"join",1),cl([lt("0003")],Wn.prototype,"leave",1),cl([lt("0001"),_n.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Wn,"init",1),Wn=cl([lt("0000")],Wn);const vy=Wn;return vy}();
22
+ ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const N=yield Io.init(b),M=new Wn(b,N);return B(c=M,rp,gy).call(c,t),M})}static setupContext(t,e,i,n){var r;const s=Yn.createContext(t,e),o=x(x({},x_),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",i),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(r=e.overrides)!=null?r:{}),s.setValue("env",V_({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",hi(e.cachedUserDetails)),s.setValue("sdkVersion","3.0.2-staging.7"),s}join(){return u(this,null,function*(){const{selfController:t}=a(this,ot);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){my.cleanup();const{selfController:e}=a(this,ot);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,ot).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,ot).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,ot).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,ot).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,ot).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,ot).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,ot).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,dl))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,ot).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,ot).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,ot).stageController)==null?void 0:t.stage}get stores(){return a(this,ot).storesManager}get __internals__(){var t;return(t=a(this,ot).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)})}},ot=new WeakMap,dl=new WeakMap,ll=new WeakMap,rp=new WeakSet,gy=function(t){v(this,dl,ol.init(a(this,ll),this,t))},fy);cl([lt("0002"),_n.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Wn.prototype,"join",1),cl([lt("0003")],Wn.prototype,"leave",1),cl([lt("0001"),_n.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Wn,"init",1),Wn=cl([lt("0000")],Wn);const vy=Wn;return vy}();
package/dist/index.cjs.js CHANGED
@@ -20,4 +20,4 @@ ${t}`}const Ns={maxInvocations:5,period:1};function Ut(t,e){return function(i,n,
20
20
  maxEnergy: ${a(this,or)}`),r===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,_n)||r<a(this,_n))&&v(this,_n,r),(!a(this,or)||r>a(this,or))&&v(this,or,r),{energy:(r-a(this,_n))/(a(this,or)-a(this,_n))*10||0,isVoice:n})},nd=new WeakSet,ph=function(t){return t<5},mh=new WeakSet,Xv=function(t=a(this,ks)){var e;if(!a(this,Ni)||!t){Y.hasFeature(ie.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&l.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Ni)}`);return}const i={producerId:a(this,Ni),energy:Math.round(t),silent:B(e=xd,nd,ph).call(e,t)};v(this,_o,i.silent),this.reportRequest(i)},Gl=new WeakSet,cg=function(t){const e=Math.log10(t);return Math.round(e)},f(gh,nd),f(gh,Gl);const HD=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const i=new window.MediaStreamTrackGenerator({kind:"audio"}),n=i.writable.getWriter(),r=48e3,s=128,o=1;let c=0,d=null;const h=()=>u(void 0,null,function*(){try{const g=new Float32Array(s*o),y=new window.AudioData({format:"f32",sampleRate:r,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:g});c+=s/r*1e6,yield n.ready,yield n.write(y)}catch{d&&clearInterval(d),n.releaseLock(),i.writable.abort()}});d=window.setInterval(h,100);const p=new MediaStream([i]).getAudioTracks()[0];return p.addEventListener("ended",()=>{d&&clearInterval(d),n.releaseLock(),i.writable.abort()}),p}catch{}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const i=new e;if(!i||i.state!=="running"||!i.destination)return;const n=i.createOscillator();n.frequency.value=0,n.type="sine";const r=i.createGain();r.gain.value=0,n.connect(r);const s=i.createMediaStreamDestination();r.connect(s),n.start();const o=s.stream.getAudioTracks()[0];return o?(o.enabled=t,o):void 0}catch{return}},qD=(t=!1)=>{var e,i;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(e=n==null?void 0:n.getSettings().height)!=null?e:720,r.width=(i=n==null?void 0:n.getSettings().width)!=null?i:1280;const s=r.getContext("2d");s.fillStyle="black",s.fillRect(0,0,r.width,r.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,r.width,r.height)},1e3);const o=r.captureStream().getVideoTracks()[0];return o.enabled=t,o};var GD=Object.defineProperty,$D=Object.getOwnPropertyDescriptor,fe=(t,e,i,n)=>{for(var r=n>1?void 0:n?$D(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&GD(e,i,r),r};const wi=["video/VP9","video/VP8"];var vc,yc,vt,Q,Da,Bi,At,Kr,zr,Yr,Sc,oi,un,Oa,Qr,Xr,Dt,Wt,Jn,Zr,$l,dg,Jl,lg,Kl,ug,Tc,zl,Yl,Ql,hg,Xl,pg,Zl,mg,eu,gg,dt,yt,es,Na,tu,fg,iu,vg,nu,yg;const Zv=(Ql=class{constructor(t,e,i){f(this,Jn),f(this,$l),f(this,Jl),f(this,Kl),f(this,Tc),f(this,Xl),f(this,Zl),f(this,eu),f(this,dt),f(this,es),f(this,tu),f(this,iu),f(this,nu),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),f(this,vc,void 0),f(this,yc,void 0),f(this,vt,void 0),f(this,Q,void 0),f(this,Da,void 0),f(this,Bi,void 0),f(this,At,void 0),f(this,Kr,void 0),f(this,zr,void 0),f(this,Yr,void 0),f(this,Sc,void 0),f(this,oi,null),f(this,un,void 0),f(this,Oa,void 0),f(this,Qr,void 0),f(this,Xr,void 0),f(this,Dt,void 0),f(this,Wt,void 0);var n,r;this.context=t;const{socket:s}=i;this.mediaJoined=!1,v(this,Qr,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Xr,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Bi,e),v(this,vt,s),v(this,Kr,!1),v(this,Q,new BD(t,s,e)),v(this,At,a(this,Q).events),v(this,un,new Set),v(this,Dt,new Map),v(this,zr,!1),v(this,Yr,new Wu),e===Le.CF&&!navigator.isReactNative&&v(this,Wt,new gh(a(this,Q).socketHandler.audioActivity.bind(a(this,Q).socketHandler))),this.e2ee=(r=(n=t.getValue("modules").e2ee)==null?void 0:n.enabled)!=null?r:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,Sc,Fh(()=>u(this,null,function*(){if(!a(this,Jn,Zr).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,yc),a(this,vc),!0,!0);o&&(P.emit(R.RESET_PRODUCER_STATE),P.emit(R.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return a(this,Jn,Zr).mediaJoined}set mediaJoined(t){a(this,Jn,Zr).mediaJoined=t}reset(){a(this,Q).closeAllProducers(),a(this,Q).closeAllConsumers(),a(this,Dt).clear(),a(this,un).clear(),v(this,oi,null),a(this,Yr).stop(),a(this,Q).stopAllTransports(),a(this,Q).reset(),v(this,Yr,new Wu)}joinRoom(t,e){return u(this,arguments,function*(i,n,r=!1,s=!1,o={}){a(this,Jn,Zr).mediaJoinAttempted=!0,v(this,Kr,!0),r&&this.reset();try{return yield a(this,Yr).push(()=>B(this,$l,dg).call(this,i,n,s,o),"joinRoom")}catch(c){return l.error("Error in room joining process",{error:c}),P.emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(i,n,r=!1,s={}){return a(this,oi)?a(this,oi):(v(this,oi,(()=>u(this,null,function*(){try{yield B(this,Tc,zl).call(this,i,n,r,s)}catch(o){throw v(this,oi,null),o}}))()),a(this,oi))})}getConsumers(){return a(this,Q).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,Q).stopAllTransports(),v(this,zr,!1),a(this,Jn,Zr).mediaJoinAttempted=!1;const e={closeRoom:!1};try{const i=yield a(this,vt).sendMessagePromise(a(this,At).leaveRoom,Ww.toBinary(e));(t=RI.fromBinary(i.payload))!=null&&t.closed||l.warn("weird state on peer closed and should not happen")}catch(i){l.error("error on sending leave room request",{error:i})}K.callEnded(),S.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,Q).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((i,n)=>{const r=a(this,Q).producerIdToConsumerIdMap.get(n.producerId);return r?(i.push(r),i):(l.warn(`consumer not found in close consumers: ${n.producerId}`),i)},[]);yield a(this,Q).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const i=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,n=B(this,dt,yt).call(this,i);if(n){const h=yield n;if(a(this,Q).producers.has(h)){const p=a(this,Q).producers.get(h);if(!p.closed)return yield p.replaceTrack({track:t}),yield this.resumeWebcam(i),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const r=B(this,nu,yg).call(this,t,e),s=Ps(this.context,"disableSimulcast"),o=a(this,Bi)===Le.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!s&&Y.hasFeature(o)?(l.info(`Simulcast enabled for SFU: ${a(this,Bi)}`),r.encodings=I1(t)):l.info(`Simulcast disabled for webcam producer, SFU: ${a(this,Bi)}`),Y.hasFeature(ie.TRACK_HINT)&&(r.track.contentHint=Y.getValue(ie.TRACK_HINT));const c=()=>{l.info("Disabling video due to the producer closure"),a(this,Dt).delete(i)},d=a(this,Q).createProducer(r,c);return B(this,es,Na).call(this,i,d.then(h=>h.id)),d.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(Y.hasFeature(ie.FORCE_VIDEO_CODEC)){const e=Y.getValue(ie.FORCE_VIDEO_CODEC).toString();if(e)return l.debug(`Calling _shareWebcam with forced video codec: ${e}`),this._shareWebcam(t,e)}return yield Promise.all(wi.map(e=>{var i,n;return((n=(i=a(this,Da).sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(r=>r.mimeType===e))>=0&&a(this,Xr).get(e).size>0?(l.debug(`Calling _shareWebcam with video codec: ${e}`),this._shareWebcam(t,e)):t})),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:i}=t;if(e===void 0)return;const n={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Re.isElectron()},stopTracks:!1},r=()=>{l.info("Disabling screenShare due to the producer closure"),a(this,Dt).delete(ke.SCREENSHARE_VIDEO),a(this,Dt).delete(ke.SCREENSHARE_AUDIO)},s=a(this,Q).createProducer(n,r);B(this,es,Na).call(this,ke.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:Re.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,Bi)!==Le.CF},d=()=>{};o=a(this,Q).createProducer(c,d),B(this,es,Na).call(this,ke.SCREENSHARE_AUDIO,o.then(h=>h.id))}yield Promise.all([s,o||Promise.resolve()]),K.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new xt("track undefined");const e=B(this,dt,yt).call(this,ke.MIC);if(e){const s=yield e;if(a(this,Q).producers.has(s)){const o=a(this,Q).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Wt)&&(a(this,Wt).audioTrack=t,a(this,Wt).producerId=s,a(this,Wt).start());return}yield a(this,Q).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const i=B(this,iu,vg).call(this,t),n=()=>{a(this,Dt).delete(ke.MIC)},r=a(this,Q).createProducer(i,n);B(this,es,Na).call(this,ke.MIC,r.then(s=>s.id)),yield r.then(s=>{a(this,Wt)&&(a(this,Wt).audioTrack=s.track,a(this,Wt).producerId=s.id,a(this,Wt).start())})}catch(e){throw new w(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield B(this,dt,yt).call(this,ke.MIC),i=a(this,Q).producers.get(e);if(!i){l.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){l.info("pauseMic::mic_producer_already_paused");return}i.pause(),(t=a(this,Wt))==null||t.stop();const n={producerId:i.id,pause:!0};a(this,vt).sendMessage(a(this,At).toggleProducer,Qo.toBinary(n))})}pauseWebcam(){return u(this,null,function*(){const t=yield B(this,dt,yt).call(this,ke.WEBCAM),e=yield B(this,dt,yt).call(this,ke.WEBCAM_BACKUP),i=a(this,Q).producers.get(t),n=a(this,Q).producers.get(e);if(!i&&!n){l.error("pauseWebcam::could_not_find_webcam_producer");return}const r=s=>{const o={producerId:s.id,pause:!0};a(this,vt).sendMessage(a(this,At).toggleProducer,Qo.toBinary(o))};i&&(i.pause(),r(i)),n&&(n.pause(),r(n))})}resumeMic(){return u(this,null,function*(){const t=yield B(this,dt,yt).call(this,ke.MIC),e=a(this,Q).producers.get(t);if(!e){l.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){l.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,e);const i={producerId:e.id,pause:!1};a(this,vt).sendMessage(a(this,At).toggleProducer,Qo.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(t=ke.WEBCAM){const e=yield B(this,dt,yt).call(this,t),i=a(this,Q).producers.get(e);if(!i){l.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){l.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,i);const n={producerId:i.id,pause:!1};a(this,vt).sendMessage(a(this,At).toggleProducer,Qo.toBinary(n))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=yield B(this,dt,yt).call(this,e);B(this,tu,fg).call(this,e),i&&(yield a(this,Q).closeProducer(i))})}disableMic(){return u(this,null,function*(){var t;const e=yield B(this,dt,yt).call(this,ke.MIC);e&&(yield a(this,Q).closeProducer(e)),(t=a(this,Wt))==null||t.stop(),a(this,Dt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),K.screenShareStop();const t=yield B(this,dt,yt).call(this,ke.SCREENSHARE_VIDEO),e=yield B(this,dt,yt).call(this,ke.SCREENSHARE_AUDIO);t&&(yield a(this,Q).closeProducer(t)),e&&(yield a(this,Q).closeProducer(e)),a(this,un).clear(),a(this,Dt).delete(ke.SCREENSHARE_VIDEO),a(this,Dt).delete(ke.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 B(this,dt,yt).call(this,ke.WEBCAM),n=yield B(this,dt,yt).call(this,ke.WEBCAM_BACKUP);yield a(this,Q).closeProducer(i,{stopTrack:!1}),yield a(this,Q).closeProducer(n,{stopTrack:!1}),this.shareWebcam(t)}if(e){const i=yield B(this,dt,yt).call(this,ke.SCREENSHARE_VIDEO);yield a(this,Q).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,Q).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,Q).socketHandler.kickPeer(e)}kickAll(){a(this,Q).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,Q).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,Q).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,Q).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,Q).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,vt).sendMessagePromise(a(this,At).globalPinPeer,tI.toBinary(e))}catch(i){l.error("Error in pinning peer:",{error:i})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,Q).producers.get(t.producerId)&&a(this,un).add(t.consumerPeerId),a(this,un).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const i=t.map(n=>this.getConsumers().get(n));a(this,Q).switchConsumersToLayer(i,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,vt).on(a(this,At).peerProducerCreateBroadcast,({payload:t})=>{var e,i;if(this.mediaJoined)try{const{participantId:n,producerState:r}=sC.fromBinary(t);if(n===this.peerId)return;if(r!=null&&r.mimeType||(r.mimeType=r.kind===Li.AUDIO?"audio/opus":"video/VP8"),r.kind===Li.VIDEO&&!r.screenShare&&((i=(e=a(this,Da).receiver)==null?void 0:e.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===wi[0]))>=0&&a(this,Qr).get(wi[0]).has(n)&&r.mimeType!==wi[0]){l.warn(`Ignoring producer: ${r.producerId}`);return}l.info(`producer created broadcast: ${n}, producer state: ${r}`),P.emit(R.NEW_PRODUCER,{peerId:n,producer:$(x({},r),{kind:r.kind===Li.AUDIO?"audio":"video",producingPeerId:n})})}catch(n){l.error("error in peer-producer-create-broadcast",{error:n})}}),a(this,vt).on(a(this,At).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:i,producerState:{kind:n,pause:r,producerId:s}}=dm.fromBinary(t),o=n===Li.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${r} payload: ${JSON.stringify(dm.fromBinary(t))}`),e===this.peerId&&i!==this.peerId&&r&&P.emit(o==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),e===this.peerId)return;P.emit(R.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:r,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===s).forEach(c=>{c.paused!==r&&(l.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${r}`),r?(c.pause(),P.emit(R.CONSUMER_PAUSED,{id:c.id})):(c.resume(),P.emit(R.CONSUMER_RESUMED,{id:c.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),a(this,vt).on(a(this,At).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ku.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),a(this,un).delete(e),a(this,Q).consumers.forEach(i=>{i.peerId===e&&i.close()}),P.emit(R.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),a(this,vt).on(a(this,At).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:i}}=cC.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),P.emit(R.PRODUCER_CLOSED,{peerId:e,producerId:i});const n=a(this,Q).producerIdToConsumerIdMap.get(i);if(!n){l.warn(`no consumer found for producer:${i}`);return}l.info(`closing consumer ${n}, producer id: ${i}`),a(this,Q).closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),a(this,Q).producerIdToConsumerIdMap.delete(i),P.emit(R.CONSUMER_CLOSED,{id:n})}).catch(r=>{l.error("error closing consumer",{error:r})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),a(this,vt).on(a(this,At).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Kr)&&!a(this,zr)||(l.warn("media hub termination broadcast received, rejoining room"),P.emit(R.ROOM_NODE_DISCONNECTED),a(this,Sc).call(this))})})}handleCallstatsEvents(){K.onConsumerScore(t=>{t.forEach((e,i)=>{const n=a(this,Q).consumers.get(i);n&&P.emit(R.CONSUMER_SCORE_UPDATE,{id:i,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),K.onProducerScore(t=>{t.forEach((e,i)=>{const n=Array.from(a(this,Q).producers.values()).find(r=>r.id===i);n&&P.emit(R.PRODUCER_SCORE_UPDATE,{id:i,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var i,n,r,s;for(let o=0;o<=wi.length;o+=1){const c=wi[o];if(((n=(i=e==null?void 0:e.receiver)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===wi.length-1){a(this,Xr).get(c).add(t);break}}for(let o=0;o<=wi.length;o+=1){const c=wi[o];if(((s=(r=e==null?void 0:e.sender)==null?void 0:r.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===wi.length-1){a(this,Qr).get(c).add(t);break}}}handlePeerLeaving(t){Y.hasFeature(ie.FORCE_VIDEO_CODEC)||(a(this,Qr).forEach(e=>e.delete(t)),a(this,Xr).forEach((e,i)=>{e.delete(t),e.size===0&&this.disableWebcam(i)}))}},vc=new WeakMap,yc=new WeakMap,vt=new WeakMap,Q=new WeakMap,Da=new WeakMap,Bi=new WeakMap,At=new WeakMap,Kr=new WeakMap,zr=new WeakMap,Yr=new WeakMap,Sc=new WeakMap,oi=new WeakMap,un=new WeakMap,Oa=new WeakMap,Qr=new WeakMap,Xr=new WeakMap,Dt=new WeakMap,Wt=new WeakMap,Jn=new WeakSet,Zr=function(){return this.context.getValue("connectionHandler")},$l=new WeakSet,dg=function(t,e,i,n){return u(this,null,function*(){v(this,yc,t);try{return a(this,oi)?yield a(this,oi):yield B(this,Tc,zl).call(this,t,e,i,n),B(this,Kl,ug).call(this,e),{roomJoined:yield B(this,Jl,lg).call(this)}}catch(r){return l.error("Failed to complete room join",{error:r}),{roomJoined:!1}}finally{v(this,oi,null)}})},Jl=new WeakSet,lg=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,Q).socketHandler.notifySelfJoinComplete();return v(this,vc,t.roomUuid),v(this,zr,!0),v(this,Kr,!1),!0}catch(t){return l.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},Kl=new WeakSet,ug=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:$(x({},Re.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};K.roomJoined(e)}catch(e){l.error("Error reporting room joined analytics",{error:e})}},0)},Tc=new WeakSet,zl=function(t,e,i,n){return u(this,null,function*(){var r,s;try{(s=a(this,Oa))!=null||v(this,Oa,B(r=Zv,Yl,hg).call(r));const o=B(this,Xl,pg).call(this);yield B(this,Zl,mg).call(this,t,e,i,o),yield a(this,Q).setupTransports({send:!0,recv:!0}),yield B(this,eu,gg).call(this,n)}catch(o){throw l.error("Failed to initialize connection",{error:o}),o}})},Yl=new WeakSet,hg=function(){const{ipInfo:t}=ut();if(!(t!=null&&t.loc))return;const[e,i]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:i}},Xl=new WeakSet,pg=function(){var t;const e=(t=Y.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),i=CD(e);return v(this,Da,i),i},Zl=new WeakSet,mg=function(t,e,i,n){return u(this,null,function*(){yield Uv((r,s)=>u(this,null,function*(){if(!a(this,vt).isConnected){s(new Error("Socket is not connected"));return}r>0&&l.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${r}`});try{yield a(this,Q).socketHandler.joinRoom(e,t,n,i,a(this,Oa))}catch(o){throw l.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Y.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},eu=new WeakSet,gg=function(t){return u(this,null,function*(){if(!(a(this,Bi)===Le.HIVE||!Y.hasFeature(ie.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(qD())),t.canProduceAudio===G.Allowed){const i=HD();i&&e.push(this.shareMic(i))}e.length>0&&(yield Promise.all(e))}catch(e){l.warn("Failed to precreate producers",{error:e})}})},dt=new WeakSet,yt=function(t){return a(this,Dt).get(t)},es=new WeakSet,Na=function(t,e){return a(this,Dt).set(t,e)},tu=new WeakSet,fg=function(t){return a(this,Dt).delete(t)},iu=new WeakSet,vg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,Bi)!==Le.CF}},nu=new WeakSet,yg=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},f(Ql,Yl),Ql);let he=Zv;fe([S.trace("MediaNodeClient.reset",{country:S.location.country})],he.prototype,"reset",1);fe([S.trace("MediaNodeClient.joinRoom")],he.prototype,"joinRoom",1);fe([S.trace("MediaNodeClient.leaveRoom")],he.prototype,"leaveRoom",1);fe([S.trace("MediaNodeClient.activatePeers")],he.prototype,"activatePeers",1);fe([S.trace("MediaNodeClient.createConsumers")],he.prototype,"createConsumers",1);fe([S.trace("MediaNodeClient.closeConsumers")],he.prototype,"closeConsumers",1);fe([S.trace("MediaNodeClient._shareWebcam")],he.prototype,"_shareWebcam",1);fe([S.trace("MediaNodeClient.shareWebcam")],he.prototype,"shareWebcam",1);fe([S.trace("MediaNodeClient.shareScreen")],he.prototype,"shareScreen",1);fe([S.trace("MediaNodeClient.shareMic")],he.prototype,"shareMic",1);fe([S.trace("MediaNodeClient.pauseMic")],he.prototype,"pauseMic",1);fe([S.trace("MediaNodeClient.pauseWebcam")],he.prototype,"pauseWebcam",1);fe([S.trace("MediaNodeClient.resumeMic")],he.prototype,"resumeMic",1);fe([S.trace("MediaNodeClient.resumeWebcam")],he.prototype,"resumeWebcam",1);fe([S.trace("MediaNodeClient.disableWebcam")],he.prototype,"disableWebcam",1);fe([S.trace("HiveClient.disableMic")],he.prototype,"disableMic",1);fe([S.trace("HiveClient.disableScreenShare")],he.prototype,"disableScreenShare",1);fe([S.trace("MediaNodeClient.muteSelf")],he.prototype,"muteSelf",1);fe([S.trace("MediaNodeClient.resetVideoProducers")],he.prototype,"resetVideoProducers",1);fe([S.trace("MediaNodeClient.changeDisplayName")],he.prototype,"changeDisplayName",1);fe([S.trace("MediaNodeClient.kickPeer")],he.prototype,"kick",1);fe([S.trace("MediaNodeClient.kickAllPeers")],he.prototype,"kickAll",1);fe([S.trace("MediaNodeClient.muteAll")],he.prototype,"muteAll",1);fe([S.trace("MediaNodeClient.muteAllVideo")],he.prototype,"muteAllVideo",1);fe([S.trace("MediaNodeClient.disableAudio")],he.prototype,"disableAudio",1);fe([S.trace("MediaNodeClient.disableVideo")],he.prototype,"disableVideo",1);fe([S.trace("MediaNodeClient.pinPeer")],he.prototype,"pinPeer",1);fe([S.trace("MediaNodeClient.validateScreenShare")],he.prototype,"validateScreenShare",1);function ey(t,e,i){const n=t.getValue("roomNodeClient");if(n){if(n)return n;throw new Error("Room node client already set up.")}const r=new he(t,e,i);return t.setValue("roomNodeClient",r),r}function ty(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Or=(t,e,i,n)=>{for(var r=n>1?void 0:n?KD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&JD(e,i,r),r},Kn,Ii,St,Ot,jt,Sg;const iy=(Sg=class{constructor(t,e,i,n){f(this,Ot),m(this,"self"),m(this,"authToken"),f(this,Kn,void 0),m(this,"viewType"),f(this,Ii,void 0),f(this,St,void 0);const{socket:r}=i,s=t.getValue("authToken");this.self=e,v(this,St,t),this.viewType=n,this.authToken=s,v(this,Kn,r),v(this,Ii,i),e.config.viewType!==Vt.Chat&&this.setupEvents()}get peerId(){return a(this,St).getValue("peerId")}get mediaJoined(){return a(this,St).getValue("connectionHandler").mediaJoined}static init(t,e,i,n,r){return u(this,null,function*(){const s=ut(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield nt.__init__(t,i,n,r,r.name,c);if(navigator.product!=="ReactNative"){const h=!Y.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),K.devices("AUDIO",p==null?void 0:p.filter(g=>g.kind==="audioinput")),K.devices("VIDEO",p==null?void 0:p.filter(g=>g.kind==="videoinput")),K.devices("SPEAKER",p==null?void 0:p.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield K.initialize({peerId:o,engineName:Re.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Y.getAllFlags(),logger:l,apiHostnames:Xf(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new iy(t,d,e,r.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:n,audioEnabled:r,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(n.canProduceAudio===G.Allowed&&r)try{yield a(this,Ot,jt).shareMic(e),this.self.audioEnabled||a(this,Ot,jt).pauseMic()}catch{this.self.disableAudio()}if(n.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Ot,jt).shareWebcam(i);d&&d.id!==i.id&&Y.hasFeature(ie.EXP_RESHARE)&&(yield a(this,Ot,jt).shareWebcam(d)),this.self.videoEnabled||a(this,Ot,jt).pauseWebcam()}catch{this.self.disableVideo()}if(n.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Ot,jt))==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(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){K.callEnded(),a(this,Ot,jt).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){P.on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),P.on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),P.on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),P.on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),P.on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),P.on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Y.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=As()),a(this,Kn).updateURL(e),S.resetPeerId(e),ut().setHeader("dyte-tracing-id",e),Tr.remapContext(e,a(this,St)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),P.on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ii).on(W.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ii).on(Ac.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&P.emit(R.UPDATE_PERMISSIONS,e.patch)})}),a(this,Ii).on(W.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ii).on(W.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ii).on(W.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),P.onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),P.on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:n})=>{var r;const s=(r=i==null?void 0:i.screenShare)!=null?r:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:n})}),P.on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),K.audioOff())})),P.on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),K.videoOff())})),P.onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),P.on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Ii).joinRoom(this.self);a(this,Ii).socket.flush();const i=Gh(e.stageType);if(a(this,St).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,St).notify("stageStatus")}catch(e){throw l.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,Kn))==null||e.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,St).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,St).notify("stageStatus");try{(i=a(this,Kn))==null||i.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}ty(a(this,St)),Pd.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:n,viewType:r,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,St).getAllValues(),{sfu:d}=c;try{if(r===Vt.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}ey(a(this,St),d,{socket:a(this,Kn),peerId:n})}const{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}=this.self.permissions,{roomJoined:y}=(i=yield(e=a(this,Ot,jt))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:h,canProduceVideo:p,canProduceScreenshare:g}))!=null?i:{};if(!y)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(h){throw l.error("Error:SelfController.mediaRoomJoin",{error:h}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,St).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Vt.Webinar)&&a(this,Ot,jt)&&(a(this,Ot,jt).mediaJoined&&t!=="disconnected"&&(yield a(this,Ot,jt).leaveRoom()),!(t==="stageLeft"&&e===Vt.Livestream)&&(a(this,Ot,jt).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()})}},Kn=new WeakMap,Ii=new WeakMap,St=new WeakMap,Ot=new WeakSet,jt=function(){return a(this,St).getValue("roomNodeClient")},Sg);let Wn=iy;Or([S.trace("SelfController.resetSelf")],Wn.prototype,"resetSelf",1);Or([S.trace("SelfController.setupEvents")],Wn.prototype,"setupEvents",1);Or([S.trace("SelfController.joinRoom")],Wn.prototype,"joinRoom",1);Or([S.trace("SelfController.leaveRoom")],Wn.prototype,"leaveRoom",1);Or([S.trace("SelfController.joinMediaRoom")],Wn.prototype,"joinMediaRoom",1);Or([S.trace("SelfController.leaveMediaRoom")],Wn.prototype,"leaveMediaRoom",1);Or([S.trace("SelfController.init")],Wn,"init",1);var rd;class zD{constructor(e){f(this,rd,void 0),v(this,rd,e)}on(e,i){let n;e===W.roomPeerCount?n=hm.fromBinary.bind(hm):n=bm.fromBinary.bind(bm),a(this,rd).on(e,({payload:r})=>{const s=n(r);return i(s)})}}rd=new WeakMap;var sd;class YD{constructor(e){f(this,sd,void 0),v(this,sd,e)}on(e,i){let n,r;switch(e){case W.transcript:{n=Tl.fromBinary.bind(Tl),r=Tl.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,sd).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}sd=new WeakMap;var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,np=(t,e,i,n)=>{for(var r=n>1?void 0:n?XD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&QD(e,i,r),r},wn;class sl{constructor(e){f(this,wn,void 0),v(this,wn,e)}getPolls(){return a(this,wn).sendMessagePromise($i.getPolls)}createPoll(e,i,n=!1,r=!1){const s={anonymous:n,hideVotes:r,question:e,options:i};return a(this,wn).sendMessage($i.createPoll,YM.toBinary(s))}votePoll(e,i){const n={index:i,pollId:e};return a(this,wn).sendMessage($i.votePoll,XM.toBinary(n))}on(e,i){let n,r;switch(e){case $i.updatePoll:case $i.createPoll:case $i.votePoll:{n=Il.fromBinary.bind(Il),r=Il.create();break}}a(this,wn).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){l.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,wn).removeListeners(e)}}wn=new WeakMap;np([S.trace("PollSocketHandler.getPolls")],sl.prototype,"getPolls",1);np([S.trace("PollSocketHandler.createPoll")],sl.prototype,"createPoll",1);np([S.trace("PollSocketHandler.votePoll")],sl.prototype,"votePoll",1);var Gt;class ZD{constructor(e){f(this,Gt,void 0),v(this,Gt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,Gt).sendMessagePromise(W.getStageRequests);return e?wl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,Gt).sendMessage(W.requestStageAccess)}cancelRequestAccess(){a(this,Gt).sendMessage(W.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Gt).sendMessage(W.grantStageAccess,BM.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,Gt).sendMessage(W.denyStageAccess,jM.toBinary(i))})}joinStage(){return a(this,Gt).sendMessagePromise(W.joinStage,void 0,void 0,W.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,Gt).sendMessagePromise(W.leaveStage,wm.toBinary(i),void 0,W.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,Gt).sendMessagePromise(W.leaveStage,wm.toBinary(i))}on(e,i){let n;switch(e){case W.grantStageAccess:case W.denyStageAccess:{n=void 0;break}case W.getStagePeers:{n=_m.fromBinary.bind(_m);break}case W.getStageRequests:case W.requestStageAccess:case W.cancelStageRequest:{n=wl.fromBinary.bind(wl);break}case W.peerStageStatusUpdate:{n=um.fromBinary.bind(um);break}}a(this,Gt).on(e,({payload:r,id:s})=>{if(!r||!n)return i(void 0,s);const o=n(r);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,Gt).sendMessagePromise(W.getPeerInfo,dv.toBinary({peerId:e}));return ts.fromBinary(i.payload)})}}Gt=new WeakMap;var et;class eO{constructor(e){f(this,et,void 0),v(this,et,e)}addPlugin(e,i){a(this,et).sendMessage(z.addPlugin,nM.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,et).sendMessage(z.removePlugin,sM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,et).sendMessagePromise(z.getPlugins);return e?PM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,n){const r={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,et).sendMessage(z.customPluginEventToRoom,gM.toBinary(r),n)}customPluginEventToPeers(e,i,n,r){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(n))};a(this,et).sendMessage(z.customPluginEventToPeers,vM.toBinary(s),r)}enablePluginForRoom(e,i){a(this,et).sendMessage(z.enablePluginForRoom,oM.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,n){a(this,et).sendMessage(z.enablePluginForPeers,uM.toBinary({pluginId:e,peerIds:i}),n)}disablePluginForRoom(e,i){a(this,et).sendMessage(z.disablePluginForRoom,dM.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,n){a(this,et).sendMessage(z.disablePluginForPeers,pM.toBinary({pluginId:e,peerIds:i}),n)}storeInsertKeys(e,i,n,r){const s={pluginId:e,storeName:i,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,et).sendMessage(z.storeInsertKeys,Sm.toBinary(s),r)}storeGetKeys(e,i,n,r){const s={pluginId:e,storeName:i,getKeys:n.map(o=>({storeKey:o.key}))};a(this,et).sendMessage(z.storeGetKeys,EM.toBinary(s),r)}storeDeleteKeys(e,i,n,r){const s={pluginId:e,storeName:i,deleteKeys:n.map(o=>({storeKey:o.key}))};a(this,et).sendMessage(z.storeDeleteKeys,bM.toBinary(s),r)}storeDelete(e,i,n){a(this,et).sendMessage(z.storeDelete,wM.toBinary({pluginId:e,storeName:i}),n)}getPluginDataOld(e,i){l.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,n){const r={pluginId:e,storeName:i,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};a(this,et).sendMessage(z.storeInsertKeys,Sm.toBinary(r))}on(e,i){let n;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{n=Iu.fromBinary.bind(Iu);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{n=Tm.fromBinary.bind(Tm);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{n=km.fromBinary.bind(km);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{n=Em.fromBinary.bind(Em);break}}a(this,et).on(e,({payload:r,id:s})=>{const o=n(r);return i(o,s)})}}et=new WeakMap;var tO=Object.defineProperty,iO=(t,e,i)=>e in t?tO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,nO=(t,e,i)=>(iO(t,typeof e!="symbol"?e+"":e,i),i),rp=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},L=(t,e,i)=>(rp(t,e,"read from private field"),i?i.call(t):e.get(t)),Ce=(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)},ue=(t,e,i,n)=>(rp(t,e,"write to private field"),n?n.call(t,i):e.set(t,i),i),De=(t,e,i)=>(rp(t,e,"access private method"),i),Vd={},rO={get exports(){return Vd},set exports(t){Vd=t}},bs=typeof Reflect=="object"?Reflect:null,Tg=bs&&typeof bs.apply=="function"?bs.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},ad;bs&&typeof bs.ownKeys=="function"?ad=bs.ownKeys:Object.getOwnPropertySymbols?ad=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ad=function(t){return Object.getOwnPropertyNames(t)};function sO(t){console&&console.warn&&console.warn(t)}var ny=Number.isNaN||function(t){return t!==t};function ge(){ge.init.call(this)}rO.exports=ge;Vd.once=dO;ge.EventEmitter=ge;ge.prototype._events=void 0;ge.prototype._eventsCount=0;ge.prototype._maxListeners=void 0;var Eg=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(ge,"defaultMaxListeners",{enumerable:!0,get:function(){return Eg},set:function(t){if(typeof t!="number"||t<0||ny(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Eg=t}});ge.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};ge.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||ny(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 ry(t){return t._maxListeners===void 0?ge.defaultMaxListeners:t._maxListeners}ge.prototype.getMaxListeners=function(){return ry(this)};ge.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var n=t==="error",r=this._events;if(r!==void 0)n=n&&r.error===void 0;else if(!n)return!1;if(n){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=r[t];if(c===void 0)return!1;if(typeof c=="function")Tg(c,this,e);else for(var d=c.length,h=dy(c,d),i=0;i<d;++i)Tg(h[i],this,e);return!0};function sy(t,e,i,n){var r,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]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),r=ry(t),r>0&&o.length>r&&!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,sO(c)}return t}ge.prototype.addListener=function(t,e){return sy(this,t,e,!1)};ge.prototype.on=ge.prototype.addListener;ge.prototype.prependListener=function(t,e){return sy(this,t,e,!0)};function aO(){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 ay(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},r=aO.bind(n);return r.listener=i,n.wrapFn=r,r}ge.prototype.once=function(t,e){return al(e),this.on(t,ay(this,t,e)),this};ge.prototype.prependOnceListener=function(t,e){return al(e),this.prependListener(t,ay(this,t,e)),this};ge.prototype.removeListener=function(t,e){var i,n,r,s,o;if(al(e),n=this._events,n===void 0)return this;if(i=n[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,r=s;break}if(r<0)return this;r===0?i.shift():oO(i,r),i.length===1&&(n[t]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};ge.prototype.off=ge.prototype.removeListener;ge.prototype.removeAllListeners=function(t){var e,i,n;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 r=Object.keys(i),s;for(n=0;n<r.length;++n)s=r[n],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(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function oy(t,e,i){var n=t._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?i?[r.listener||r]:[r]:i?cO(r):dy(r,r.length)}ge.prototype.listeners=function(t){return oy(this,t,!0)};ge.prototype.rawListeners=function(t){return oy(this,t,!1)};ge.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):cy.call(t,e)};ge.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}ge.prototype.eventNames=function(){return this._eventsCount>0?ad(this._events):[]};function dy(t,e){for(var i=new Array(e),n=0;n<e;++n)i[n]=t[n];return i}function oO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function cO(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,n){function r(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",r),i([].slice.call(arguments))}ly(t,e,s,{once:!0}),e!=="error"&&lO(t,r,{once:!0})})}function lO(t,e,i){typeof t.on=="function"&&ly(t,"error",e,i)}function ly(t,e,i,n){if(typeof t.on=="function")n.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function r(s){n.once&&t.removeEventListener(e,r),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class uO extends T{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 kg=new uO;class uy{static encode(e){return kg.toBinary(e)}static decode(e){return kg.fromBinary(new Uint8Array(e))}}function hO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var In;class pO{constructor(e={}){nO(this,"opts"),Ce(this,In,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ue(this,In,0)}wait(){return u(this,null,function*(){ue(this,In,L(this,In)+1);const e=hO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*bS(2,L(this,In))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return L(this,In)}reset(){ue(this,In,0)}}In=new WeakMap;const hn={debug:0,info:1,warn:2,error:3};var cr,dr;class mO{constructor(e){Ce(this,cr,void 0),Ce(this,dr,void 0),ue(this,cr,console),ue(this,dr,e)}debug(...e){hn[L(this,dr)]>hn.debug||L(this,cr).debug("[Sockrates]:",...e)}info(...e){hn[L(this,dr)]>hn.info||L(this,cr).info("[Sockrates]:",...e)}warn(...e){hn[L(this,dr)]>hn.warn||L(this,cr).warn("[Sockrates]:",...e)}error(...e){hn[L(this,dr)]>hn.error||L(this,cr).error("[Sockrates]:",...e)}}cr=new WeakMap,dr=new WeakMap;var hy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(hy||{});const gO="2",fO="3";var Fe,hs,Ae,Ge,Cn,tt,Qi,On,fi,ps,Gi,fh,py,lo,od,vh,my,yh,bg,Ud,Sh,Th,gy,wo,cd,Io,Fd,Bd,Eh,_s,Co,Po,Wd;class vO{constructor(e,i){var n;Ce(this,fh),Ce(this,lo),Ce(this,vh),Ce(this,yh),Ce(this,Ud),Ce(this,Th),Ce(this,wo),Ce(this,Io),Ce(this,Bd),Ce(this,_s),Ce(this,Po),Ce(this,Fe,void 0),Ce(this,hs,void 0),Ce(this,Ae,void 0),Ce(this,Ge,void 0),Ce(this,Cn,void 0),Ce(this,tt,void 0),Ce(this,Qi,void 0),Ce(this,On,void 0),Ce(this,fi,void 0),Ce(this,ps,void 0),Ce(this,Gi,void 0);var r,s,o,c,d,h,p,g,y;ue(this,hs,e),ue(this,Cn,[]),ue(this,tt,new Vd),ue(this,Qi,!0),ue(this,fi,!1),ue(this,Ae,i!=null?i:{}),(r=L(this,Ae)).autoReconnect!=null||(r.autoReconnect=!0),(s=L(this,Ae)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=L(this,Ae)).pingTimeout!=null||(o.pingTimeout=3e4),(c=L(this,Ae)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=L(this,Ae)).debug!=null||(d.debug=!0),(h=L(this,Ae)).maxReconnectionAttempts!=null||(h.maxReconnectionAttempts=10),(p=L(this,Ae)).disconnectOnPingTimeout!=null||(p.disconnectOnPingTimeout=!0),(g=L(this,Ae)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(y=L(this,Ae)).flushOnReconnect!=null||(y.flushOnReconnect=!1),ue(this,On,{code:void 0,reason:void 0}),ue(this,Ge,(n=L(this,Ae).logger)!=null?n:new mO(L(this,Ae).debug?"debug":"info")),ue(this,Gi,new pO)}get readyState(){var e;return(e=L(this,Fe))==null?void 0:e.readyState}get url(){return L(this,hs)}updateURL(e){ue(this,hs,e),De(this,Th,gy).call(this)}get config(){return L(this,Ae)}get sendQueue(){return L(this,Cn)}flush(){if(!L(this,Ae).queueOnDisconnect)return!1;const e=[];return L(this,Cn).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),ue(this,Cn,e),L(this,Cn)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,Ge).debug("Websocket was already connecting or connected.");return}if(L(this,Qi)!==!1)return new Promise((i,n)=>{De(this,_s,Co).call(this),De(this,Po,Wd).call(this);try{ue(this,Fe,new WebSocket(De(this,fh,py).call(this,L(this,hs)))),L(this,Fe).binaryType="arraybuffer",L(this,Ge).debug("Connecting");const r=setTimeout(()=>{L(this,Ge).debug("Connection timeout. Closing socket"),ue(this,Qi,!0),De(this,Po,Wd).call(this),L(this,Fe).close(3001,"Connection Timeout"),L(this,Ae).autoReconnect&&!L(this,fi)&&(L(this,tt).emit("reconnecting"),De(this,wo,cd).call(this)),n(new Error("Connection timed out!"))},L(this,Ae).connectionTimeout);L(this,Fe).onopen=()=>{L(this,Ge).debug(`Ready State: ${hy[L(this,Fe).readyState]}`),r&&clearTimeout(r),De(this,Bd,Eh).call(this),ue(this,On,{code:void 0,reason:void 0}),L(this,tt).emit("connected"),L(this,Ae).flushOnReconnect&&this.flush(),i()},L(this,Fe).onclose=s=>{try{r&&clearTimeout(r);const{code:o,reason:c}=s;n(c),L(this,Ge).debug("Socket closed. Close event:",{event:s}),L(this,Ge).debug(`Connection closed code: ${o}`),L(this,Ge).debug(`Connection closed reason: ${c}`),L(this,fi)||De(this,Ud,Sh).call(this,o,c)}catch(o){De(this,lo,od).call(this,o)}},L(this,Fe).onerror=s=>{De(this,lo,od).call(this,s)},L(this,Fe).onmessage=s=>De(this,vh,my).call(this,s)}catch(r){De(this,lo,od).call(this,r,n)}})})}send(e,i,n,r){const s={event:e,id:i,payload:n,metadata:r};if(L(this,Ae).queueOnDisconnect&&(!L(this,Fe)||L(this,Fe).readyState!==1))return L(this,Ge).debug("Queuing message since socket is not connected!",s),L(this,Cn).push(s),!1;const o=uy.encode(s);return De(this,Io,Fd).call(this,o)}emit(e,i,n,r){return this.send(e,i,n,r)}sendRaw(e){return De(this,Io,Fd).call(this,e)}receive(e,i){return L(this,tt).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")){L(this,tt).on(e,i);return}this.receive(e,i)}removeAllListeners(){L(this,tt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){L(this,tt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,tt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){ue(this,Qi,!1),De(this,_s,Co).call(this),this.removeAllListeners(),ue(this,On,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,Fe).close(1e3,"Sockrates disconnect method called.")}}Fe=new WeakMap,hs=new WeakMap,Ae=new WeakMap,Ge=new WeakMap,Cn=new WeakMap,tt=new WeakMap,Qi=new WeakMap,On=new WeakMap,fi=new WeakMap,ps=new WeakMap,Gi=new WeakMap,fh=new WeakSet,py=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)://.")},lo=new WeakSet,od=function(t,e){L(this,Ge).error("Error:",{error:t}),L(this,tt).emit("errored",{error:t}),e==null||e(t)},vh=new WeakSet,my=function(t){if(De(this,Bd,Eh).call(this),t.data===gO){L(this,Ge).debug("Received ping from server"),De(this,Io,Fd).call(this,fO);return}const e=uy.decode(t.data),{id:i,payload:n}=e;L(this,Ge).debug("Received message",{event:e.event,messageID:i}),L(this,tt).emit(e.event.toString(),{id:i,payload:n})},yh=new WeakSet,bg=function(){return L(this,Fe).readyState===1},Ud=new WeakSet,Sh=function(t,e){ue(this,On,{reason:e,code:t}),L(this,tt).emit("disconnected",{code:t,reason:e})},Th=new WeakSet,gy=function(){const{reason:t,code:e}=L(this,On);e&&e!==1e3&&L(this,Qi)&&L(this,Ae).autoReconnect&&!L(this,fi)&&(L(this,Ge).debug(`Triggering reconnection due to ${t}.`),L(this,tt).emit("reconnecting"),De(this,wo,cd).call(this))},wo=new WeakSet,cd=function(t=!0){return u(this,null,function*(){if(t&&L(this,fi)){L(this,Ge).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,fi)||L(this,Gi).reset(),L(this,Ae).maxReconnectionAttempts!==null&&L(this,Gi).getAttempts()>=L(this,Ae).maxReconnectionAttempts){L(this,tt).emit("failed"),ue(this,fi,!1);return}ue(this,fi,!0),De(this,Po,Wd).call(this),De(this,_s,Co).call(this);try{if(yield L(this,Gi).wait(),L(this,Qi)===!1)return;if(L(this,Ge).debug(`Reconnection attempt ${L(this,Gi).getAttempts()}`),L(this,tt).emit("reconnectAttempt",{attempt:L(this,Gi).getAttempts()}),yield this.connect(),!De(this,yh,bg).call(this))throw Error("Reconnect Failed");ue(this,fi,!1),ue(this,On,{code:void 0,reason:void 0}),L(this,tt).emit("reconnected")}catch{L(this,Ge).debug("Failed to reconnect."),L(this,tt).emit("reconnectFailure",{attempt:L(this,Gi).getAttempts()}),De(this,wo,cd).call(this,!1)}})},Io=new WeakSet,Fd=function(t){try{return L(this,Fe).send(t),!0}catch(e){return L(this,Ge).error(e.message),!1}},Bd=new WeakSet,Eh=function(){this.config.disconnectOnPingTimeout&&(L(this,Ge).debug("Resetting ping timeout"),De(this,_s,Co).call(this),ue(this,ps,setTimeout(()=>{var t;L(this,Ge).debug("Disconnecting the socket due to ping timeout"),ue(this,Qi,!0);const e=3002,i="Ping timeout";(t=L(this,Fe))==null||t.close(e,i),De(this,Ud,Sh).call(this,e,i)},L(this,Ae).pingTimeout)))},_s=new WeakSet,Co=function(){L(this,ps)&&(clearTimeout(L(this,ps)),ue(this,ps,void 0))},Po=new WeakSet,Wd=function(){L(this,Fe)&&(L(this,Fe).onopen=void 0,L(this,Fe).onerror=void 0,L(this,Fe).onmessage=void 0,L(this,Fe).onclose=void 0)};var yO=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,ol=(t,e,i,n)=>{for(var r=n>1?void 0:n?SO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&yO(e,i,r),r};const _g=65535,TO=3e3;var zn,xe,Ve,We,ci,pn,Ec,ru,kc,su,wg;const fy=(wg=class{constructor(t,{peerId:e,meetingId:i,authToken:n,capabilities:r}){f(this,Ve),f(this,Ec),f(this,kc),f(this,zn,void 0),f(this,xe,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),f(this,ci,void 0),f(this,pn,void 0);var s;if(!e||!i||!n)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,ci,void 0),v(this,pn,t),this.capabilities=r,this.roomName=i,this.authToken=n,v(this,zn,B(this,Ec,ru).call(this,e)),v(this,xe,new vO(a(this,zn),{autoReconnect:!0,disconnectOnPingTimeout:(s=r.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ve,We).socketJoinAttempted}set joinAttempted(t){a(this,Ve,We).socketJoinAttempted=t}get peerId(){return a(this,pn).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,zn,B(this,Ec,ru).call(this,t)),l.debug("SocketService:: Connection URL updated.")),a(this,xe).updateURL(a(this,zn))}static getSocketEdgeDomain(t){return Ts({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,zn)}connect(){return u(this,null,function*(){a(this,Ve,We).socketJoinAttempted=!0,yield a(this,xe).connect(),a(this,Ve,We).socketJoinAttempted=!0,a(this,Ve,We).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Ve,We).socketJoinAttempted=!1,a(this,xe).disconnect(),a(this,Ve,We).socketJoinAttempted=!0,a(this,Ve,We).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,xe).readyState===1}catch{return!1}}sendMessage(t,e,i){const n={};return S.injectContext(n),a(this,xe).send(t,i!=null?i:B(this,kc,su).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,i,n){const r=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:r,protobuf:e,messageId:i,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:n,resp:r}){const s=r!=null?r:t;return new Promise((o,c)=>{const d=(E,b)=>{a(this,xe).removeListener(s,E),a(this,xe).removeListener(_g,b),a(this,xe).removeListener(ti.errorResponse,b),a(this,xe).removeListener(vi.errorResponse,b)},h=n!=null?n:B(this,kc,su).call(this),p={};S.injectContext(p);const g=({id:E,payload:b})=>{if(h===E){let O;try{const M=SI.fromBinary(b);O=new Error(M.errorMessage)}catch(M){O=new Error("failed to parse error message",{cause:M});try{const V=TC.fromBinary(b);O=new Error(V.message)}catch(V){O=new Error("failed to parse error message",{cause:V})}}c(O),d(y,g)}},y=({id:E,payload:b})=>{h===E&&(o({id:E,payload:b}),d(y,g))};a(this,xe).on(s,y),a(this,xe).on(_g,g),a(this,xe).on(ti.errorResponse,g),a(this,xe).on(vi.errorResponse,g),setTimeout(()=>{d(y,g),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,xe).send(t,h,i,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){a(this,xe).on(t,e)}onStateEvent(t,e){a(this,xe).on(t,e)}removeListener(t,e){a(this,xe).removeListener(t,e)}removeListeners(t){a(this,xe).removeListeners(t)}flush(){return a(this,xe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),a(this,ci)&&(clearTimeout(a(this,ci)),v(this,ci,void 0)),a(this,Ve,We).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:n,send:r}=(i=a(this,Ve,We).mediaState)!=null?i:{};n!=null&&n.state&&(n==null?void 0:n.state)!==Ms.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Ms.CONNECTED?P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ve,We).joinAttempted}):v(this,ci,setTimeout(()=>{P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ve,We).joinAttempted}),v(this,ci,void 0)},TO)),a(this,Ve,We).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),a(this,Ve,We).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ve,We).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ve,We).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ve,We).mediaJoinAttempted}}),a(this,ci)&&(clearTimeout(a(this,ci)),v(this,ci,void 0)),P.emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ve,We).mediaJoinAttempted}),a(this,Ve,We).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),P.emit(R.SOCKET_SERVICE_FAILED),a(this,Ve,We).updateSocketConnectionState("failed")}))}},zn=new WeakMap,xe=new WeakMap,Ve=new WeakSet,We=function(){return a(this,pn).getValue("connectionHandler")},ci=new WeakMap,pn=new WeakMap,Ec=new WeakSet,ru=function(t){let e=fy.getSocketEdgeDomain(a(this,pn).getValue("baseURI"));typeof Ps(a(this,pn),"socket_server_base")=="string"&&(e=Ps(a(this,pn),"socket_server_base"));const i=`wss://${e}`,n=new URL(`${i}/ws`),r=this.peerId,s=$(x({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},r!==t&&{oldPeerID:r}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>_d[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{n.searchParams.append(o,c.toString())}),n.href},kc=new WeakSet,su=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},wg);let jo=fy;ol([S.trace("SocketService.connect")],jo.prototype,"connect",1);ol([S.trace("SocketService.disconnect")],jo.prototype,"disconnect",1);ol([S.trace("SocketService.sendMessagePromise")],jo.prototype,"sendMessagePromise",1);ol([S.trace("SocketService.sendMessagePromiseWithTimeout")],jo.prototype,"sendMessagePromiseWithTimeout",1);const lr=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const i=JC.fromBinary(t),n=i.meetings.map(r=>{var s;return{id:r.id,title:r.title,participants:(s=r.participants)!=null?s:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(e=i.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=SP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=lv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return gm.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return dP.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield lr.socketService.sendMessagePromise(W.getConnectedRoomsDump);return lr.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield lr.socketService.sendMessagePromise(W.createConnectedRooms,QC.toBinary({payloads:t}));return gm.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),i=yield lr.socketService.sendMessagePromise(W.deleteConnectedRooms,oP.toBinary({payloads:e}));return lr.handleConnectedRoomsDeletedRaw(i)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield lr.socketService.sendMessagePromise(W.movePeers,gP.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=lr;m(Ne,"socketService"),m(Ne,"currentMeetingId");var EO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,cl=(t,e,i,n)=>{for(var r=n>1?void 0:n?kO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&EO(e,i,r),r};const ms=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),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}static init(t){return u(this,null,function*(){var e,i;const{peerId:n,apiBase:r,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(P.reset(),Pd.cleanup(),ty(t),Re.isSupported()===!1)throw new w("Browser not supported","0010",!0);const h=AA(t,{authToken:s,baseURL:r,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",n),t.setValue("apiClient",h);const p=new p1;t.setValue("connectionHandler",p);const g=ms.createSocketService(t),y=g.connect(),E=h.getUserDetails(),b=h.getPlugins();let O=Le.HIVE,M,V="";try{yield ms.setupFlagsmith(t)}catch(re){l.error("Failed to setup flagsmith",{error:re})}try{yield y}catch(re){l.error("[Controller]: Failed to connect to socket server:",{error:re})}try{({sfu:O,meetingTitle:V}=yield h.getRoomNodeData()),M=yield E,l.info(`SFU ${O} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:O})}catch(re){l.error("Failed to get room metadata",{error:re})}const H=Q1.init(M.preset,!t.getValue("modules").theme),J=yD.init(t,H.viewType,M.preset.permissions),I=ms.setupControllers(g,t,M,b,V,H,J);i1(H)&&((e=ms.createRoomNodeClient(t,g).initializeConnection(M.participant.name,o,!1,J))==null||e.catch(re=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:re})})),S.location.country=(i=h.ipInfo)==null?void 0:i.country;const{controllers:ae}=yield I;return Z_(),new ms(r,ae)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:n,overrides:r,meetingId:s,organizationId:o}=t.getAllValues(),c=Q_(s),d=$(x({entity:Su.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Re.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=r==null?void 0:r.whitelabelled_flags_endpoint)==null||e?Ts({servicePrefix:"flags",baseURI:n}):"edge.api.flagsmith.com";yield Y.identify(`${Su.PEER}_${i}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,l),l.info("flagsmith::allFlags",{flags:JSON.stringify(Y.getAllFlags())},!0)}catch{l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,n,r,s,o){return u(this,null,function*(){var c,d,h;const p=e.getValue("modules"),{participant:g}=i,y=e.getValue("defaults"),{sfu:E}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:O}}=s;e.setValue("viewType",b),e.setValue("defaults",x({mediaConfiguration:{audio:{enableHighBitrate:(c=O.enableHighBitrate)!=null?c:!1,enableStereo:(d=O.enableStereo)!=null?d:!1}}},y)),e.setValue("maxPreferredStreams",Re.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let M,V,H,J,I,ae,re,ve;const Qe=new YD(t);Ne.socketService=t;const ct=new sl(t),Rt=new ii(t),A=new ZD(t),k=Pd.create(t,e),_=new eO(t),j=new zD(t),we=new br(t),pe=yield Wn.init(e,k,g,o,s),F=yield kv.init(e,pe.self,k,Qe,r);if(p.participant&&(ve=new sn(e,pe.self,k,E)),(h=p.e2ee)!=null&&h.enabled&&p.e2ee.manager.init(l,P),p.chat&&(V=yield Xi.init(e,Rt,we,pe.self,ve.participants)),p.internals&&(I=yield Jh.init()),p.livestream&&s.viewType===Vt.Livestream&&Y.hasFeature(ie.LIVESTREAM)&&(re=new Av(pe.self,j)),s.viewType!==Vt.Chat){if(p.poll&&(M=yield yv.init(e,pe.self,ct)),p.recording&&(ae=new Iv(e,pe.self,k)),p.stage&&(H=new bv(e,A,k,pe.self,ve.participants)),p.plugin){if(!ve)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const Be=yield n;J=yield Uo.init(e,Be,_,Rt,V==null?void 0:V.chat,pe.self,ve.participants,r)}if(p.pip){const Be=yield iw._init(e,pe.self);e.setValue("pip",Be)}}const C={storesManager:new sD(e,_),pollController:M,selfController:pe,metaController:F,chatController:V,stageController:H,pluginController:J,recordingController:ae,internalsController:I,livestreamController:re,participantController:ve};return{theme:s,permissions:o,controllers:C}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:n}=t.getAllValues(),{sfu:r}=n;return ey(t,r,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:n}=t.getAllValues(),r=["PING"];return new jo(t,{peerId:e,meetingId:i,authToken:n,capabilities:r})}};let Ho=ms;cl([S.trace("Controller.init")],Ho,"init",1);cl([S.trace("setupFlagsmith")],Ho,"setupFlagsmith",1);cl([S.trace("Controller.createRoomNodeClient")],Ho,"createRoomNodeClient",1);cl([S.trace("Controller.createSocketService")],Ho,"createSocketService",1);var bO=Object.defineProperty,_O=Object.getOwnPropertyDescriptor,wO=(t,e,i,n)=>{for(var r=n>1?void 0:n?_O(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&bO(e,i,r),r},dd,kh;class vy extends Kt{constructor(e,i){super(),f(this,dd,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),f(this,kh,void 0),v(this,kh,e),v(this,dd,i.self)}get supportsConnectedMeetings(){return a(this,dd).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}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 Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(r=>r.id)):Promise.resolve());return yield Promise.all(i),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n.map(s=>({id:s}))});return r.success&&this.moveSuccessHandler(e,i,n),r})}moveParticipantsWithCustomPreset(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n});return r.success&&this.moveSuccessHandler(e,i,n.map(s=>s.id)),r})}moveSuccessHandler(e,i,n){const r=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>r.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>r.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(i===s.id){const o=s.participants.concat(n.map(c=>r.get(c)));return $(x({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!n.includes(c.id));return $(x({},s),{participants:o})}return s})}}dd=new WeakMap,kh=new WeakMap;wO([Ut({maxInvocations:60,period:60})],vy.prototype,"getConnectedMeetings",1);var IO=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,sp=(t,e,i,n)=>{for(var r=n>1?void 0:n?CO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&IO(e,i,r),r},La,di,au,ou;const Pn=(au=class{constructor(t,e,i){m(this,"connectedMeetings"),f(this,La,void 0),f(this,di,void 0),f(this,ou,void 0),v(this,ou,t),v(this,La,i),this.connectedMeetings=new vy(t,e),this.setCurrentMeeting(e)}static init(t,e,i){return Pn.instance||(Pn.instance=new Pn(t,e,i)),Pn.instance.connectedMeetings.supportsConnectedMeetings&&(Pn.instance.setupEvents(),e.self.once("roomJoined",()=>Pn.instance.getConnectedMeetings())),Pn.instance}setCurrentMeeting(t){v(this,di,t),Ne.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(W.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(W.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(W.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(W.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(W.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var n,r,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.`);l.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,di).self.videoEnabled,audio:a(this,di).self.audioEnabled};try{a(this,di).self.cleanupEvents(),yield a(this,di).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(r=(n=a(this,di))==null?void 0:n.meta)==null?void 0:r.meetingId}`,{error:h})}Ne.socketService=void 0,l.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield yy.init($(x({},a(this,La)),{cachedUserDetails:null,defaults:$(x(x({},a(this,La).defaults),c),{mediaHandler:a(this,di).self}),authToken:e}));l.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:h}=a(this,di).self;d.self.setName(a(this,di).self.name),yield d.join(),h&&d.self.hide()}catch(h){l.error("ConnectedMeetingsController.joinRoom",{error:h})}return l.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),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.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 Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(n=>{i.set(n.id,n)}),e.forEach(n=>{i.has(n.id)?i.get(n.id).title=n.title:i.set(n.id,$(x({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.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})}},La=new WeakMap,di=new WeakMap,ou=new WeakMap,m(au,"instance"),au);let dl=Pn;sp([S.trace("ConnectedMeetingsController.getConnectedMeetings")],dl.prototype,"getConnectedMeetings",1);sp([S.trace("ConnectedMeetingsController.setupEvents")],dl.prototype,"setupEvents",1);sp([S.trace("ConnectedMeetingsController.switchMeeting")],dl.prototype,"switchMeeting",1);class PO{constructor(){m(this,"battery"),m(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(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 Ig=new PO;function RO(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:n,participantId:r}=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://api.${s}`;return{meetingId:i,orgId:n,participantId:r,baseURI:s,apiBase:o}}catch(i){throw l.error("constants::decodeAuthToken",{error:i,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var MO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,ll=(t,e,i,n)=>{for(var r=n>1?void 0:n?AO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&MO(e,i,r),r},st,bc,_c,cu,Cg,Pg;let Un=(Pg=class{constructor(t,e){f(this,cu),f(this,st,void 0),f(this,bc,void 0),f(this,_c,void 0),v(this,_c,t),v(this,st,e)}static init(t){return u(this,null,function*(){var e,i,n,r,s,o,c;K_(),Re.init();const d=(i=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?i:As();Ig.init();const{authToken:h,baseURI:p}=t,g=RO(h,p),{meetingId:y}=g,E=qd(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Un.setupContext(d,t,y,E);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=E.participantId,S.meetingMetadata.organizationId=E.orgId,S.init(b,(r=(n=t.modules)==null?void 0:n.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:$(x({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
23
- ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const O=yield Ho.init(b),M=new Un(b,O);return B(c=M,cu,Cg).call(c,t),M})}static setupContext(t,e,i,n){var r;const s=Tr.createContext(t,e),o=x(x({},j_),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",i),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(r=e.overrides)!=null?r:{}),s.setValue("env",H_({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",Si(e.cachedUserDetails)),s.setValue("sdkVersion","3.0.2-staging.6"),s}join(){return u(this,null,function*(){const{selfController:t}=a(this,st);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Ig.cleanup();const{selfController:e}=a(this,st);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,st).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,st).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,st).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,st).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,st).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,st).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,st).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,bc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,st).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,st).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,st).stageController)==null?void 0:t.stage}get stores(){return a(this,st).storesManager}get __internals__(){var t;return(t=a(this,st).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)})}},st=new WeakMap,bc=new WeakMap,_c=new WeakMap,cu=new WeakSet,Cg=function(t){v(this,bc,dl.init(a(this,_c),this,t))},Pg);ll([mt("0002"),Bn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Un.prototype,"join",1);ll([mt("0003")],Un.prototype,"leave",1);ll([mt("0001"),Bn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Un,"init",1);Un=ll([mt("0000")],Un);const yy=Un;exports.RTKSelfMedia=xv;exports.default=yy;
23
+ ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const O=yield Ho.init(b),M=new Un(b,O);return B(c=M,cu,Cg).call(c,t),M})}static setupContext(t,e,i,n){var r;const s=Tr.createContext(t,e),o=x(x({},j_),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",i),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(r=e.overrides)!=null?r:{}),s.setValue("env",H_({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",Si(e.cachedUserDetails)),s.setValue("sdkVersion","3.0.2-staging.7"),s}join(){return u(this,null,function*(){const{selfController:t}=a(this,st);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){Ig.cleanup();const{selfController:e}=a(this,st);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,st).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,st).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,st).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,st).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,st).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,st).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,st).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,bc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,st).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,st).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,st).stageController)==null?void 0:t.stage}get stores(){return a(this,st).storesManager}get __internals__(){var t;return(t=a(this,st).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)})}},st=new WeakMap,bc=new WeakMap,_c=new WeakMap,cu=new WeakSet,Cg=function(t){v(this,bc,dl.init(a(this,_c),this,t))},Pg);ll([mt("0002"),Bn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Un.prototype,"join",1);ll([mt("0003")],Un.prototype,"leave",1);ll([mt("0001"),Bn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Un,"init",1);Un=ll([mt("0000")],Un);const yy=Un;exports.RTKSelfMedia=xv;exports.default=yy;
package/dist/index.es.js CHANGED
@@ -29945,7 +29945,7 @@ let jr = (Sm = class {
29945
29945
  var c;
29946
29946
  const n = Fi.createContext(t, e), o = O(O({}, BP), e == null ? void 0 : e.modules);
29947
29947
  return 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", HP({ baseURI: i.baseURI })), n.setValue("defaults", e.defaults || { audio: true, video: true }), n.setValue("onError", e.onError || (() => {
29948
- })), n.setValue("cachedUserDetails", vs(e.cachedUserDetails)), n.setValue("sdkVersion", "3.0.2-staging.6"), n;
29948
+ })), n.setValue("cachedUserDetails", vs(e.cachedUserDetails)), n.setValue("sdkVersion", "3.0.2-staging.7"), n;
29949
29949
  }
29950
29950
  join() {
29951
29951
  return u(this, null, function* () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.0.2-staging.6",
3
+ "version": "1.0.2-staging.7",
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",