@cloudflare/realtimekit-react 1.2.0-staging.10 → 1.2.0-staging.11

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/index.cjs.js CHANGED
@@ -20,4 +20,4 @@ ${t}`}const sa={maxInvocations:5,period:1};function Bt(t,e){return function(r,i,
20
20
  maxEnergy: ${a(this,Es)}`),s===-1/0||r<1e-6?{energy:0,isVoice:!1}:((!a(this,Ni)||s<a(this,Ni))&&f(this,Ni,s),(!a(this,Es)||s>a(this,Es))&&f(this,Es,s),{energy:(s-a(this,Ni))/(a(this,Es)-a(this,Ni))*10||0,isVoice:i})},Rd=new WeakSet,xh=function(t){return t<5},Uh=new WeakSet,Ay=function(t=a(this,Jn)){var e;if(!a(this,jr)||!t){a(this,ji).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,jr)}`);return}const r={producerId:a(this,jr),energy:Math.round(t),silent:U(e=ol,Rd,xh).call(e,t)};f(this,Ho,r.silent),this.reportRequest(r)},vu=new WeakSet,Lg=function(t){const e=Math.log10(t);return Math.round(e)},g(Fh,Rd),g(Fh,vu);const C1=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const r=new window.MediaStreamTrackGenerator({kind:"audio"}),i=r.writable.getWriter(),s=48e3,n=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const p=new Float32Array(n*o),v=new window.AudioData({format:"f32",sampleRate:s,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:p});c+=n/s*1e6,yield i.ready,yield i.write(v)}catch{d&&clearInterval(d),i.releaseLock(),r.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([r]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),i.releaseLock(),r.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch{}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const r=new e;if(!r||r.state!=="running"||!r.destination)return;const i=r.createOscillator();i.frequency.value=0,i.type="sine";const s=r.createGain();s.gain.value=0,i.connect(s);const n=r.createMediaStreamDestination();s.connect(n),i.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch{return}},P1=(t=!1)=>{var e,r;const i=new MediaStream().getVideoTracks()[0],s=document.createElement("canvas");s.height=(e=i==null?void 0:i.getSettings().height)!=null?e:720,s.width=(r=i==null?void 0:i.getSettings().width)!=null?r:1280;const n=s.getContext("2d");n.fillStyle="black",n.fillRect(0,0,s.width,s.height),setInterval(()=>{n.fillStyle="black",n.fillRect(0,0,s.width,s.height)},1e3);const o=s.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var R1=Object.defineProperty,M1=Object.getOwnPropertyDescriptor,me=(t,e,r,i)=>{for(var s=i>1?void 0:i?M1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&R1(e,r,s),s};const qt=["video/VP9","video/VP8"];var Vc,Lc,St,J,eo,Kr,Dt,dn,ln,un,xc,mr,Ei,to,hn,pn,Ot,Gt,cs,mn,yu,xg,Su,Ug,Tu,Fg,Uc,Eu,ku,bu,Bg,wu,Wg,_u,jg,Iu,Hg,lt,Tt,gn,ro,Cu,qg,Pu,Gg,Ru,$g;const Dy=(bu=class{constructor(t,e,r){g(this,cs),g(this,yu),g(this,Su),g(this,Tu),g(this,Uc),g(this,wu),g(this,_u),g(this,Iu),g(this,lt),g(this,gn),g(this,Cu),g(this,Pu),g(this,Ru),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),g(this,Vc,void 0),g(this,Lc,void 0),g(this,St,void 0),g(this,J,void 0),g(this,eo,void 0),g(this,Kr,void 0),g(this,Dt,void 0),g(this,dn,void 0),g(this,ln,void 0),g(this,un,void 0),g(this,xc,void 0),g(this,mr,null),g(this,Ei,void 0),g(this,to,void 0),g(this,hn,void 0),g(this,pn,void 0),g(this,Ot,void 0),g(this,Gt,void 0);var i,s;this.context=t;const{socket:n}=r;this.mediaJoined=!1,f(this,hn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,pn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Kr,e),f(this,St,n),f(this,dn,!1),f(this,J,new b1(t,n,e)),f(this,Dt,a(this,J).events),f(this,Ei,new Set),f(this,Ot,new Map),f(this,ln,!1),f(this,un,new ch(t.getValue("logger"))),e===De.CF&&f(this,Gt,new Fh(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(s=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,xc,lp(()=>u(this,null,function*(){if(!a(this,cs,mn).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Lc),a(this,Vc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(M.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(M.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,cs,mn).mediaJoined}set mediaJoined(t){a(this,cs,mn).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Ot).clear(),a(this,Ei).clear(),f(this,mr,null),a(this,un).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,un,new ch)}joinRoom(t,e){return u(this,arguments,function*(r,i,s=!1,n=!1,o={}){a(this,cs,mn).mediaJoinAttempted=!0,f(this,dn,!0),s&&this.reset();try{return yield a(this,un).push(()=>U(this,yu,xg).call(this,r,i,n,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(M.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(r,i,s=!1,n={}){return a(this,mr)?a(this,mr):(f(this,mr,(()=>u(this,null,function*(){try{yield U(this,Uc,Eu).call(this,r,i,s,n)}catch(o){throw f(this,mr,null),o}}))()),a(this,mr))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){a(this,J).stopAllTransports(),f(this,ln,!1),a(this,cs,mn).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,St).sendMessagePromise(a(this,Dt).leaveRoom,CI.toBinary(t)).then(e=>{var r;(r=gC.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()})}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((r,i)=>{const s=a(this,J).producerIdToConsumerIdMap.get(i.producerId);return s?(r.push(s),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const r=e==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,i=U(this,lt,Tt).call(this,r);if(i){const h=yield i;if(a(this,J).producers.has(h)){const p=a(this,J).producers.get(h);if(!p.closed)return yield p.replaceTrack({track:t}),yield this.resumeWebcam(r),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const s=[e].concat(qt.filter(h=>h!==e)),n=U(this,Ru,$g).call(this,t,s),o=Zn(this.context,"disableSimulcast"),c=a(this,Kr)===De.CF?X.ENABLE_CF_SIMULCAST:X.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,Kr)}`),n.encodings=hO(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,Kr)}`),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ot).delete(r)},l=a(this,J).createProducer(n,d);return U(this,gn,ro).call(this,r,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const r=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(r)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${r}`),this._shareWebcam(t,r);const i=qt.filter(s=>{var n,o;return((o=(n=a(this,eo).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===s))>=0&&a(this,pn).get(s).size>0});return i.length===0&&i.push(qt[0]),yield Promise.all(i.map(s=>(this.logger.debug(`Calling _shareWebcam with video codec: ${s}`),this._shareWebcam(t,s)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},s=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(Se.SCREENSHARE_VIDEO),a(this,Ot).delete(Se.SCREENSHARE_AUDIO)},n=a(this,J).createProducer(i,s);U(this,gn,ro).call(this,Se.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(r){const c={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,Kr)!==De.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,gn,ro).call(this,Se.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new Ut("track undefined");const e=U(this,lt,Tt).call(this,Se.MIC);if(e){const n=yield e;if(a(this,J).producers.has(n)){const o=a(this,J).producers.get(n);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,Gt)&&(a(this,Gt).audioTrack=t,a(this,Gt).producerId=n,a(this,Gt).start());return}yield a(this,J).closeProducer(n,{stopTrack:!1})}yield this.shareMic(t);return}const r=U(this,Pu,Gg).call(this,t),i=()=>{a(this,Ot).delete(Se.MIC)},s=a(this,J).createProducer(r,i);U(this,gn,ro).call(this,Se.MIC,s.then(n=>n.id)),yield s.then(n=>{a(this,Gt)&&(a(this,Gt).audioTrack=n.track,a(this,Gt).producerId=n.id,a(this,Gt).start())})}catch(e){throw new C(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Tt).call(this,Se.MIC),r=a(this,J).producers.get(e);if(!r){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(r.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}r.pause(),(t=a(this,Gt))==null||t.stop();const i={producerId:r.id,pause:!0};a(this,St).sendMessage(a(this,Dt).toggleProducer,vc.toBinary(i))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,lt,Tt).call(this,Se.WEBCAM),e=yield U(this,lt,Tt).call(this,Se.WEBCAM_BACKUP),r=a(this,J).producers.get(t),i=a(this,J).producers.get(e);if(!r&&!i){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const s=n=>{const o={producerId:n.id,pause:!0};a(this,St).sendMessage(a(this,Dt).toggleProducer,vc.toBinary(o))};r&&(r.pause(),s(r)),i&&(i.pause(),s(i))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,lt,Tt).call(this,Se.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(M.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,St).sendMessage(a(this,Dt).toggleProducer,vc.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(t=Se.WEBCAM){const e=yield U(this,lt,Tt).call(this,t),r=a(this,J).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(M.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,St).sendMessage(a(this,Dt).toggleProducer,vc.toBinary(i))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,r=yield U(this,lt,Tt).call(this,e);U(this,Cu,qg).call(this,e),r&&(yield a(this,J).closeProducer(r))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Tt).call(this,Se.MIC);e&&(yield a(this,J).closeProducer(e)),(t=a(this,Gt))==null||t.stop(),a(this,Ot).delete(Se.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,lt,Tt).call(this,Se.SCREENSHARE_VIDEO),e=yield U(this,lt,Tt).call(this,Se.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,Ei).clear(),a(this,Ot).delete(Se.SCREENSHARE_VIDEO),a(this,Ot).delete(Se.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const r=yield U(this,lt,Tt).call(this,Se.WEBCAM),i=yield U(this,lt,Tt).call(this,Se.WEBCAM_BACKUP);yield a(this,J).closeProducer(r,{stopTrack:!1}),yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=yield U(this,lt,Tt).call(this,Se.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,St).sendMessagePromise(a(this,Dt).globalPinPeer,WI.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,Ei).add(t.consumerPeerId),a(this,Ei).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const r=t.map(i=>this.getConsumers().get(i));a(this,J).switchConsumersToLayer(r,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,St).on(a(this,Dt).peerProducerCreateBroadcast,({payload:t})=>{var e,r;if(this.mediaJoined)try{const{participantId:i,producerState:s}=GC.fromBinary(t);if(i===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===Hr.AUDIO?"audio/opus":"video/VP8"),s.kind===Hr.VIDEO&&!s.screenShare&&((r=(e=a(this,eo).receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(n=>n.mimeType===qt[0]))>=0&&a(this,hn).get(qt[0]).has(i)&&s.mimeType!==qt[0]){this.logger.warn(`Ignoring producer: ${s.producerId}`);return}this.logger.info(`producer created broadcast: ${i}, producer state: ${s}`),this.context.getValue("peerSessionStore").emit(M.NEW_PRODUCER,{peerId:i,producer:G(V({},s),{kind:s.kind===Hr.AUDIO?"audio":"video",producingPeerId:i})})}catch(i){this.logger.error("error in peer-producer-create-broadcast",{error:i})}}),a(this,St).on(a(this,Dt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:s,producerId:n}}=Om.fromBinary(t),o=i===Hr.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${n}, kind:${o}, paused:${s} payload: ${JSON.stringify(Om.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&s&&this.context.getValue("peerSessionStore").emit(o==="audio"?M.MUTE_SELF:M.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(M.PRODUCER_TOGGLE,{peerId:e,producerId:n,paused:s,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===n).forEach(c=>{c.paused!==s&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${s}`),s?(c.pause(),this.context.getValue("peerSessionStore").emit(M.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(M.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,St).on(a(this,Dt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Gu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Ei).delete(e),a(this,J).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(M.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,St).on(a(this,Dt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=KC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(M.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,J).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,J).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,J).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(M.CONSUMER_CLOSED,{id:i})}).catch(s=>{this.logger.error("error closing consumer",{error:s})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,St).on(a(this,Dt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,dn)&&!a(this,ln)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(M.ROOM_NODE_DISCONNECTED),a(this,xc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,J).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(M.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,J).producers.values()).find(s=>s.id===r);i&&this.context.getValue("peerSessionStore").emit(M.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var r,i,s,n;for(let o=0;o<=qt.length;o+=1){const c=qt[o];if(((i=(r=e==null?void 0:e.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(d=>d.mimeType===c))>=0||o===qt.length-1){a(this,pn).get(c).add(t);break}}for(let o=0;o<=qt.length;o+=1){const c=qt[o];if(((n=(s=e==null?void 0:e.sender)==null?void 0:s.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===qt.length-1){a(this,hn).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,hn).forEach(e=>e.delete(t)),a(this,pn).forEach((e,r)=>{e.delete(t),!(e.size!==0||r===qt[0])&&this.disableWebcam(r)}))}},Vc=new WeakMap,Lc=new WeakMap,St=new WeakMap,J=new WeakMap,eo=new WeakMap,Kr=new WeakMap,Dt=new WeakMap,dn=new WeakMap,ln=new WeakMap,un=new WeakMap,xc=new WeakMap,mr=new WeakMap,Ei=new WeakMap,to=new WeakMap,hn=new WeakMap,pn=new WeakMap,Ot=new WeakMap,Gt=new WeakMap,cs=new WeakSet,mn=function(){return this.context.getValue("connectionHandler")},yu=new WeakSet,xg=function(t,e,r,i){return u(this,null,function*(){f(this,Lc,t);try{return a(this,mr)?yield a(this,mr):yield U(this,Uc,Eu).call(this,t,e,r,i),U(this,Tu,Fg).call(this,e),{roomJoined:yield U(this,Su,Ug).call(this)}}catch(s){return this.logger.error("Failed to complete room join",{error:s}),{roomJoined:!1}}finally{f(this,mr,null)}})},Su=new WeakSet,Ug=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,Vc,t.roomUuid),f(this,ln,!0),f(this,dn,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},Tu=new WeakSet,Fg=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:G(V({},Ie.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(e)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Uc=new WeakSet,Eu=function(t,e,r,i){return u(this,null,function*(){var s,n;try{(n=a(this,to))!=null||f(this,to,U(s=Dy,ku,Bg).call(s));const o=U(this,wu,Wg).call(this);yield U(this,_u,jg).call(this,t,e,r,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,Iu,Hg).call(this,i)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},ku=new WeakSet,Bg=function(){const{ipInfo:t}=pt();if(!(t!=null&&t.loc))return;const[e,r]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:r}},wu=new WeakSet,Wg=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),r=l1(e);return f(this,eo,r),r},_u=new WeakSet,jg=function(t,e,r,i){return u(this,null,function*(){yield vy((s,n)=>u(this,null,function*(){if(!a(this,St).isConnected){n(new Error("Socket is not connected"));return}s>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${s}`});try{yield a(this,J).socketHandler.joinRoom(e,t,i,r,a(this,to))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},Iu=new WeakSet,Hg=function(t){return u(this,null,function*(){if(!(a(this,Kr)===De.HIVE||!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===q.Allowed&&e.push(this.shareWebcam(P1(!1))),t.canProduceAudio===q.Allowed){const r=C1(!1);r&&e.push(this.shareMic(r))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},lt=new WeakSet,Tt=function(t){return a(this,Ot).get(t)},gn=new WeakSet,ro=function(t,e){return a(this,Ot).set(t,e)},Cu=new WeakSet,qg=function(t){return a(this,Ot).delete(t)},Pu=new WeakSet,Gg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,Kr)!==De.CF}},Ru=new WeakSet,$g=function(t,e){return{track:t,codecOptions:e?e.map(r=>({name:r.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(bu,ku),bu);let le=Dy;me([E.trace("MediaNodeClient.reset",{country:E.location.country})],le.prototype,"reset",1);me([E.trace("MediaNodeClient.joinRoom")],le.prototype,"joinRoom",1);me([E.trace("MediaNodeClient.leaveRoom")],le.prototype,"leaveRoom",1);me([E.trace("MediaNodeClient.activatePeers")],le.prototype,"activatePeers",1);me([E.trace("MediaNodeClient.createConsumers")],le.prototype,"createConsumers",1);me([E.trace("MediaNodeClient.closeConsumers")],le.prototype,"closeConsumers",1);me([E.trace("MediaNodeClient._shareWebcam")],le.prototype,"_shareWebcam",1);me([E.trace("MediaNodeClient.shareWebcam")],le.prototype,"shareWebcam",1);me([E.trace("MediaNodeClient.shareScreen")],le.prototype,"shareScreen",1);me([E.trace("MediaNodeClient.shareMic")],le.prototype,"shareMic",1);me([E.trace("MediaNodeClient.pauseMic")],le.prototype,"pauseMic",1);me([E.trace("MediaNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1);me([E.trace("MediaNodeClient.resumeMic")],le.prototype,"resumeMic",1);me([E.trace("MediaNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1);me([E.trace("MediaNodeClient.disableWebcam")],le.prototype,"disableWebcam",1);me([E.trace("HiveClient.disableMic")],le.prototype,"disableMic",1);me([E.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1);me([E.trace("MediaNodeClient.muteSelf")],le.prototype,"muteSelf",1);me([E.trace("MediaNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1);me([E.trace("MediaNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1);me([E.trace("MediaNodeClient.kickPeer")],le.prototype,"kick",1);me([E.trace("MediaNodeClient.kickAllPeers")],le.prototype,"kickAll",1);me([E.trace("MediaNodeClient.muteAll")],le.prototype,"muteAll",1);me([E.trace("MediaNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1);me([E.trace("MediaNodeClient.disableAudio")],le.prototype,"disableAudio",1);me([E.trace("MediaNodeClient.disableVideo")],le.prototype,"disableVideo",1);me([E.trace("MediaNodeClient.pinPeer")],le.prototype,"pinPeer",1);me([E.trace("MediaNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);function Oy(t,e,r){const i=t.getValue("roomNodeClient");if(i){if(i)return i;throw new Error("Room node client already set up.")}const s=new le(t,e,r);return t.setValue("roomNodeClient",s),s}function Ny(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var A1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,$s=(t,e,r,i)=>{for(var s=i>1?void 0:i?D1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&A1(e,r,s),s},fn,Nr,ie,Nt,$t,Jg;const Vy=(Jg=class{constructor(t,e,r,i){g(this,Nt),m(this,"self"),m(this,"authToken"),g(this,fn,void 0),m(this,"viewType"),g(this,Nr,void 0),g(this,ie,void 0);const{socket:s}=r,n=t.getValue("authToken");this.self=e,f(this,ie,t),this.viewType=i,this.authToken=n,f(this,fn,s),f(this,Nr,r),e.config.viewType!==Ft.Chat&&this.setupEvents()}get peerId(){return a(this,ie).getValue("peerId")}get telemetry(){return a(this,ie).getValue("telemetry")}get logger(){return a(this,ie).getValue("logger")}get mediaJoined(){return a(this,ie).getValue("connectionHandler").mediaJoined}static init(t,e,r,i,s){return u(this,null,function*(){const n=pt(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield nt.__init__(t,r,i,s,s.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),t.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield n.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Ov(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Vy(t,d,e,s.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:i,audioEnabled:s,videoEnabled:n,screenShareEnabled:o,screenShareTracks:c}=this.self;if(i.canProduceAudio===q.Allowed&&s)try{yield a(this,Nt,$t).shareMic(e),this.self.audioEnabled||a(this,Nt,$t).pauseMic()}catch{this.self.disableAudio()}if(i.canProduceVideo===q.Allowed&&n)try{const d=yield a(this,Nt,$t).shareWebcam(r);d&&d.id!==r.id&&a(this,ie).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&(yield a(this,Nt,$t).shareWebcam(d)),this.self.videoEnabled||a(this,Nt,$t).pauseWebcam()}catch{this.self.disableVideo()}if(i.canProduceScreenshare===q.Allowed&&o)try{yield(t=a(this,Nt,$t))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch{this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){a(this,ie).getValue("callstats").callEnded(),a(this,Nt,$t).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,ie).getValue("peerSessionStore").on(M.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,ie).getValue("peerSessionStore").on(M.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ie).getValue("peerSessionStore").on(M.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ie).getValue("peerSessionStore").on(M.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ie).getValue("peerSessionStore").on(M.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,ie).getValue("peerSessionStore").on(M.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,ie).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(e=Ns()),a(this,fn).updateURL(e),a(this,ie).getValue("telemetry").resetPeerId(e),pt().setHeader("dyte-tracing-id",e),ci.remapContext(e,a(this,ie)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ie).getValue("peerSessionStore").on(M.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Nr).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Nr).on(Kc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,ie).getValue("peerSessionStore").emit(M.UPDATE_PERMISSIONS,e.patch)})}),a(this,Nr).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Nr).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Nr).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ie).getValue("peerSessionStore").onAsync(M.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ie).getValue("peerSessionStore").on(M.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:r,scoreStats:i})=>{var s;const n=(s=r==null?void 0:r.screenShare)!=null?s:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:n,score:t,participantId:this.self.id,scoreStats:i})}),a(this,ie).getValue("peerSessionStore").on(M.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,ie).getValue("callstats").audioOff())})),a(this,ie).getValue("peerSessionStore").on(M.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,ie).getValue("callstats").videoOff())})),a(this,ie).getValue("peerSessionStore").onAsync(M.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ie).getValue("peerSessionStore").on(M.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Nr).joinRoom(this.self);a(this,Nr).socket.flush();const r=gp(e.stageType);if(a(this,ie).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,ie).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,r;if(this.logger.info(`Leaving room with state: ${t}`),(e=a(this,ie).getValue("roomSocketHandler"))==null||e.cleanup(),t==="rejected"){this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,ie).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,ie).notify("stageStatus");try{(r=a(this,fn))==null||r.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}Ny(a(this,ie)),this.self.roomState=t,this.self.emit("roomLeft",{state:t}),this.logger.info(`roomLeft event emitted with state: ${t}`)})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:i,viewType:s,meetingId:n,stageStatus:o,roomNodeOptions:c}=a(this,ie).getAllValues(),{sfu:d}=c;try{if(s===Ft.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}Oy(a(this,ie),d,{socket:a(this,fn),peerId:i})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:p}=this.self.permissions,{roomJoined:v}=(r=yield(e=a(this,Nt,$t))==null?void 0:e.joinRoom(this.self.name,n,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:p}))!=null?r:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new C("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,ie).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Ft.Webinar)&&a(this,Nt,$t)&&(a(this,Nt,$t).mediaJoined&&t!=="disconnected"&&(yield a(this,Nt,$t).leaveRoom()),!(t==="stageLeft"&&e===Ft.Livestream)&&(a(this,Nt,$t).mediaJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},fn=new WeakMap,Nr=new WeakMap,ie=new WeakMap,Nt=new WeakSet,$t=function(){return a(this,ie).getValue("roomNodeClient")},Jg);let Qi=Vy;$s([E.trace("SelfController.resetSelf")],Qi.prototype,"resetSelf",1);$s([E.trace("SelfController.setupEvents")],Qi.prototype,"setupEvents",1);$s([E.trace("SelfController.joinRoom")],Qi.prototype,"joinRoom",1);$s([E.trace("SelfController.leaveRoom")],Qi.prototype,"leaveRoom",1);$s([E.trace("SelfController.joinMediaRoom")],Qi.prototype,"joinMediaRoom",1);$s([E.trace("SelfController.leaveMediaRoom")],Qi.prototype,"leaveMediaRoom",1);$s([E.trace("SelfController.init")],Qi,"init",1);var Md;class O1{constructor(e){g(this,Md,void 0),f(this,Md,e)}on(e,r){let i;e===F.roomPeerCount?i=Lm.fromBinary.bind(Lm):i=Jm.fromBinary.bind(Jm),a(this,Md).on(e,({payload:s})=>{if(e===F.roomPeerCount&&!s)return;const n=i(s);r(n)})}}Md=new WeakMap;var Ad,Dd;class N1{constructor(e,r){g(this,Ad,void 0),g(this,Dd,void 0),f(this,Ad,r),f(this,Dd,e)}get logger(){return a(this,Dd).getValue("logger")}on(e,r){let i,s;switch(e){case F.transcript:{i=Jl.fromBinary.bind(Jl),s=Jl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Ad).on(e,({payload:n})=>{let o=s;try{o=i(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}}Ad=new WeakMap,Dd=new WeakMap;var V1=Object.defineProperty,L1=Object.getOwnPropertyDescriptor,Cp=(t,e,r,i)=>{for(var s=i>1?void 0:i?L1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&V1(e,r,s),s},Vi,Ro;class Al{constructor(e,r){g(this,Vi,void 0),g(this,Ro,void 0),f(this,Vi,r),f(this,Ro,e)}get logger(){return a(this,Ro).getValue("logger")}get telemetry(){return a(this,Ro).getValue("telemetry")}getPolls(){return a(this,Vi).sendMessagePromise(ri.getPolls)}createPoll(e,r,i=!1,s=!1){const n={anonymous:i,hideVotes:s,question:e,options:r};return a(this,Vi).sendMessage(ri.createPoll,LA.toBinary(n))}votePoll(e,r){const i={index:r,pollId:e};return a(this,Vi).sendMessage(ri.votePoll,UA.toBinary(i))}on(e,r){let i,s;switch(e){case ri.updatePoll:case ri.createPoll:case ri.votePoll:{i=Zl.fromBinary.bind(Zl),s=Zl.create();break}}a(this,Vi).on(e,({payload:n})=>{let o=s;try{o=i(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}removeListeners(e){a(this,Vi).removeListeners(e)}}Vi=new WeakMap,Ro=new WeakMap;Cp([E.trace("PollSocketHandler.getPolls")],Al.prototype,"getPolls",1);Cp([E.trace("PollSocketHandler.createPoll")],Al.prototype,"createPoll",1);Cp([E.trace("PollSocketHandler.votePoll")],Al.prototype,"votePoll",1);var x1=Object.defineProperty,U1=Object.getOwnPropertyDescriptor,F1=(t,e,r,i)=>{for(var s=i>1?void 0:i?U1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&x1(e,r,s),s},ar;class Ly{constructor(e,r){m(this,"socket"),g(this,ar,void 0),f(this,ar,e),this.socket=r,this.handleSocketEvents(),a(this,ar).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ar).getValue("telemetry")}get logger(){return a(this,ar).getValue("logger")}cleanup(){var e;try{(e=this.socket)==null||e.disconnect()}catch{this.logger.error("roomSocketHandler::cleanup")}}joinRoom(e){return u(this,null,function*(){var r;this.socket.joinAttempted=!0;const i={capabilities:[],peer:{displayName:(r=e.name)!=null?r:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},s=this.socket.sendMessagePromise(F.joinRoom,bP.toBinary(i));try{const{peer:n}=Sn.fromBinary((yield s).payload);a(this,ar).getValue("connectionHandler").socketJoined=!0,a(this,ar).getValue("peerSessionStore").emit(M.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,ar).getValue("peerSessionStore").emit(M.ROOM_STATE,d),a(this,ar).getValue("peerSessionStore").emit(M.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return oR.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var r=e,{id:i}=r,s=fl(r,["id"]);return G(V({},s),{userId:i})})}catch{return[]}})}getRoomPeers(e,r,i){return u(this,null,function*(){let s;try{const n={seachQuery:e,limit:r,offset:i},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,pP.toBinary(n));s=Kl.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return s})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=Kl.fromBinary(r.payload)}catch(r){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:r})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=Kl.fromBinary(r.payload)}catch(r){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:r})}return e})}getPeerInfo(e){return u(this,null,function*(){let r;try{const i=yield this.socket.sendMessagePromise(F.getPeerInfo,qv.toBinary({peerId:e}));r=Sn.fromBinary(i.payload)}catch(i){this.logger.error("getPeerInfo::binary_decode_error",{error:i})}return r})}getRoomState(){return u(this,null,function*(){let e=xm.create();try{const r=yield this.socket.sendMessagePromise(F.getRoomInfo);e=xm.fromBinary(r.payload)}catch(r){this.logger.error("getRoomState::binary_decode_error",{error:r})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Wm.create();try{const r=yield this.socket.sendMessagePromise(F.getRoomStageState);e=Wm.fromBinary(r.payload)}catch(r){this.logger.error("getRoomStageState::binary_decode_error",{error:r})}return e})}broadcastMessage(e,r){return u(this,null,function*(){const i={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,ba.toBinary(i))})}broadcastToMeetings(e,r,i){return u(this,null,function*(){const s={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:r,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,ba.toBinary(s))})}broadcastToPeers(e,r,i){return u(this,null,function*(){const s={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:r,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,ba.toBinary(s))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,_P.toBinary({}))})}kick(e){return u(this,null,function*(){const r={peerIds:[e]};this.socket.sendMessage(F.kick,$v.toBinary(r))})}kickAll(e=!1){return u(this,null,function*(){const r={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,Wv.toBinary(r))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const r={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,pR.toBinary(r))}rejectWaitingRoomRequest(e){const r={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,gR.toBinary(r))}updatePermissions(e,r){return u(this,null,function*(){const i={updatePeersPresets:[]};return e.forEach(s=>{i.updatePeersPresets.push({userIds:s,patch:r})}),this.socket.sendMessagePromise(Kc.updateUserPreset,qR.toBinary(i))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const r=ba.fromBinary(e);a(this,ar).getValue("peerSessionStore").emit(M.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(r.payload)),type:r.type,timestamp:r.timestamp})}catch(r){this.logger.error("failed to decode broadcast message:",r)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const r=ba.fromBinary(e);a(this,ar).getValue("peerSessionStore").emit(M.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(r.payload)),type:r.type,timestamp:r.timestamp})}catch(r){this.logger.error("failed to decode peer broadcast message:",r)}})}on(e,r){let i,s;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{i=Sn.fromBinary.bind(Sn),s=Sn.create();break}case F.getWaitingRoomRequests:{i=(n,o)=>n?Bm.fromBinary(n,o):{requests:[]},s=Bm.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{i=Ym.fromBinary.bind(Ym);break}case Kc.updateUserPreset:{i=jm.fromBinary.bind(jm);break}case wr.peerJoinedBroadcast:case cr.peerJoinedBroadcast:{i=Am.fromBinary.bind(Am);break}case wr.selfJoinComplete:case cr.selfJoinComplete:{i=qu.fromBinary.bind(qu);break}case wr.globalPeerPinBroadcast:case cr.globalPeerPinBroadcast:{i=Nm.fromBinary.bind(Nm);break}case wr.selectedPeer:case cr.selectedPeer:{i=Hu.fromBinary.bind(Hu);break}case wr.selectedPeerDiff:case cr.selectedPeerDiff:{i=Mm.fromBinary.bind(Mm);break}case wr.leaveRoom:case cr.leaveRoom:{i=Gu.fromBinary.bind(Gu);break}}this.socket.on(e,({payload:n})=>{let o=s;if(!i)return r(void 0);try{o=i(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}getUserPermissions(e){return u(this,null,function*(){const r={userIds:[e]};try{const i=yield this.socket.sendMessagePromise(Kc.getUserPresets,xR.toBinary(r)),s=WR.fromBinary(i.payload).peerPresets[0],n=new TextDecoder().decode(s.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(i){throw this.logger.error("Error in getting user preset",{error:i}),i}})}}ar=new WeakMap;F1([E.trace("RoomSocketHandler.joinRoom")],Ly.prototype,"joinRoom",1);var zt;class B1{constructor(e){g(this,zt,void 0),f(this,zt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,zt).sendMessagePromise(F.getStageRequests);return e?Xl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,zt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,zt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};a(this,zt).sendMessage(F.grantStageAccess,IA.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};a(this,zt).sendMessage(F.denyStageAccess,PA.toBinary(r))})}joinStage(){return a(this,zt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return a(this,zt).sendMessagePromise(F.leaveStage,zm.toBinary(r),void 0,F.peerStageStatusUpdate)}kick(e){const r={userIds:e};return a(this,zt).sendMessagePromise(F.leaveStage,zm.toBinary(r))}on(e,r){let i;switch(e){case F.grantStageAccess:case F.denyStageAccess:{i=void 0;break}case F.getStagePeers:{i=Km.fromBinary.bind(Km);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{i=Xl.fromBinary.bind(Xl);break}case F.peerStageStatusUpdate:{i=Vm.fromBinary.bind(Vm);break}}a(this,zt).on(e,({payload:s,id:n})=>{if(!s||!i)return r(void 0,n);const o=i(s);return r(o,n)})}getPeerInfo(e){return u(this,null,function*(){const r=yield a(this,zt).sendMessagePromise(F.getPeerInfo,qv.toBinary({peerId:e}));return Sn.fromBinary(r.payload)})}}zt=new WeakMap;var rt,Od;class W1{constructor(e,r){g(this,rt,void 0),g(this,Od,void 0),f(this,rt,r),f(this,Od,e)}get logger(){return a(this,Od).getValue("logger")}addPlugin(e,r){a(this,rt).sendMessage($.addPlugin,HM.toBinary({pluginId:e,staggered:r}))}removePlugin(e){a(this,rt).sendMessage($.removePlugin,GM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,rt).sendMessagePromise($.getPlugins);return e?mA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,i){const s={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,rt).sendMessage($.customPluginEventToRoom,tA.toBinary(s),i)}customPluginEventToPeers(e,r,i,s){const n={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,rt).sendMessage($.customPluginEventToPeers,iA.toBinary(n),s)}enablePluginForRoom(e,r){a(this,rt).sendMessage($.enablePluginForRoom,JM.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,i){a(this,rt).sendMessage($.enablePluginForPeers,QM.toBinary({pluginId:e,peerIds:r}),i)}disablePluginForRoom(e,r){a(this,rt).sendMessage($.disablePluginForRoom,zM.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,i){a(this,rt).sendMessage($.disablePluginForPeers,ZM.toBinary({pluginId:e,peerIds:r}),i)}storeInsertKeys(e,r,i,s){const n={pluginId:e,storeName:r,insertKeys:i.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,rt).sendMessage($.storeInsertKeys,Hm.toBinary(n),s)}storeGetKeys(e,r,i,s){const n={pluginId:e,storeName:r,getKeys:i.map(o=>({storeKey:o.key}))};a(this,rt).sendMessage($.storeGetKeys,oA.toBinary(n),s)}storeDeleteKeys(e,r,i,s){const n={pluginId:e,storeName:r,deleteKeys:i.map(o=>({storeKey:o.key}))};a(this,rt).sendMessage($.storeDeleteKeys,dA.toBinary(n),s)}storeDelete(e,r,i){a(this,rt).sendMessage($.storeDelete,uA.toBinary({pluginId:e,storeName:r}),i)}getPluginDataOld(e,r){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,i){const s={pluginId:e,storeName:r,insertKeys:[{storeKey:i.key,payload:new TextEncoder().encode(JSON.stringify(i))}]};a(this,rt).sendMessage($.storeInsertKeys,Hm.toBinary(s))}on(e,r){let i;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{i=zu.fromBinary.bind(zu);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{i=qm.fromBinary.bind(qm);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{i=$m.fromBinary.bind($m);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{i=Gm.fromBinary.bind(Gm);break}}a(this,rt).on(e,({payload:s,id:n})=>{const o=i(s);return r(o,n)})}}rt=new WeakMap,Od=new WeakMap;var j1=Object.defineProperty,H1=(t,e,r)=>e in t?j1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,q1=(t,e,r)=>(H1(t,typeof e!="symbol"?e+"":e,r),r),Pp=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},N=(t,e,r)=>(Pp(t,e,"read from private field"),r?r.call(t):e.get(t)),we=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},de=(t,e,r,i)=>(Pp(t,e,"write to private field"),i?i.call(t,r):e.set(t,r),r),Re=(t,e,r)=>(Pp(t,e,"access private method"),r),cl={},G1={get exports(){return cl},set exports(t){cl=t}},Kn=typeof Reflect=="object"?Reflect:null,Kg=Kn&&typeof Kn.apply=="function"?Kn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Nd;Kn&&typeof Kn.ownKeys=="function"?Nd=Kn.ownKeys:Object.getOwnPropertySymbols?Nd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Nd=function(t){return Object.getOwnPropertyNames(t)};function $1(t){console&&console.warn&&console.warn(t)}var xy=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}G1.exports=pe;cl.once=Y1;pe.EventEmitter=pe;pe.prototype._events=void 0;pe.prototype._eventsCount=0;pe.prototype._maxListeners=void 0;var zg=10;function Dl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return zg},set:function(t){if(typeof t!="number"||t<0||xy(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");zg=t}});pe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||xy(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 Uy(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return Uy(this)};pe.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var n;if(e.length>0&&(n=e[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")Kg(c,this,e);else for(var d=c.length,l=Hy(c,d),r=0;r<d;++r)Kg(l[r],this,e);return!0};function Fy(t,e,r,i){var s,n,o;if(Dl(r),n=t._events,n===void 0?(n=t._events=Object.create(null),t._eventsCount=0):(n.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),n=t._events),o=n[e]),o===void 0)o=n[e]=r,++t._eventsCount;else if(typeof o=="function"?o=n[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),s=Uy(t),s>0&&o.length>s&&!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,$1(c)}return t}pe.prototype.addListener=function(t,e){return Fy(this,t,e,!1)};pe.prototype.on=pe.prototype.addListener;pe.prototype.prependListener=function(t,e){return Fy(this,t,e,!0)};function J1(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function By(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},s=J1.bind(i);return s.listener=r,i.wrapFn=s,s}pe.prototype.once=function(t,e){return Dl(e),this.on(t,By(this,t,e)),this};pe.prototype.prependOnceListener=function(t,e){return Dl(e),this.prependListener(t,By(this,t,e)),this};pe.prototype.removeListener=function(t,e){var r,i,s,n,o;if(Dl(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(s=-1,n=r.length-1;n>=0;n--)if(r[n]===e||r[n].listener===e){o=r[n].listener,s=n;break}if(s<0)return this;s===0?r.shift():K1(r,s),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};pe.prototype.off=pe.prototype.removeListener;pe.prototype.removeAllListeners=function(t){var e,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var s=Object.keys(r),n;for(i=0;i<s.length;++i)n=s[i],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Wy(t,e,r){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?r?[s.listener||s]:[s]:r?z1(s):Hy(s,s.length)}pe.prototype.listeners=function(t){return Wy(this,t,!0)};pe.prototype.rawListeners=function(t){return Wy(this,t,!1)};pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):jy.call(t,e)};pe.prototype.listenerCount=jy;function jy(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}pe.prototype.eventNames=function(){return this._eventsCount>0?Nd(this._events):[]};function Hy(t,e){for(var r=new Array(e),i=0;i<e;++i)r[i]=t[i];return r}function K1(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function z1(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Y1(t,e){return new Promise(function(r,i){function s(o){t.removeListener(e,n),i(o)}function n(){typeof t.removeListener=="function"&&t.removeListener("error",s),r([].slice.call(arguments))}qy(t,e,n,{once:!0}),e!=="error"&&Q1(t,s,{once:!0})})}function Q1(t,e,r){typeof t.on=="function"&&qy(t,"error",e,r)}function qy(t,e,r,i){if(typeof t.on=="function")i.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(n){i.once&&t.removeEventListener(e,s),r(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class X1 extends y{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const Yg=new X1;class Gy{static encode(e){return Yg.toBinary(e)}static decode(e){return Yg.fromBinary(new Uint8Array(e))}}function Z1(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Li;class eN{constructor(e={}){q1(this,"opts"),we(this,Li,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,Li,0)}wait(){return u(this,null,function*(){de(this,Li,N(this,Li)+1);const e=Z1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*cT(2,N(this,Li))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return N(this,Li)}reset(){de(this,Li,0)}}Li=new WeakMap;const ki={debug:0,info:1,warn:2,error:3};var ks,bs;class tN{constructor(e){we(this,ks,void 0),we(this,bs,void 0),de(this,ks,console),de(this,bs,e)}debug(...e){ki[N(this,bs)]>ki.debug||N(this,ks).debug("[Sockrates]:",...e)}info(...e){ki[N(this,bs)]>ki.info||N(this,ks).info("[Sockrates]:",...e)}warn(...e){ki[N(this,bs)]>ki.warn||N(this,ks).warn("[Sockrates]:",...e)}error(...e){ki[N(this,bs)]>ki.error||N(this,ks).error("[Sockrates]:",...e)}}ks=new WeakMap,bs=new WeakMap;var $y=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))($y||{});const rN="2",iN="3";var Le,Vn,Pe,je,xi,it,oi,qi,br,Ln,ti,Bh,Jy,Mo,Vd,Wh,Ky,jh,Qg,dl,Hh,qh,zy,qo,Ld,Go,ll,ul,Gh,zn,$o,Jo,hl;class sN{constructor(e,r){var i;we(this,Bh),we(this,Mo),we(this,Wh),we(this,jh),we(this,dl),we(this,qh),we(this,qo),we(this,Go),we(this,ul),we(this,zn),we(this,Jo),we(this,Le,void 0),we(this,Vn,void 0),we(this,Pe,void 0),we(this,je,void 0),we(this,xi,void 0),we(this,it,void 0),we(this,oi,void 0),we(this,qi,void 0),we(this,br,void 0),we(this,Ln,void 0),we(this,ti,void 0);var s,n,o,c,d,l,h,p,v;de(this,Vn,e),de(this,xi,[]),de(this,it,new cl),de(this,oi,!0),de(this,br,!1),de(this,Pe,r!=null?r:{}),(s=N(this,Pe)).autoReconnect!=null||(s.autoReconnect=!0),(n=N(this,Pe)).retryConnectionInterval!=null||(n.retryConnectionInterval=1e3),(o=N(this,Pe)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Pe)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Pe)).debug!=null||(d.debug=!0),(l=N(this,Pe)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Pe)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=N(this,Pe)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(v=N(this,Pe)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,qi,{code:void 0,reason:void 0}),de(this,je,(i=N(this,Pe).logger)!=null?i:new tN(N(this,Pe).debug?"debug":"info")),de(this,ti,new eN)}get readyState(){var e;return(e=N(this,Le))==null?void 0:e.readyState}get url(){return N(this,Vn)}updateURL(e){de(this,Vn,e),Re(this,qh,zy).call(this)}get config(){return N(this,Pe)}get sendQueue(){return N(this,xi)}flush(){if(!N(this,Pe).queueOnDisconnect)return!1;const e=[];return N(this,xi).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),de(this,xi,e),N(this,xi)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,je).debug("Websocket was already connecting or connected.");return}if(N(this,oi)!==!1)return new Promise((r,i)=>{Re(this,zn,$o).call(this),Re(this,Jo,hl).call(this);try{de(this,Le,new WebSocket(Re(this,Bh,Jy).call(this,N(this,Vn)))),N(this,Le).binaryType="arraybuffer",N(this,je).debug("Connecting");const s=setTimeout(()=>{N(this,je).debug("Connection timeout. Closing socket"),de(this,oi,!0),Re(this,Jo,hl).call(this),N(this,Le).close(3001,"Connection Timeout"),N(this,Pe).autoReconnect&&!N(this,br)&&(N(this,it).emit("reconnecting"),Re(this,qo,Ld).call(this)),i(new Error("Connection timed out!"))},N(this,Pe).connectionTimeout);N(this,Le).onopen=()=>{N(this,je).debug(`Ready State: ${$y[N(this,Le).readyState]}`),s&&clearTimeout(s),Re(this,ul,Gh).call(this),de(this,qi,{code:void 0,reason:void 0}),N(this,it).emit("connected"),N(this,Pe).flushOnReconnect&&this.flush(),r()},N(this,Le).onclose=n=>{try{s&&clearTimeout(s);const{code:o,reason:c}=n;i(c),N(this,je).debug("Socket closed. Close event:",{event:n}),N(this,je).debug(`Connection closed code: ${o}`),N(this,je).debug(`Connection closed reason: ${c}`),N(this,br)||Re(this,dl,Hh).call(this,o,c)}catch(o){Re(this,Mo,Vd).call(this,o)}},N(this,Le).onerror=n=>{Re(this,Mo,Vd).call(this,n)},N(this,Le).onmessage=n=>Re(this,Wh,Ky).call(this,n)}catch(s){Re(this,Mo,Vd).call(this,s,i)}})})}send(e,r,i,s){const n={event:e,id:r,payload:i,metadata:s};if(N(this,Pe).queueOnDisconnect&&(!N(this,Le)||N(this,Le).readyState!==1))return N(this,je).debug("Queuing message since socket is not connected!",n),N(this,xi).push(n),!1;const o=Gy.encode(n);return Re(this,Go,ll).call(this,o)}emit(e,r,i,s){return this.send(e,r,i,s)}sendRaw(e){return Re(this,Go,ll).call(this,e)}receive(e,r){return N(this,it).on(e.toString(),r)}on(e,r){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,it).on(e,r);return}this.receive(e,r)}removeAllListeners(){N(this,it).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){N(this,it).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,it).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){de(this,oi,!1),Re(this,zn,$o).call(this),this.removeAllListeners(),de(this,qi,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Le).close(1e3,"Sockrates disconnect method called.")}}Le=new WeakMap,Vn=new WeakMap,Pe=new WeakMap,je=new WeakMap,xi=new WeakMap,it=new WeakMap,oi=new WeakMap,qi=new WeakMap,br=new WeakMap,Ln=new WeakMap,ti=new WeakMap,Bh=new WeakSet,Jy=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)://.")},Mo=new WeakSet,Vd=function(t,e){N(this,je).error("Error:",{error:t}),N(this,it).emit("errored",{error:t}),e==null||e(t)},Wh=new WeakSet,Ky=function(t){if(Re(this,ul,Gh).call(this),t.data===rN){N(this,je).debug("Received ping from server"),Re(this,Go,ll).call(this,iN);return}const e=Gy.decode(t.data),{id:r,payload:i}=e;N(this,je).debug("Received message",{event:e.event,messageID:r}),N(this,it).emit(e.event.toString(),{id:r,payload:i})},jh=new WeakSet,Qg=function(){return N(this,Le).readyState===1},dl=new WeakSet,Hh=function(t,e){de(this,qi,{reason:e,code:t}),N(this,it).emit("disconnected",{code:t,reason:e})},qh=new WeakSet,zy=function(){const{reason:t,code:e}=N(this,qi);e&&e!==1e3&&N(this,oi)&&N(this,Pe).autoReconnect&&!N(this,br)&&(N(this,je).debug(`Triggering reconnection due to ${t}.`),N(this,it).emit("reconnecting"),Re(this,qo,Ld).call(this))},qo=new WeakSet,Ld=function(t=!0){return u(this,null,function*(){if(t&&N(this,br)){N(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,br)||N(this,ti).reset(),N(this,Pe).maxReconnectionAttempts!==null&&N(this,ti).getAttempts()>=N(this,Pe).maxReconnectionAttempts){N(this,it).emit("failed"),de(this,br,!1);return}de(this,br,!0),Re(this,Jo,hl).call(this),Re(this,zn,$o).call(this);try{if(yield N(this,ti).wait(),N(this,oi)===!1)return;if(N(this,je).debug(`Reconnection attempt ${N(this,ti).getAttempts()}`),N(this,it).emit("reconnectAttempt",{attempt:N(this,ti).getAttempts()}),yield this.connect(),!Re(this,jh,Qg).call(this))throw Error("Reconnect Failed");de(this,br,!1),de(this,qi,{code:void 0,reason:void 0}),N(this,it).emit("reconnected")}catch{N(this,je).debug("Failed to reconnect."),N(this,it).emit("reconnectFailure",{attempt:N(this,ti).getAttempts()}),Re(this,qo,Ld).call(this,!1)}})},Go=new WeakSet,ll=function(t){try{return N(this,Le).send(t),!0}catch(e){return N(this,je).error(e.message),!1}},ul=new WeakSet,Gh=function(){this.config.disconnectOnPingTimeout&&(N(this,je).debug("Resetting ping timeout"),Re(this,zn,$o).call(this),de(this,Ln,setTimeout(()=>{var t;N(this,je).debug("Disconnecting the socket due to ping timeout"),de(this,oi,!0);const e=3002,r="Ping timeout";(t=N(this,Le))==null||t.close(e,r),Re(this,dl,Hh).call(this,e,r)},N(this,Pe).pingTimeout)))},zn=new WeakSet,$o=function(){N(this,Ln)&&(clearTimeout(N(this,Ln)),de(this,Ln,void 0))},Jo=new WeakSet,hl=function(){N(this,Le)&&(N(this,Le).onopen=void 0,N(this,Le).onerror=void 0,N(this,Le).onmessage=void 0,N(this,Le).onclose=void 0)};var nN=Object.defineProperty,aN=Object.getOwnPropertyDescriptor,Ol=(t,e,r,i)=>{for(var s=i>1?void 0:i?aN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&nN(e,r,s),s};const Xg=65535,oN=3e3;var ds,Oe,Ne,xe,gr,ut,Fc,Mu,Bc,Au,Zg;const Yy=(Zg=class{constructor(t,{peerId:e,meetingId:r,authToken:i,capabilities:s}){g(this,Ne),g(this,Fc),g(this,Bc),g(this,ds,void 0),g(this,Oe,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),g(this,gr,void 0),g(this,ut,void 0);var n;if(!e||!r||!i)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,gr,void 0),f(this,ut,t),this.capabilities=s,this.roomName=r,this.authToken=i,f(this,ds,U(this,Fc,Mu).call(this,e)),f(this,Oe,new sN(a(this,ds),{autoReconnect:!0,disconnectOnPingTimeout:(n=s.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ne,xe).socketJoinAttempted}set joinAttempted(t){a(this,Ne,xe).socketJoinAttempted=t}get telemetry(){return a(this,ut).getValue("telemetry")}get logger(){return a(this,ut).getValue("logger")}get peerId(){return a(this,ut).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,ds,U(this,Fc,Mu).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Oe).updateURL(a(this,ds))}static getSocketEdgeDomain(t){return Ds({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,ds)}connect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!0,yield a(this,Oe).connect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){a(this,Ne,xe).socketJoinAttempted=!1,a(this,Oe).disconnect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Oe).readyState===1}catch{return!1}}sendMessage(t,e,r){const i={};return a(this,ut).getValue("telemetry").injectContext(i),a(this,Oe).send(t,r!=null?r:U(this,Bc,Au).call(this),e,new TextEncoder().encode(JSON.stringify(i)))}sendMessagePromise(t,e,r,i){const s=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:s,protobuf:e,messageId:r,resp:i})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:i,resp:s}){const n=s!=null?s:t;return new Promise((o,c)=>{const d=(T,k)=>{a(this,Oe).removeListener(n,T),a(this,Oe).removeListener(Xg,k),a(this,Oe).removeListener(cr.errorResponse,k),a(this,Oe).removeListener(wr.errorResponse,k)},l=i!=null?i:U(this,Bc,Au).call(this),h={};a(this,ut).getValue("telemetry").injectContext(h);const p=({id:T,payload:k})=>{if(l===T){let w;try{const b=nC.fromBinary(k);w=new Error(b.errorMessage)}catch(b){w=new Error("failed to parse error message",{cause:b});try{const P=aP.fromBinary(k);w=new Error(P.message)}catch(P){w=new Error("failed to parse error message",{cause:P})}}c(w),d(v,p)}},v=({id:T,payload:k})=>{l===T&&(o({id:T,payload:k}),d(v,p))};a(this,Oe).on(n,v),a(this,Oe).on(Xg,p),a(this,Oe).on(cr.errorResponse,p),a(this,Oe).on(wr.errorResponse,p),setTimeout(()=>{d(v,p),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Oe).send(t,l,r,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Oe).on(t,e)}onStateEvent(t,e){a(this,Oe).on(t,e)}removeListener(t,e){a(this,Oe).removeListener(t,e)}removeListeners(t){a(this,Oe).removeListeners(t)}flush(){return a(this,Oe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,gr)&&(clearTimeout(a(this,gr)),f(this,gr,void 0)),a(this,Ne,xe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var r;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:E.location.country});const{recv:i,send:s}=(r=a(this,Ne,xe).mediaState)!=null?r:{};i!=null&&i.state&&(i==null?void 0:i.state)!==ta.CONNECTED||s!=null&&s.state&&(s==null?void 0:s.state)!==ta.CONNECTED?a(this,ut).getValue("peerSessionStore").emit(M.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}):f(this,gr,setTimeout(()=>{a(this,ut).getValue("peerSessionStore").emit(M.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}),f(this,gr,void 0)},oN)),a(this,Ne,xe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),a(this,Ne,xe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ne,xe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ne,xe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ne,xe).mediaJoinAttempted}}),a(this,gr)&&(clearTimeout(a(this,gr)),f(this,gr,void 0)),a(this,ut).getValue("peerSessionStore").emit(M.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ne,xe).mediaJoinAttempted}),a(this,Ne,xe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),a(this,ut).getValue("peerSessionStore").emit(M.SOCKET_SERVICE_FAILED),a(this,Ne,xe).updateSocketConnectionState("failed")}))}},ds=new WeakMap,Oe=new WeakMap,Ne=new WeakSet,xe=function(){return a(this,ut).getValue("connectionHandler")},gr=new WeakMap,ut=new WeakMap,Fc=new WeakSet,Mu=function(t){let e=Yy.getSocketEdgeDomain(a(this,ut).getValue("baseURI"));typeof Zn(a(this,ut),"socket_server_base")=="string"&&(e=Zn(a(this,ut),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),s=this.peerId,n=G(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},s!==t&&{oldPeerID:s}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Yd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(n).forEach(([o,c])=>{i.searchParams.append(o,c.toString())}),i.href},Bc=new WeakSet,Au=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Zg);let oc=Yy;Ol([E.trace("SocketService.connect")],oc.prototype,"connect",1);Ol([E.trace("SocketService.disconnect")],oc.prototype,"disconnect",1);Ol([E.trace("SocketService.sendMessagePromise")],oc.prototype,"sendMessagePromise",1);Ol([E.trace("SocketService.sendMessagePromiseWithTimeout")],oc.prototype,"sendMessagePromiseWithTimeout",1);class cN{constructor(e){m(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var r;const i=OP.fromBinary(e),s=i.meetings.map(n=>{var o;return{id:n.id,title:n.title,participants:(o=n.participants)!=null?o:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(r=i.parentMeeting.participants)!=null?r:[]},meetings:s}}handleTransferPeerRaw({payload:e}){const r=nR.fromBinary(e);return{authToken:r.authToken,meetingId:r.meetingId}}handleMovedPeerRaw({payload:e}){const r=Gv.fromBinary(e);return{meetingId:r.meetingId,customParticipantId:r.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Fm.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return zP.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:r}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,xP.toBinary({payloads:e}));return Fm.fromBinary(r).payloads.map(i=>({id:i.id,title:i.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const r=e.map(s=>({id:s})),i=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,JP.toBinary({payloads:r}));return this.handleConnectedRoomsDeletedRaw(i)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const r=yield this.socketService.sendMessagePromise(F.movePeers,tR.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(r.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(r){return{success:!1,error:r}}})}}var dN=Object.defineProperty,lN=Object.getOwnPropertyDescriptor,uN=(t,e,r,i)=>{for(var s=i>1?void 0:i?lN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&dN(e,r,s),s},Ur;class Qy extends Xt{constructor(e){const r=e.getValue("logger");super(r),m(this,"meetings",[]),m(this,"parentMeeting",null),g(this,Ur,void 0),f(this,Ur,e)}get supportsConnectedMeetings(){return a(this,Ur).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield a(this,Ur).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Ur).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Ur).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(i=>e.includes(i.id)&&i.participants.length!==0?this.moveParticipants(i.id,this.parentMeeting.id,i.participants.map(s=>s.id)):Promise.resolve());return yield Promise.all(r),yield a(this,Ur).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield a(this,Ur).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(n=>({id:n}))});return s.success&&this.moveSuccessHandler(e,r,i),s})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield a(this,Ur).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return s.success&&this.moveSuccessHandler(e,r,i.map(n=>n.id)),s})}moveSuccessHandler(e,r,i){const s=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(n=>n.participants)].forEach(n=>s.set(n.id,n)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(n=>s.get(n)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(n=>!i.includes(n.id))),this.meetings=this.meetings.map(n=>{if(r===n.id){const o=n.participants.concat(i.map(c=>s.get(c)));return G(V({},n),{participants:o})}if(e===n.id){const o=n.participants.filter(c=>!i.includes(c.id));return G(V({},n),{participants:o})}return n})}}Ur=new WeakMap;uN([Bt({maxInvocations:60,period:60})],Qy.prototype,"getConnectedMeetings",1);var hN=Object.defineProperty,pN=Object.getOwnPropertyDescriptor,Rp=(t,e,r,i)=>{for(var s=i>1?void 0:i?pN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&hN(e,r,s),s},ke,ef;const Xy=(ef=class{constructor(t){m(this,"connectedMeetings"),g(this,ke,void 0),f(this,ke,t),this.connectedMeetings=new Qy(t)}get telemetry(){return a(this,ke).getValue("telemetry")}get logger(){return a(this,ke).getValue("logger")}static init(t){const e=new Xy(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ke).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:r}){var i,s,n,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
22
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",r);const c={video:a(this,ke).getValue("self").videoEnabled,audio:a(this,ke).getValue("self").audioEnabled};try{a(this,ke).getValue("self").cleanupEvents(),yield a(this,ke).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(s=(i=a(this,ke).getValue("meeting"))==null?void 0:i.meta)==null?void 0:s.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${r}`);const d=yield eS.init(G(V({},a(this,ke).getValue("options")),{cachedUserDetails:null,defaults:G(V(V({},a(this,ke).getValue("options").defaults),c),{mediaHandler:a(this,ke).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(n=d==null?void 0:d.meta)==null?void 0:n.meetingId}`);try{const{hidden:l}=a(this,ke).getValue("self");d.self.setName(a(this,ke).getValue("self").name),yield d.join(),l&&d.self.hide()}catch(l){this.logger.error("ConnectedMeetingsController.joinRoom",{error:l})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(r=>({id:r.id,title:r.title,participants:r.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,ke).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),r=new Map;this.connectedMeetings.meetings.forEach(i=>{r.set(i.id,i)}),e.forEach(i=>{r.has(i.id)?r.get(i.id).title=i.title:r.set(i.id,G(V({},i),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(r.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,ke).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ke=new WeakMap,ef);let Nl=Xy;Rp([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Nl.prototype,"getConnectedMeetings",1);Rp([E.trace("ConnectedMeetingsController.setupEvents")],Nl.prototype,"setupEvents",1);Rp([E.trace("ConnectedMeetingsController.switchMeeting")],Nl.prototype,"switchMeeting",1);var mN=Object.defineProperty,gN=Object.getOwnPropertyDescriptor,Vl=(t,e,r,i)=>{for(var s=i>1?void 0:i?gN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&mN(e,r,s),s};const xn=class{constructor(t,e,r){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"),m(this,"connectedMeetingsController"),m(this,"telemetry"),m(this,"logger"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=r.getValue("telemetry"),this.logger=r.getValue("logger")}static init(t){return u(this,null,function*(){var e,r;const{peerId:i,apiBase:s,authToken:n,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(Ny(t),Ie.isSupported()===!1)throw new C("Browser not supported","0010",l,!0);const h=vD(t,{authToken:n,baseURL:s,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",i),t.setValue("apiClient",h);const p=new ZD(t);t.setValue("connectionHandler",p);const v=xn.createSocketService(t),T=v.connect(),k=h.getUserDetails(),w=h.getPlugins();let b=De.HIVE,P,j="";try{yield xn.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield T}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:b,meetingTitle:j}=yield h.getRoomNodeData()),P=yield k,l.info(`SFU ${b} is being used.`),t.setValue("presetName",P.preset.name),t.setValue("roomNodeOptions",{sfu:b})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const W=xO.init(P.preset,!t.getValue("modules").theme),_=s1.init(t,W.viewType,P.preset.permissions),te=xn.setupControllers(v,t,P,w,j,W,_);jD(W)&&((e=xn.createRoomNodeClient(t,v).initializeConnection(P.participant.name,o,!1,_))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),E.location.country=(r=h.ipInfo)==null?void 0:r.country;const{controllers:re}=yield te;return F0(),new xn(s,re,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:r,baseURI:i,overrides:s,meetingId:n,organizationId:o,logger:c}=t.getAllValues(),d=U0(n),l=G(V({entity:ju.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:n},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=s==null?void 0:s.whitelabelled_flags_endpoint)==null||e?Ds({servicePrefix:"flags",baseURI:i}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${ju.PEER}_${r}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch{c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,r,i,s,n,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:p}=r,v=e.getValue("defaults"),T=e.getValue("logger"),{sfu:k}=e.getValue("roomNodeOptions"),{viewType:w,mediaConstraints:{audio:b}}=n;e.setValue("viewType",w),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=b.enableHighBitrate)!=null?c:!1,enableStereo:(d=b.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",Ie.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let P,j,W,_,te,re,ae,Me,Xe;const jt=new N1(e,t),A=new cN(t);e.setValue("connectedMeetingsSocketHandler",A);const S=new Al(e,t),I=new dr(e,t),B=new B1(t),oe=new Ly(e,t),He=new W1(e,t),x=new O1(t),R=new Ls(e,t),ce=yield Qi.init(e,oe,p,o,n);e.setValue("selfController",ce);const Xi=yield iy.init(e,ce.self,oe,jt,s);if(h.participant&&(Me=new fi(e,ce.self,oe,k)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(T,e.getValue("peerSessionStore")),h.chat&&(j=yield di.init(e,I,R,ce.self,Me.participants)),h.internals&&(te=yield vp.init(e)),h.livestream&&n.viewType===Ft.Livestream&&e.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&(ae=new hy(e,ce.self,x)),n.viewType!==Ft.Chat){if(h.poll&&(P=yield Zv.init(e,ce.self,S)),h.recording&&(re=new oy(e,ce.self,oe)),h.stage&&(W=new sy(e,B,oe,ce.self,Me.participants)),h.plugin){if(!Me)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Jr=yield i;_=yield ic.init(e,Jr,He,I,j==null?void 0:j.chat,ce.self,Me.participants,s)}if(h.connectedMeetings&&(Xe=yield Nl.init(e)),h.pip){const Jr=yield j0._init(e,ce.self);e.setValue("pip",Jr)}}const Zi={storesManager:new GO(e,He),pollController:P,selfController:ce,metaController:Xi,chatController:j,stageController:W,pluginController:_,recordingController:re,internalsController:te,livestreamController:ae,participantController:Me,connectedMeetingsController:Xe};return{theme:n,permissions:o,controllers:Zi}})}static createRoomNodeClient(t,e){const{peerId:r,roomNodeOptions:i}=t.getAllValues(),{sfu:s}=i;return Oy(t,s,{socket:e,peerId:r})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:i}=t.getAllValues(),s=["PING"];return new oc(t,{peerId:e,meetingId:r,authToken:i,capabilities:s})}};let cc=xn;Vl([E.trace("Controller.init")],cc,"init",1);Vl([E.trace("setupFlagsmith")],cc,"setupFlagsmith",1);Vl([E.trace("Controller.createRoomNodeClient")],cc,"createRoomNodeClient",1);Vl([E.trace("Controller.createSocketService")],cc,"createSocketService",1);class fN{constructor(){m(this,"battery"),m(this,"logger"),m(this,"init",e=>u(this,null,function*(){this.logger=e;try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(r){e.error("Error getting battery",r)}})),m(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)}),m(this,"cleanup",()=>{var e,r;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(r=this.battery)==null||r.removeEventListener("levelchange",this.updateLevelInfo))})}}const tf=new fN;function vN(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:r,orgId:i,participantId:s}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let n="dyte.io";e&&(n=e);const o=`https://${Ds({servicePrefix:"api",baseURI:n})}`;return{meetingId:r,orgId:i,participantId:s,baseURI:n,apiBase:o}}catch{throw new C("Invalid auth token","0004")}}var ws,Un,Fn,pl,$h,Zy;class yN{constructor(){g(this,$h),g(this,ws,new Audio),g(this,Un,new MediaStream),g(this,Fn,new Map),g(this,pl,void 0),a(this,ws).srcObject=a(this,Un),a(this,ws).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(r=>{a(this,Fn).has(r.id)||(a(this,Un).addTrack(r),a(this,Fn).set(r.id,r))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,ws).setSinkId(e)}removeTrack(e){const r=a(this,Fn).get(e);r&&(a(this,Un).removeTrack(r),a(this,Fn).delete(e))}play(){return u(this,null,function*(){return a(this,ws).srcObject=a(this,Un),a(this,ws).play().catch(e=>{U(this,$h,Zy).call(this,e)})})}onError(e){f(this,pl,e)}}ws=new WeakMap,Un=new WeakMap,Fn=new WeakMap,pl=new WeakMap,$h=new WeakSet,Zy=function(t){var e;(e=a(this,pl))==null||e.call(this,t)};var Bn;class SN extends yN{constructor(){super(),g(this,Bn,void 0),f(this,Bn,new Map)}addParticipantTrack(e,r){a(this,Bn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,Bn).get(e);r&&this.removeTrack(r),a(this,Bn).delete(e)}}Bn=new WeakMap;var TN=Object.defineProperty,EN=Object.getOwnPropertyDescriptor,Ll=(t,e,r,i)=>{for(var s=i>1?void 0:i?EN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&TN(e,r,s),s},et,vn,rf;let zi=(rf=class{constructor(t,e){g(this,et,void 0),g(this,vn,void 0),f(this,vn,t),f(this,et,e)}get peerId(){return a(this,vn).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var i;const s=(i=r==null?void 0:r.peerId)!=null?i:Ns(),n=ci.createContext(s,{peerId:s}),o=n.getValue("logger");o.init(n);const c=new fy(o);return c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,r,i,s,n,o,c;Ie.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((i=(r=t==null?void 0:t.cachedUserDetails)==null?void 0:r.peerId)!=null?i:Ns()),{authToken:h,baseURI:p}=t,v=vN(h,p),{meetingId:T}=v,k=fl(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const w=zi.setupContext(l,t,T,k),b=w.getValue("telemetry"),P=w.getValue("logger");hT(P),tf.init(P),b.init(w,{roomName:T,userId:k.participantId,organizationId:k.orgId,peerId:l},(n=(s=t.modules)==null?void 0:s.tracing)!=null?n:!0),P.init(w),P.info("DyteClient::init::options",{dyteClientInitOptions:G(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
23
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield cc.init(w),W=new zi(w,j);return w.setValue("meeting",W),W})}static setupContext(t,e,r,i){var s,n;const o=ci.createContext(t,e),c=V(V({},M0),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",r),o.setValue("apiBase",i.apiBase),o.setValue("baseURI",i.baseURI),o.setValue("userId",i.participantId),o.setValue("organizationId",i.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(s=e.overrides)!=null?s:{}),o.setValue("env",A0({baseURI:i.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",Ir(e.cachedUserDetails)),o.setValue("sdkVersion","3.2.0-staging.10"),(n=e.modules)!=null&&n.experimentalAudioPlayback&&o.setValue("audioPlayback",new SN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){tf.cleanup(),a(this,vn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,et);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,vn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},et=new WeakMap,vn=new WeakMap,rf);Ll([ft("0002"),gi.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],zi.prototype,"join",1);Ll([ft("0003")],zi.prototype,"leave",1);Ll([ft("0001"),gi.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],zi,"init",1);zi=Ll([ft("0000")],zi);const eS=zi;class kN{constructor(e){dc(this,"meeting");dc(this,"l");dc(this,"onUpdate",()=>{this.l.forEach(e=>{e()})});var r,i,s,n,o,c,d,l,h,p,v,T,k,w,b,P;this.meeting=e,this.l=new Set,(r=this.meeting.self)==null||r.addListener("*",this.onUpdate),(i=this.meeting.meta)==null||i.addListener("*",this.onUpdate),(s=this.meeting.participants)==null||s.addListener("*",this.onUpdate),(o=(n=this.meeting.participants)==null?void 0:n.joined)==null||o.addListener("*",this.onUpdate),(d=(c=this.meeting.participants)==null?void 0:c.active)==null||d.addListener("*",this.onUpdate),(h=(l=this.meeting.participants)==null?void 0:l.waitlisted)==null||h.addListener("*",this.onUpdate),(p=this.meeting.stage)==null||p.addListener("*",this.onUpdate),(v=this.meeting.livestream)==null||v.addListener("*",this.onUpdate),(T=this.meeting.chat)==null||T.addListener("*",this.onUpdate),(k=this.meeting.plugins)==null||k.all.addListener("*",this.onUpdate),(w=this.meeting.recording)==null||w.addListener("*",this.onUpdate),(b=this.meeting.connectedMeetings)==null||b.addListener("*",this.onUpdate),(P=this.meeting.polls)==null||P.addListener("*",this.onUpdate)}clean(){var e,r,i,s,n,o,c,d,l,h,p,v,T,k,w,b;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(r=this.meeting.meta)==null||r.removeListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.removeListener("*",this.onUpdate),(n=(s=this.meeting.participants)==null?void 0:s.joined)==null||n.removeListener("*",this.onUpdate),(c=(o=this.meeting.participants)==null?void 0:o.active)==null||c.removeListener("*",this.onUpdate),(l=(d=this.meeting.participants)==null?void 0:d.waitlisted)==null||l.removeListener("*",this.onUpdate),(h=this.meeting.stage)==null||h.removeListener("*",this.onUpdate),(p=this.meeting.livestream)==null||p.removeListener("*",this.onUpdate),(v=this.meeting.chat)==null||v.removeListener("*",this.onUpdate),(T=this.meeting.plugins)==null||T.all.removeListener("*",this.onUpdate),(k=this.meeting.recording)==null||k.removeListener("*",this.onUpdate),(w=this.meeting.connectedMeetings)==null||w.removeListener("*",this.onUpdate),(b=this.meeting.polls)==null||b.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const xl=Pt.createContext({meeting:void 0,updates:void 0});function bN({value:t,children:e,fallback:r}){const[i,s]=Pt.useState(),n=Pt.useRef();return Pt.useEffect(()=>(t&&s(new kN(t)),()=>{var o;(o=n.current)==null||o.clean()}),[t]),sS.default.createElement(xl.Provider,{value:{meeting:t,updates:i}},t?e:r)}const wN=()=>{const{meeting:t}=Pt.useContext(xl);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},_N=t=>{const e=Pt.useRef(!1),[r,i]=Pt.useState(),s=t==null?void 0:t.resetOnLeave,n=Pt.useCallback(async o=>{if(!e.current)return e.current=!0,eS.init(o).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Pt.useEffect(()=>{if(!r||!s)return()=>{};const o=({state:c})=>{c!=="connected-meeting"&&c!=="disconnected"&&i(void 0)};return r.self.on("roomLeft",o),()=>{r.self.removeListener("roomLeft",o)}},[r]),Pt.useEffect(()=>{if(!r||!r.connectedMeetings)return()=>{};const o=c=>{i(void 0),setTimeout(()=>{i(c)},100)};return r.connectedMeetings.on("meetingChanged",o),()=>{r.connectedMeetings.removeListener("meetingChanged",o)}},[r]),[r,n]},IN=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),CN=t=>{const{meeting:e,updates:r}=Pt.useContext(xl);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const i=Pt.useRef(t(e)),[,s]=Pt.useReducer(n=>n+1,0);return Pt.useEffect(()=>{const n=e&&t(e),o=()=>{const c=e&&t(e);IN(i.current,c)&&(i.current=c,s())};return n&&typeof n=="object"&&"addListener"in n?(n.addListener("*",s),()=>{n.removeListener("*",s)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),i.current};exports.RealtimeKitContext=xl;exports.RealtimeKitProvider=bN;exports.useRealtimeKitClient=_N;exports.useRealtimeKitMeeting=wN;exports.useRealtimeKitSelector=CN;
23
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield cc.init(w),W=new zi(w,j);return w.setValue("meeting",W),W})}static setupContext(t,e,r,i){var s,n;const o=ci.createContext(t,e),c=V(V({},M0),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",r),o.setValue("apiBase",i.apiBase),o.setValue("baseURI",i.baseURI),o.setValue("userId",i.participantId),o.setValue("organizationId",i.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(s=e.overrides)!=null?s:{}),o.setValue("env",A0({baseURI:i.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",Ir(e.cachedUserDetails)),o.setValue("sdkVersion","3.2.0-staging.11"),(n=e.modules)!=null&&n.experimentalAudioPlayback&&o.setValue("audioPlayback",new SN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){tf.cleanup(),a(this,vn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,et);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,vn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},et=new WeakMap,vn=new WeakMap,rf);Ll([ft("0002"),gi.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],zi.prototype,"join",1);Ll([ft("0003")],zi.prototype,"leave",1);Ll([ft("0001"),gi.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],zi,"init",1);zi=Ll([ft("0000")],zi);const eS=zi;class kN{constructor(e){dc(this,"meeting");dc(this,"l");dc(this,"onUpdate",()=>{this.l.forEach(e=>{e()})});var r,i,s,n,o,c,d,l,h,p,v,T,k,w,b,P;this.meeting=e,this.l=new Set,(r=this.meeting.self)==null||r.addListener("*",this.onUpdate),(i=this.meeting.meta)==null||i.addListener("*",this.onUpdate),(s=this.meeting.participants)==null||s.addListener("*",this.onUpdate),(o=(n=this.meeting.participants)==null?void 0:n.joined)==null||o.addListener("*",this.onUpdate),(d=(c=this.meeting.participants)==null?void 0:c.active)==null||d.addListener("*",this.onUpdate),(h=(l=this.meeting.participants)==null?void 0:l.waitlisted)==null||h.addListener("*",this.onUpdate),(p=this.meeting.stage)==null||p.addListener("*",this.onUpdate),(v=this.meeting.livestream)==null||v.addListener("*",this.onUpdate),(T=this.meeting.chat)==null||T.addListener("*",this.onUpdate),(k=this.meeting.plugins)==null||k.all.addListener("*",this.onUpdate),(w=this.meeting.recording)==null||w.addListener("*",this.onUpdate),(b=this.meeting.connectedMeetings)==null||b.addListener("*",this.onUpdate),(P=this.meeting.polls)==null||P.addListener("*",this.onUpdate)}clean(){var e,r,i,s,n,o,c,d,l,h,p,v,T,k,w,b;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(r=this.meeting.meta)==null||r.removeListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.removeListener("*",this.onUpdate),(n=(s=this.meeting.participants)==null?void 0:s.joined)==null||n.removeListener("*",this.onUpdate),(c=(o=this.meeting.participants)==null?void 0:o.active)==null||c.removeListener("*",this.onUpdate),(l=(d=this.meeting.participants)==null?void 0:d.waitlisted)==null||l.removeListener("*",this.onUpdate),(h=this.meeting.stage)==null||h.removeListener("*",this.onUpdate),(p=this.meeting.livestream)==null||p.removeListener("*",this.onUpdate),(v=this.meeting.chat)==null||v.removeListener("*",this.onUpdate),(T=this.meeting.plugins)==null||T.all.removeListener("*",this.onUpdate),(k=this.meeting.recording)==null||k.removeListener("*",this.onUpdate),(w=this.meeting.connectedMeetings)==null||w.removeListener("*",this.onUpdate),(b=this.meeting.polls)==null||b.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const xl=Pt.createContext({meeting:void 0,updates:void 0});function bN({value:t,children:e,fallback:r}){const[i,s]=Pt.useState(),n=Pt.useRef();return Pt.useEffect(()=>(t&&s(new kN(t)),()=>{var o;(o=n.current)==null||o.clean()}),[t]),sS.default.createElement(xl.Provider,{value:{meeting:t,updates:i}},t?e:r)}const wN=()=>{const{meeting:t}=Pt.useContext(xl);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},_N=t=>{const e=Pt.useRef(!1),[r,i]=Pt.useState(),s=t==null?void 0:t.resetOnLeave,n=Pt.useCallback(async o=>{if(!e.current)return e.current=!0,eS.init(o).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Pt.useEffect(()=>{if(!r||!s)return()=>{};const o=({state:c})=>{c!=="connected-meeting"&&c!=="disconnected"&&i(void 0)};return r.self.on("roomLeft",o),()=>{r.self.removeListener("roomLeft",o)}},[r]),Pt.useEffect(()=>{if(!r||!r.connectedMeetings)return()=>{};const o=c=>{i(void 0),setTimeout(()=>{i(c)},100)};return r.connectedMeetings.on("meetingChanged",o),()=>{r.connectedMeetings.removeListener("meetingChanged",o)}},[r]),[r,n]},IN=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),CN=t=>{const{meeting:e,updates:r}=Pt.useContext(xl);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const i=Pt.useRef(t(e)),[,s]=Pt.useReducer(n=>n+1,0);return Pt.useEffect(()=>{const n=e&&t(e),o=()=>{const c=e&&t(e);IN(i.current,c)&&(i.current=c,s())};return n&&typeof n=="object"&&"addListener"in n?(n.addListener("*",s),()=>{n.removeListener("*",s)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),i.current};exports.RealtimeKitContext=xl;exports.RealtimeKitProvider=bN;exports.useRealtimeKitClient=_N;exports.useRealtimeKitMeeting=wN;exports.useRealtimeKitSelector=CN;
package/dist/index.es.js CHANGED
@@ -30504,7 +30504,7 @@ let si = (Wg = class {
30504
30504
  video: true
30505
30505
  };
30506
30506
  return a.setValue("options", e), a.setValue("peerId", t), a.setValue("modules", o), a.setValue("sdkName", "web-core"), a.setValue("meetingId", r), a.setValue("apiBase", i.apiBase), a.setValue("baseURI", i.baseURI), a.setValue("userId", i.participantId), a.setValue("organizationId", i.orgId), a.setValue("authToken", e.authToken), a.setValue("overrides", (d = e.overrides) != null ? d : {}), a.setValue("env", PC({ baseURI: i.baseURI })), a.setValue("defaults", c), a.setValue("onError", e.onError || (() => {
30507
- })), a.setValue("cachedUserDetails", Cs(e.cachedUserDetails)), a.setValue("sdkVersion", "3.2.0-staging.10"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new oO()), a;
30507
+ })), a.setValue("cachedUserDetails", Cs(e.cachedUserDetails)), a.setValue("sdkVersion", "3.2.0-staging.11"), (l = e.modules) != null && l.experimentalAudioPlayback && a.setValue("audioPlayback", new oO()), a;
30508
30508
  }
30509
30509
  join() {
30510
30510
  return u(this, null, function* () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit-react",
3
- "version": "1.2.0-staging.10",
3
+ "version": "1.2.0-staging.11",
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",
@@ -16,11 +16,11 @@
16
16
  "dist"
17
17
  ],
18
18
  "bugs": {
19
- "url": "https://realtime.cloudflare.com/issues"
19
+ "url": "https://community.cloudflare.com"
20
20
  },
21
21
  "private": false,
22
22
  "dependencies": {
23
- "@cloudflare/realtimekit": "1.2.0-staging.10"
23
+ "@cloudflare/realtimekit": "1.2.0-staging.11"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "react": ">=16.8.6"