@cloudflare/realtimekit 0.5.0-staging.91 → 0.5.0-staging.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -21,4 +21,4 @@ slogScale: ${i}, isVoice: ${r}, minEnergy: ${o(this,xr)},
21
21
  maxEnergy: ${o(this,Li)}`),i===-1/0||n<1e-6?{energy:0,isVoice:!1}:((!o(this,xr)||i<o(this,xr))&&v(this,xr,i),(!o(this,Li)||i>o(this,Li))&&v(this,Li,i),{energy:(i-o(this,xr))/(o(this,Li)-o(this,xr))*10||0,isVoice:r})},rl=new WeakSet,hp=function(t){return t<5},pp=new WeakSet,zy=function(t=o(this,Ns)){var e;if(!o(this,Bn)||!t){Q.hasFeature(ie.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&p.debug(`AudioActivityReporter: No producerId or energy to report: ${o(this,Bn)}`);return}const n={producerId:o(this,Bn),energy:Math.round(t),silent:H(e=il,rl,hp).call(e,t)};v(this,Po,n.silent),this.reportRequest(n)},mp=new WeakSet,Yy=function(t){const e=Math.log10(t);return Math.round(e)},f(gp,rl),f(gp,mp);const YN=()=>{const t=new window.AudioContext,e=t.createOscillator();e.type="triangle",e.frequency.setValueAtTime(20,t.currentTime);const n=t.createGain();n.gain.setValueAtTime(0,t.currentTime),e.connect(n);const r=t.createMediaStreamDestination();return n.connect(r),e.start(),r.stream.getAudioTracks()[0]},QN=()=>{var t,e;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(t=n==null?void 0:n.getSettings().height)!=null?t:720,r.width=(e=n==null?void 0:n.getSettings().width)!=null?e:1280;const i=r.getContext("2d");return i.fillStyle="black",i.fillRect(0,0,r.width,r.height),setInterval(()=>{i.fillStyle="black",i.fillRect(0,0,r.width,r.height)},1e3),r.captureStream().getVideoTracks()[0]};var XN=Object.defineProperty,ZN=Object.getOwnPropertyDescriptor,he=(t,e,n,r)=>{for(var i=r>1?void 0:r?ZN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&XN(e,n,i),i};const Wn=["video/VP9","video/VP8"];var sl,al,Pt,$,Ro,xi,Ft,Ls,xs,Vi,ol,Vr,Ao,Vs,Us,Bt,Qt,Ui,Fs,ft,Rt,Bs,Mo,fp,Qy,vp,Xy,yp,Zy;class ue{constructor(e,n,r){f(this,Ui),f(this,ft),f(this,Bs),f(this,fp),f(this,vp),f(this,yp),g(this,"context"),g(this,"authToken"),g(this,"e2ee"),f(this,sl,void 0),f(this,al,void 0),f(this,Pt,void 0),f(this,$,void 0),f(this,Ro,void 0),f(this,xi,void 0),f(this,Ft,void 0),f(this,Ls,void 0),f(this,xs,void 0),f(this,Vi,void 0),f(this,ol,void 0),f(this,Vr,void 0),f(this,Ao,void 0),f(this,Vs,void 0),f(this,Us,void 0),f(this,Bt,void 0),f(this,Qt,void 0),g(this,"partialJoinRoomPromise");var i,s;this.context=e;const{socket:a}=r;this.mediaJoined=!1,v(this,Vs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Us,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,xi,n),v(this,Pt,a),v(this,Ls,!1),v(this,$,new $N(e,a,n)),v(this,Ft,o(this,$).events),v(this,Vr,new Set),v(this,Bt,new Map),v(this,xs,!1),v(this,Vi,new xd),n===tt.CF&&v(this,Qt,new gp(o(this,$).socketHandler.audioActivity.bind(o(this,$).socketHandler))),this.e2ee=(s=(i=e.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,ol,Hc(()=>u(this,null,function*(){if(!o(this,Ui,Fs).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(o(this,al),o(this,sl),{},!0,!0);c&&(P.emit(R.RESET_PRODUCER_STATE),P.emit(R.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return o(this,Ui,Fs).mediaJoined}set mediaJoined(e){o(this,Ui,Fs).mediaJoined=e}reset(e=!0){o(this,$).closeAllProducers(),o(this,$).closeAllConsumers(),o(this,Bt).clear(),o(this,Vr).clear(),e&&(this.partialJoinRoomPromise=void 0,o(this,Vi).stop(),o(this,$).stopAllTransports(),o(this,$).reset(),v(this,Vi,new xd))}joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=!1){o(this,Ui,Fs).mediaJoinAttempted=!0,v(this,Ls,!0),this.reset(a);const d=ot().ipInfo;if(d!=null&&d.loc&&!o(this,Ao)){const h=d.loc.split(",");v(this,Ao,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let l;try{return l=yield o(this,Vi).push(()=>this._joinRoom(r,i,s,c,o(this,Ao)),"joinRoom"),l}catch(h){l={roomJoined:!1}}return l.roomJoined||P.emit(R.ROOM_NODE_FAILED),l})}_partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){var s;const{ipInfo:a}=ot();let c=i;if(a!=null&&a.loc&&!i){const[h,m]=a.loc.split(",").map(parseFloat);c={latitude:h,longitude:m}}const d=(s=Q.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:s.toString(),l=ON(d);v(this,Ro,l),yield Dh((h,m)=>u(this,null,function*(){if(!o(this,Pt).isConnected){m(new Error("socket is not connected"));return}h>0&&p.warn(`retrying sending join room request, count: ${h}`);try{yield o(this,$).socketHandler.joinRoom(n,e,l,r,c)}catch(y){throw p.error("failed to send join room request, error:",{error:y}),y}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield o(this,$).setupTransports({send:!0,recv:!0}),o(this,xi)!==tt.HIVE&&Q.hasFeature(ie.PRECREATE_PRODUCERS)&&(this.shareWebcam(QN()),this.shareMic(YN()))})}partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){return this.partialJoinRoomPromise=o(this,Vi).push(()=>this._partialJoinRoom(e,n,r,i)),this.partialJoinRoomPromise})}_joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=null){v(this,al,r);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,i,a,c)}catch(d){p.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:i,roomViewType:"groupCall",deviceInfo:G(x({},Ie.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};J.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return p.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:e}=yield o(this,$).socketHandler.notifySelfJoinComplete();return v(this,sl,e.roomUuid),v(this,xs,!0),v(this,Ls,!1),!0}catch(e){return p.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){o(this,$).stopAllTransports(),v(this,xs,!1),o(this,Ui,Fs).mediaJoinAttempted=!1;const e={closeRoom:!1};o(this,Pt).sendMessagePromise(o(this,Ft).leaveRoom,HC.toBinary(e)).then(n=>{var r;(r=PP.fromBinary(n.payload))!=null&&r.closed||p.warn("weird state on peer closed and should not happen")}).catch(n=>{p.error("error on sending leave room request",{error:n})}),J.callEnded(),S.destruct()})}getConsumers(){return o(this,$).consumers}activatePeers(e){return u(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,n="default"){return u(this,null,function*(){const r=new Set;e.forEach(s=>{s.screenShare&&s.kind==="video"&&r.add(s.producingPeerId)});const i=n==="default"?e.filter(s=>!r.has(s.producingPeerId)).filter(s=>s.kind!=="audio"):e;yield Promise.all(i.map(s=>{const a=o(this,$).producerIdToConsumerIdMap.get(s.producerId);if(!a){p.warn(`consumer not found in deactivate producers: ${s.producerId}`);return}return o(this,$).closeConsumer(a)}))})}createConsumers(e){return u(this,null,function*(){return e.length===0?Promise.resolve():o(this,$).createConsumers(e)})}closeConsumers(e){return u(this,null,function*(){if(!e.length)return;const n=e.reduce((r,i)=>{const s=o(this,$).producerIdToConsumerIdMap.get(i.producerId);return s?(r.push(s),r):(p.warn(`consumer not found in deactivate producers: ${i.producerId}`),r)},[]);yield o(this,$).closeConsumers(n)})}_shareWebcam(e,n){return u(this,null,function*(){const r=n==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=H(this,ft,Rt).call(this,r);if(i){const h=yield i;if(o(this,$).producers.has(h)){const m=o(this,$).producers.get(h);if(!m.closed&&!navigator.isReactNative)return yield m.replaceTrack({track:e}),yield this.resumeWebcam(r),e;yield this.disableWebcam(n)}return this._shareWebcam(e,n)}const s=H(this,yp,Zy).call(this,e,n),a=Jc(this.context,"disableSimulcast"),c=o(this,xi)===tt.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!a&&Q.hasFeature(c)?(p.info(`Simulcast enabled for SFU: ${o(this,xi)}`),s.encodings=PO(e)):p.info(`Simulcast disabled for webcam producer, SFU: ${o(this,xi)}`),Q.hasFeature(ie.TRACK_HINT)&&(s.track.contentHint=Q.getValue(ie.TRACK_HINT));const d=()=>{p.info("Disabling video due to the producer closure"),o(this,Bt).delete(r)},l=o(this,$).createProducer(s,d);return H(this,Bs,Mo).call(this,r,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(e){return u(this,null,function*(){if(e===void 0)return null;if(Q.hasFeature(ie.FORCE_VIDEO_CODEC)){const n=Q.getValue(ie.FORCE_VIDEO_CODEC).toString();if(n)return p.debug(`Calling _shareWebcam with forced video codec: ${n}`),this._shareWebcam(e,n)}return yield Promise.all(Wn.map(n=>{var r,i;return((i=(r=o(this,Ro).sender)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===n))>=0&&o(this,Us).get(n).size>0?(p.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(e,n)):e})),e})}shareScreen(e){return u(this,null,function*(){const{video:n,audio:r}=e;if(n===void 0)return;const i={track:n,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},s=()=>{p.info("Disabling screenShare due to the producer closure"),o(this,Bt).delete(ke.SCREENSHARE_VIDEO),o(this,Bt).delete(ke.SCREENSHARE_AUDIO)},a=o(this,$).createProducer(i,s);H(this,Bs,Mo).call(this,ke.SCREENSHARE_VIDEO,a.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},l=()=>{};c=o(this,$).createProducer(d,l),H(this,Bs,Mo).call(this,ke.SCREENSHARE_AUDIO,c.then(h=>h.id))}yield Promise.all([a,c||Promise.resolve()]),J.screenShareStart()})}shareMic(e){return u(this,null,function*(){try{if(e===void 0)throw new Ut("track undefined");const n=H(this,ft,Rt).call(this,ke.MIC);if(n){const a=yield n;if(o(this,$).producers.has(a)){const c=o(this,$).producers.get(a);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),o(this,Qt)&&(o(this,Qt).audioTrack=e,o(this,Qt).producerId=a,o(this,Qt).start());return}yield o(this,$).closeProducer(a,{stopTrack:!1})}yield this.shareMic(e);return}const r=H(this,vp,Xy).call(this,e),i=()=>{o(this,Bt).delete(ke.MIC)},s=o(this,$).createProducer(r,i);H(this,Bs,Mo).call(this,ke.MIC,s.then(a=>a.id)),yield s.then(a=>{o(this,Qt)&&(o(this,Qt).audioTrack=a.track,o(this,Qt).producerId=a.id,o(this,Qt).start())})}catch(n){throw new w(n)}})}pauseMic(){return u(this,null,function*(){var e;const n=yield H(this,ft,Rt).call(this,ke.MIC),r=o(this,$).producers.get(n);if(!r){p.error("pauseMic::could_not_find_mic_producer");return}if(r.paused){p.info("pauseMic::mic_producer_already_paused");return}r.pause(),(e=o(this,Qt))==null||e.stop();const i={producerId:r.id,pause:!0};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Yc.toBinary(i))})}pauseWebcam(){return u(this,null,function*(){const e=yield H(this,ft,Rt).call(this,ke.WEBCAM),n=yield H(this,ft,Rt).call(this,ke.WEBCAM_BACKUP),r=o(this,$).producers.get(e),i=o(this,$).producers.get(n);if(!r&&!i){p.error("pauseWebcam::could_not_find_webcam_producer");return}const s=a=>{const c={producerId:a.id,pause:!0};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Yc.toBinary(c))};r&&(r.pause(),s(r)),i&&(i.pause(),s(i))})}resumeMic(){return u(this,null,function*(){const e=yield H(this,ft,Rt).call(this,ke.MIC),n=o(this,$).producers.get(e);if(!n){p.error("resumeMic::could_not_find_mic_producer");return}if(!n.pause){p.info("resumeMic::mic_producer_already_resumed");return}n.resume(),n.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,n);const r={producerId:n.id,pause:!1};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Yc.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(e=ke.WEBCAM){const n=yield H(this,ft,Rt).call(this,e),r=o(this,$).producers.get(n);if(!r){p.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){p.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Yc.toBinary(i))})}disableWebcam(e){return u(this,null,function*(){const n=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,r=yield H(this,ft,Rt).call(this,n);H(this,fp,Qy).call(this,n),r&&(yield o(this,$).closeProducer(r))})}disableMic(){return u(this,null,function*(){var e;const n=yield H(this,ft,Rt).call(this,ke.MIC);n&&(yield o(this,$).closeProducer(n)),(e=o(this,Qt))==null||e.stop(),o(this,Bt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){p.info("screen_sharing_stopped"),J.screenShareStop();const e=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_VIDEO),n=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_AUDIO);e&&(yield o(this,$).closeProducer(e)),n&&(yield o(this,$).closeProducer(n)),o(this,Vr).clear(),o(this,Bt).delete(ke.SCREENSHARE_VIDEO),o(this,Bt).delete(ke.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(e,n){return u(this,null,function*(){if(e){const r=yield H(this,ft,Rt).call(this,ke.WEBCAM),i=yield H(this,ft,Rt).call(this,ke.WEBCAM_BACKUP);yield o(this,$).closeProducer(r,{stopTrack:!1}),yield o(this,$).closeProducer(i,{stopTrack:!1}),this.shareWebcam(e)}if(n){const r=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_VIDEO);yield o(this,$).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:n})}})}changeDisplayName(e,n){return u(this,null,function*(){const r={displayName:e,participantId:n!=null?n:this.peerId};if(!(yield o(this,$).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(e){return u(this,null,function*(){const n={participantId:e};if(!(yield o(this,$).socketHandler.kickPeer(n)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return u(this,null,function*(){const n={participantId:e!=null?e:""};try{yield o(this,Pt).sendMessagePromise(o(this,Ft).globalPinPeer,ZC.toBinary(n))}catch(r){p.error("Error in pinning peer:",{error:r})}})}validateScreenShare(e){return this.peerId===e.peerId&&o(this,$).producers.get(e.producerId)&&o(this,Vr).add(e.consumerPeerId),o(this,Vr).size}switchConsumersToLayer(e,n){return u(this,null,function*(){o(this,$).switchConsumersToLayer(e,n)})}handleSocketEvents(){return u(this,null,function*(){o(this,Pt).on(o(this,Ft).peerProducerCreateBroadcast,({payload:e})=>{var n,r;if(this.mediaJoined)try{const{participantId:i,producerState:s}=aR.fromBinary(e);if(i===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===Ln.AUDIO?"audio/opus":"video/VP8"),s.kind===Ln.VIDEO&&!s.screenShare&&((r=(n=o(this,Ro).receiver)==null?void 0:n.video)==null?void 0:r.codecs.findIndex(a=>a.mimeType===Wn[0]))>=0&&o(this,Vs).get(Wn[0]).has(i)&&s.mimeType!==Wn[0]){p.warn(`Ignoring producer: ${s.producerId}`);return}p.info(`producer created broadcast: ${i}, producer state: ${s}`),P.emit(R.NEW_PRODUCER,{peerId:i,producer:G(x({},s),{kind:s.kind===Ln.AUDIO?"audio":"video",producingPeerId:i})})}catch(i){p.error("error in peer-producer-create-broadcast",{error:i})}}),o(this,Pt).on(o(this,Ft).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,initiatorParticipantId:r,producerState:{kind:i,pause:s,producerId:a}}=ov.fromBinary(e),c=i===Ln.AUDIO?"audio":"video";if(p.info(`producer toggle broadcast: ${n}, producerId: ${a}, kind:${c}, paused:${s} payload: ${JSON.stringify(ov.fromBinary(e))}`),n===this.peerId&&r!==this.peerId&&s&&P.emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),n===this.peerId)return;P.emit(R.PRODUCER_TOGGLE,{peerId:n,producerId:a,paused:s,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===a).forEach(d=>{d.paused!==s&&(p.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${s}`),s?(d.pause(),P.emit(R.CONSUMER_PAUSED,{id:d.id})):(d.resume(),P.emit(R.CONSUMER_RESUMED,{id:d.id})))})}catch(n){p.error("error in producer toggle broadcast handler",{error:n})}}),o(this,Pt).on(o(this,Ft).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n}=Nu.fromBinary(e);if(n===this.peerId)return;p.info(`peer left broadcast:${n}`),o(this,Vr).delete(n),o(this,$).consumers.forEach(r=>{r.peerId===n&&r.close()}),P.emit(R.PEER_CLOSED,{id:n})}catch(n){p.error("error in peer left broadcast",{error:n})}}),o(this,Pt).on(o(this,Ft).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,producerState:{producerId:r}}=dR.fromBinary(e);if(n===this.peerId)return;p.info(`producer closed broadcast:${n}`),P.emit(R.PRODUCER_CLOSED,{peerId:n,producerId:r});const i=o(this,$).producerIdToConsumerIdMap.get(r);if(!i){p.warn(`no consumer found for producer:${r}`);return}p.info(`closing consumer ${i}, producer id: ${r}`),o(this,$).closeConsumer(i).then(()=>{p.info(`closed consumer: ${i}`),o(this,$).producerIdToConsumerIdMap.delete(r),P.emit(R.CONSUMER_CLOSED,{id:i})}).catch(s=>{p.error("error closing consumer",{error:s})})}catch(n){p.error("error on producer close broadcast",{error:n})}}),o(this,Pt).on(o(this,Ft).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!o(this,Ls)&&!o(this,xs)||(p.warn("media hub termination broadcast received, rejoining room"),P.emit(R.ROOM_NODE_DISCONNECTED),o(this,ol).call(this))})})}handleCallstatsEvents(){J.onConsumerScore(e=>{e.forEach((n,r)=>{const i=o(this,$).consumers.get(r);i&&P.emit(R.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:n.score,scoreStats:n})})}),J.onProducerScore(e=>{e.forEach((n,r)=>{const i=Array.from(o(this,$).producers.values()).find(s=>s.id===r);i&&P.emit(R.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:n.score,scoreStats:n})})})}handlePeerCapabilities(e,n){var r,i,s,a;for(let c=0;c<=Wn.length;c+=1){const d=Wn[c];if(((i=(r=n==null?void 0:n.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(l=>l.mimeType===d))>=0||c===Wn.length-1){o(this,Us).get(d).add(e);break}}for(let c=0;c<=Wn.length;c+=1){const d=Wn[c];if(((a=(s=n==null?void 0:n.sender)==null?void 0:s.video)==null?void 0:a.codecs.findIndex(l=>l.mimeType===d))>=0||c===Wn.length-1){o(this,Vs).get(d).add(e);break}}}handlePeerLeaving(e){Q.hasFeature(ie.FORCE_VIDEO_CODEC)||(o(this,Vs).forEach(n=>n.delete(e)),o(this,Us).forEach((n,r)=>{n.delete(e),n.size===0&&this.disableWebcam(r)}))}}sl=new WeakMap,al=new WeakMap,Pt=new WeakMap,$=new WeakMap,Ro=new WeakMap,xi=new WeakMap,Ft=new WeakMap,Ls=new WeakMap,xs=new WeakMap,Vi=new WeakMap,ol=new WeakMap,Vr=new WeakMap,Ao=new WeakMap,Vs=new WeakMap,Us=new WeakMap,Bt=new WeakMap,Qt=new WeakMap,Ui=new WeakSet,Fs=function(){return this.context.getValue("connectionHandler")},ft=new WeakSet,Rt=function(t){return o(this,Bt).get(t)},Bs=new WeakSet,Mo=function(t,e){return o(this,Bt).set(t,e)},fp=new WeakSet,Qy=function(t){return o(this,Bt).delete(t)},vp=new WeakSet,Xy=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},yp=new WeakSet,Zy=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},he([S.trace("MediaNodeClient.reset",{country:S.location.country})],ue.prototype,"reset",1),he([S.trace("MediaNodeClient.joinRoom")],ue.prototype,"joinRoom",1),he([S.trace("MediaNodeClient.completeJoinRoom")],ue.prototype,"completeJoinRoom",1),he([S.trace("MediaNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1),he([S.trace("MediaNodeClient.activatePeers")],ue.prototype,"activatePeers",1),he([S.trace("MediaNodeClient.deactivatePeers")],ue.prototype,"deactivatePeers",1),he([S.trace("MediaNodeClient.createConsumers")],ue.prototype,"createConsumers",1),he([S.trace("MediaNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1),he([S.trace("MediaNodeClient._shareWebcam")],ue.prototype,"_shareWebcam",1),he([S.trace("MediaNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1),he([S.trace("MediaNodeClient.shareScreen")],ue.prototype,"shareScreen",1),he([S.trace("MediaNodeClient.shareMic")],ue.prototype,"shareMic",1),he([S.trace("MediaNodeClient.pauseMic")],ue.prototype,"pauseMic",1),he([S.trace("MediaNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1),he([S.trace("MediaNodeClient.resumeMic")],ue.prototype,"resumeMic",1),he([S.trace("MediaNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1),he([S.trace("MediaNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1),he([S.trace("HiveClient.disableMic")],ue.prototype,"disableMic",1),he([S.trace("HiveClient.disableScreenShare")],ue.prototype,"disableScreenShare",1),he([S.trace("MediaNodeClient.muteSelf")],ue.prototype,"muteSelf",1),he([S.trace("MediaNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1),he([S.trace("MediaNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1),he([S.trace("MediaNodeClient.kickPeer")],ue.prototype,"kick",1),he([S.trace("MediaNodeClient.kickAllPeers")],ue.prototype,"kickAll",1),he([S.trace("MediaNodeClient.muteAll")],ue.prototype,"muteAll",1),he([S.trace("MediaNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1),he([S.trace("MediaNodeClient.disableAudio")],ue.prototype,"disableAudio",1),he([S.trace("MediaNodeClient.disableVideo")],ue.prototype,"disableVideo",1),he([S.trace("MediaNodeClient.pinPeer")],ue.prototype,"pinPeer",1),he([S.trace("MediaNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);function eS(t,e,n){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const i=new ue(t,e,n);return t.setValue("roomNodeClient",i),i}function tS(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(n){p.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var eL=Object.defineProperty,tL=Object.getOwnPropertyDescriptor,Fi=(t,e,n,r)=>{for(var i=r>1?void 0:r?tL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&eL(e,n,i),i},Bi,jn,At,an,_n,nS;const rS=(nS=class{constructor(t,e,n,r){f(this,an),g(this,"self"),g(this,"authToken"),f(this,Bi,void 0),g(this,"viewType"),f(this,jn,void 0),f(this,At,void 0);const{socket:i}=n,s=t.getValue("authToken");this.self=e,v(this,At,t),this.viewType=r,this.authToken=s,v(this,Bi,i),v(this,jn,n),e.config.viewType!==yt.Chat&&this.setupEvents()}get peerId(){return o(this,At).getValue("peerId")}get mediaJoined(){return o(this,At).getValue("connectionHandler").mediaJoined}static init(t,e,n,r,i){return u(this,null,function*(){const s=ot(),a=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield rt.__init__(t,n,r,i,i.name,c);if(navigator.product!=="ReactNative"){const l=!Q.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const h=yield d.getAllDevices();p.info("populated_full_device_list",{devices:JSON.stringify(h)}),J.devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),J.devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),J.devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),p.info("Callstats:: initializing");try{yield J.initialize({peerId:a,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Q.getAllFlags(),logger:p,apiHostnames:qf(t),skipConnectivityChecks:l}),p.info("Callstats:: initialized")}catch(m){p.error("Callstats:: initialization failed",{error:m})}}),0)}else p.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new rS(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:n,permissions:r,audioEnabled:i,videoEnabled:s,screenShareEnabled:a,screenShareTracks:c}=this.self;if(r.canProduceAudio&&i)try{yield o(this,an,_n).shareMic(e)}catch(d){this.self.disableAudio()}if(r.canProduceVideo&&s)try{const d=yield o(this,an,_n).shareWebcam(n);d&&d.id!==n.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield o(this,an,_n).shareWebcam(d))}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare&&a)try{yield(t=o(this,an,_n))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){p.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(p.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){p.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(p.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){p.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){J.callEnded(),o(this,an,_n).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){P.on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),P.on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),P.on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),P.on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),P.on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),P.on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Q.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=Gi()),o(this,Bi).updateURL(e),S.resetPeerId(e),ot().setHeader("dyte-tracing-id",e),ri.remapContext(e,o(this,At)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),P.on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),o(this,jn).on(W.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),o(this,jn).on(nd.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&P.emit(R.UPDATE_PERMISSIONS,e.patch)})}),o(this,jn).on(W.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),o(this,jn).on(W.kick,()=>{this.kickHandler({kickType:"kick"})}),o(this,jn).on(W.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),P.onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),P.on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:n,scoreStats:r})=>{var i;const s=(i=n==null?void 0:n.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),P.on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),J.audioOff())})),P.on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),J.videoOff())})),P.onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),P.on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield o(this,jn).joinRoom(this.self);o(this,jn).socket.flush();const n=dh(e.stageType);if(o(this,At).setValue("stageStatus",n,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),o(this,At).notify("stageStatus")}catch(e){throw p.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,n;if(t==="rejected"){try{(e=o(this,Bi))==null||e.disconnect()}catch(r){p.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),o(this,At).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),o(this,At).notify("stageStatus");try{(n=o(this,Bi))==null||n.disconnect()}catch(r){p.error("SelfController::leaveRoom::socketDisconnect")}tS(o(this,At)),Nd.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,n;const{peerId:r,viewType:i,meetingId:s,stageStatus:a,roomNodeOptions:c}=o(this,At).getAllValues(),{sfu:d}=c;try{if(i===yt.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}eS(o(this,At),d,{socket:o(this,Bi),peerId:r})}const{roomJoined:l}=(n=yield(e=o(this,an,_n))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?n:{};if(!l)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw p.error("Error:SelfController.mediaRoomJoin",{error:l}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=o(this,At).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===yt.Webinar)&&o(this,an,_n)&&(o(this,an,_n).mediaJoined&&t!=="disconnected"&&(yield o(this,an,_n).leaveRoom()),!(t==="stageLeft"&&e===yt.Livestream)&&(o(this,an,_n).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()})}},Bi=new WeakMap,jn=new WeakMap,At=new WeakMap,an=new WeakSet,_n=function(){return o(this,At).getValue("roomNodeClient")},nS);let Ur=rS;Fi([S.trace("SelfController.resetSelf")],Ur.prototype,"resetSelf",1),Fi([S.trace("SelfController.setupEvents")],Ur.prototype,"setupEvents",1),Fi([S.trace("SelfController.joinRoom")],Ur.prototype,"joinRoom",1),Fi([S.trace("SelfController.leaveRoom")],Ur.prototype,"leaveRoom",1),Fi([S.trace("SelfController.joinMediaRoom")],Ur.prototype,"joinMediaRoom",1),Fi([S.trace("SelfController.leaveMediaRoom")],Ur.prototype,"leaveMediaRoom",1),Fi([S.trace("SelfController.init")],Ur,"init",1);var cl;class nL{constructor(e){f(this,cl,void 0),v(this,cl,e)}on(e,n){let r;e===W.roomPeerCount?r=lv.fromBinary.bind(lv):r=Iv.fromBinary.bind(Iv),o(this,cl).on(e,({payload:i})=>{const s=r(i);return n(s)})}}cl=new WeakMap;var dl;class rL{constructor(e){f(this,dl,void 0),v(this,dl,e)}on(e,n){let r,i;switch(e){case W.transcript:{r=Lu.fromBinary.bind(Lu),i=Lu.create();break}default:{p.debug("AISocketHandler switch case hit default, event not accounted for.");break}}o(this,dl).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}dl=new WeakMap;var iL=Object.defineProperty,sL=Object.getOwnPropertyDescriptor,Sp=(t,e,n,r)=>{for(var i=r>1?void 0:r?sL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&iL(e,n,i),i},Fr;class ll{constructor(e){f(this,Fr,void 0),v(this,Fr,e)}getPolls(){return o(this,Fr).sendMessagePromise(Xn.getPolls)}createPoll(e,n,r=!1,i=!1){const s={anonymous:r,hideVotes:i,question:e,options:n};return o(this,Fr).sendMessage(Xn.createPoll,X1.toBinary(s))}votePoll(e,n){const r={index:n,pollId:e};return o(this,Fr).sendMessage(Xn.votePoll,eD.toBinary(r))}on(e,n){let r,i;switch(e){case Xn.updatePoll:case Xn.createPoll:case Xn.votePoll:{r=Ku.fromBinary.bind(Ku),i=Ku.create();break}}o(this,Fr).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("pollSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}removeListeners(e){o(this,Fr).removeListeners(e)}}Fr=new WeakMap,Sp([S.trace("PollSocketHandler.getPolls")],ll.prototype,"getPolls",1),Sp([S.trace("PollSocketHandler.createPoll")],ll.prototype,"createPoll",1),Sp([S.trace("PollSocketHandler.votePoll")],ll.prototype,"votePoll",1);var Xt;class aL{constructor(e){f(this,Xt,void 0),v(this,Xt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield o(this,Xt).sendMessagePromise(W.getStageRequests);return e?$u.fromBinary(e):{stageRequests:[]}})}requestAccess(){o(this,Xt).sendMessage(W.requestStageAccess)}cancelRequestAccess(){o(this,Xt).sendMessage(W.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Xt).sendMessage(W.grantStageAccess,j1.toBinary(n))})}denyAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Xt).sendMessage(W.denyStageAccess,q1.toBinary(n))})}joinStage(){return o(this,Xt).sendMessagePromise(W.joinStage,void 0,void 0,W.peerStageStatusUpdate)}leaveStage(e){const n={userIds:[e]};return o(this,Xt).sendMessagePromise(W.leaveStage,Pv.toBinary(n),void 0,W.peerStageStatusUpdate)}kick(e){const n={userIds:e};return o(this,Xt).sendMessagePromise(W.leaveStage,Pv.toBinary(n))}on(e,n){let r;switch(e){case W.grantStageAccess:case W.denyStageAccess:{r=void 0;break}case W.getStagePeers:{r=Cv.fromBinary.bind(Cv);break}case W.getStageRequests:case W.requestStageAccess:case W.cancelStageRequest:{r=$u.fromBinary.bind($u);break}case W.peerStageStatusUpdate:{r=dv.fromBinary.bind(dv);break}}o(this,Xt).on(e,({payload:i,id:s})=>{if(!i||!r)return n(void 0,s);const a=r(i);return n(a,s)})}getPeerInfo(e){return u(this,null,function*(){const n=yield o(this,Xt).sendMessagePromise(W.getPeerInfo,pv.toBinary({peerId:e}));return ns.fromBinary(n.payload)})}}Xt=new WeakMap;var it;class oL{constructor(e){f(this,it,void 0),v(this,it,e)}addPlugin(e,n){o(this,it).sendMessage(z.addPlugin,s1.toBinary({pluginId:e,staggered:n}))}removePlugin(e){o(this,it).sendMessage(z.removePlugin,o1.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield o(this,it).sendMessagePromise(z.getPlugins);return e?A1.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,n,r){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(n))};o(this,it).sendMessage(z.customPluginEventToRoom,v1.toBinary(i),r)}customPluginEventToPeers(e,n,r,i){const s={pluginId:e,peerIds:n,pluginData:new TextEncoder().encode(JSON.stringify(r))};o(this,it).sendMessage(z.customPluginEventToPeers,S1.toBinary(s),i)}enablePluginForRoom(e,n){o(this,it).sendMessage(z.enablePluginForRoom,d1.toBinary({pluginId:e}),n)}enablePluginForPeers(e,n,r){o(this,it).sendMessage(z.enablePluginForPeers,p1.toBinary({pluginId:e,peerIds:n}),r)}disablePluginForRoom(e,n){o(this,it).sendMessage(z.disablePluginForRoom,u1.toBinary({pluginId:e}),n)}disablePluginForPeers(e,n,r){o(this,it).sendMessage(z.disablePluginForPeers,g1.toBinary({pluginId:e,peerIds:n}),r)}storeInsertKeys(e,n,r,i){const s={pluginId:e,storeName:n,insertKeys:r.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};o(this,it).sendMessage(z.storeInsertKeys,kv.toBinary(s),i)}storeGetKeys(e,n,r,i){const s={pluginId:e,storeName:n,getKeys:r.map(a=>({storeKey:a.key}))};o(this,it).sendMessage(z.storeGetKeys,b1.toBinary(s),i)}storeDeleteKeys(e,n,r,i){const s={pluginId:e,storeName:n,deleteKeys:r.map(a=>({storeKey:a.key}))};o(this,it).sendMessage(z.storeDeleteKeys,w1.toBinary(s),i)}storeDelete(e,n,r){o(this,it).sendMessage(z.storeDelete,C1.toBinary({pluginId:e,storeName:n}),r)}getPluginDataOld(e,n){p.info("getPluginDataOld",{plugin:{id:e,storeName:n}})}storePluginDataOld(e,n,r){const i={pluginId:e,storeName:n,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};o(this,it).sendMessage(z.storeInsertKeys,kv.toBinary(i))}on(e,n){let r;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{r=Ju.fromBinary.bind(Ju);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{r=bv.fromBinary.bind(bv);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{r=wv.fromBinary.bind(wv);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{r=_v.fromBinary.bind(_v);break}}o(this,it).on(e,({payload:i,id:s})=>{const a=r(i);return n(a,s)})}}it=new WeakMap;var cL=Object.defineProperty,dL=(t,e,n)=>e in t?cL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lL=(t,e,n)=>(dL(t,typeof e!="symbol"?e+"":e,n),n),Ep=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},L=(t,e,n)=>(Ep(t,e,"read from private field"),n?n.call(t):e.get(t)),Ce=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},me=(t,e,n,r)=>(Ep(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Ae=(t,e,n)=>(Ep(t,e,"access private method"),n),ul={},uL={get exports(){return ul},set exports(t){ul=t}},Ws=typeof Reflect=="object"?Reflect:null,iS=Ws&&typeof Ws.apply=="function"?Ws.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},hl;Ws&&typeof Ws.ownKeys=="function"?hl=Ws.ownKeys:Object.getOwnPropertySymbols?hl=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:hl=function(t){return Object.getOwnPropertyNames(t)};function hL(t){console&&console.warn&&console.warn(t)}var sS=Number.isNaN||function(t){return t!==t};function fe(){fe.init.call(this)}uL.exports=fe,ul.once=fL,fe.EventEmitter=fe,fe.prototype._events=void 0,fe.prototype._eventsCount=0,fe.prototype._maxListeners=void 0;var aS=10;function pl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(fe,"defaultMaxListeners",{enumerable:!0,get:function(){return aS},set:function(t){if(typeof t!="number"||t<0||sS(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");aS=t}}),fe.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},fe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||sS(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 oS(t){return t._maxListeners===void 0?fe.defaultMaxListeners:t._maxListeners}fe.prototype.getMaxListeners=function(){return oS(this)},fe.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var r=t==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[t];if(c===void 0)return!1;if(typeof c=="function")iS(c,this,e);else for(var d=c.length,l=hS(c,d),n=0;n<d;++n)iS(l[n],this,e);return!0};function cS(t,e,n,r){var i,s,a;if(pl(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),a=s[e]),a===void 0)a=s[e]=n,++t._eventsCount;else if(typeof a=="function"?a=s[e]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),i=oS(t),i>0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,hL(c)}return t}fe.prototype.addListener=function(t,e){return cS(this,t,e,!1)},fe.prototype.on=fe.prototype.addListener,fe.prototype.prependListener=function(t,e){return cS(this,t,e,!0)};function pL(){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 dS(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=pL.bind(r);return i.listener=n,r.wrapFn=i,i}fe.prototype.once=function(t,e){return pl(e),this.on(t,dS(this,t,e)),this},fe.prototype.prependOnceListener=function(t,e){return pl(e),this.prependListener(t,dS(this,t,e)),this},fe.prototype.removeListener=function(t,e){var n,r,i,s,a;if(pl(e),r=this._events,r===void 0)return this;if(n=r[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===e||n[s].listener===e){a=n[s].listener,i=s;break}if(i<0)return this;i===0?n.shift():mL(n,i),n.length===1&&(r[t]=n[0]),r.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this},fe.prototype.off=fe.prototype.removeListener,fe.prototype.removeAllListeners=function(t){var e,n,r;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var i=Object.keys(n),s;for(r=0;r<i.length;++r)s=i[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function lS(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?gL(i):hS(i,i.length)}fe.prototype.listeners=function(t){return lS(this,t,!0)},fe.prototype.rawListeners=function(t){return lS(this,t,!1)},fe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):uS.call(t,e)},fe.prototype.listenerCount=uS;function uS(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}fe.prototype.eventNames=function(){return this._eventsCount>0?hl(this._events):[]};function hS(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function mL(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function gL(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function fL(t,e){return new Promise(function(n,r){function i(a){t.removeListener(e,s),r(a)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}pS(t,e,s,{once:!0}),e!=="error"&&vL(t,i,{once:!0})})}function vL(t,e,n){typeof t.on=="function"&&pS(t,"error",e,n)}function pS(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class yL extends E{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 mS=new yL;class gS{static encode(e){return mS.toBinary(e)}static decode(e){return mS.fromBinary(new Uint8Array(e))}}function SL(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Br;class EL{constructor(e={}){lL(this,"opts"),Ce(this,Br,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},me(this,Br,0)}wait(){return u(this,null,function*(){me(this,Br,L(this,Br)+1);const e=SL(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*RE(2,L(this,Br))));yield new Promise(n=>{setTimeout(n,e)})})}getAttempts(){return L(this,Br)}reset(){me(this,Br,0)}}Br=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Wi,ji;class TL{constructor(e){Ce(this,Wi,void 0),Ce(this,ji,void 0),me(this,Wi,console),me(this,ji,e)}debug(...e){Wr[L(this,ji)]>Wr.debug||L(this,Wi).debug("[Sockrates]:",...e)}info(...e){Wr[L(this,ji)]>Wr.info||L(this,Wi).info("[Sockrates]:",...e)}warn(...e){Wr[L(this,ji)]>Wr.warn||L(this,Wi).warn("[Sockrates]:",...e)}error(...e){Wr[L(this,ji)]>Wr.error||L(this,Wi).error("[Sockrates]:",...e)}}Wi=new WeakMap,ji=new WeakMap;var fS=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(fS||{});const kL="2",bL="3";var xe,js,Me,He,jr,st,cr,Hr,wn,Hs,dr,Tp,vS,Do,ml,kp,yS,bp,SS,gl,_p,wp,ES,Oo,fl,No,vl,yl,Ip,qs,Lo,xo,Sl;class _L{constructor(e,n){var r;Ce(this,Tp),Ce(this,Do),Ce(this,kp),Ce(this,bp),Ce(this,gl),Ce(this,wp),Ce(this,Oo),Ce(this,No),Ce(this,yl),Ce(this,qs),Ce(this,xo),Ce(this,xe,void 0),Ce(this,js,void 0),Ce(this,Me,void 0),Ce(this,He,void 0),Ce(this,jr,void 0),Ce(this,st,void 0),Ce(this,cr,void 0),Ce(this,Hr,void 0),Ce(this,wn,void 0),Ce(this,Hs,void 0),Ce(this,dr,void 0);var i,s,a,c,d,l,h,m,y;me(this,js,e),me(this,jr,[]),me(this,st,new ul),me(this,cr,!0),me(this,wn,!1),me(this,Me,n!=null?n:{}),(i=L(this,Me)).autoReconnect!=null||(i.autoReconnect=!0),(s=L(this,Me)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(a=L(this,Me)).pingTimeout!=null||(a.pingTimeout=3e4),(c=L(this,Me)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=L(this,Me)).debug!=null||(d.debug=!0),(l=L(this,Me)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=L(this,Me)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=L(this,Me)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(y=L(this,Me)).flushOnReconnect!=null||(y.flushOnReconnect=!1),me(this,Hr,{code:void 0,reason:void 0}),me(this,He,(r=L(this,Me).logger)!=null?r:new TL(L(this,Me).debug?"debug":"info")),me(this,dr,new EL)}get readyState(){var e;return(e=L(this,xe))==null?void 0:e.readyState}get url(){return L(this,js)}updateURL(e){me(this,js,e),Ae(this,wp,ES).call(this)}get config(){return L(this,Me)}get sendQueue(){return L(this,jr)}flush(){if(!L(this,Me).queueOnDisconnect)return!1;const e=[];return L(this,jr).forEach(n=>{this.send(n.event,n.id,n.payload,n.metadata)||e.push(n)}),me(this,jr,e),L(this,jr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,He).debug("Websocket was already connecting or connected.");return}if(L(this,cr)!==!1)return new Promise((n,r)=>{Ae(this,qs,Lo).call(this),Ae(this,xo,Sl).call(this);try{me(this,xe,new WebSocket(Ae(this,Tp,vS).call(this,L(this,js)))),L(this,xe).binaryType="arraybuffer",L(this,He).debug("Connecting");const i=setTimeout(()=>{L(this,He).debug("Connection timeout. Closing socket"),me(this,cr,!0),Ae(this,xo,Sl).call(this),L(this,xe).close(3001,"Connection Timeout"),L(this,Me).autoReconnect&&!L(this,wn)&&(L(this,st).emit("reconnecting"),Ae(this,Oo,fl).call(this)),r(new Error("Connection timed out!"))},L(this,Me).connectionTimeout);L(this,xe).onopen=()=>{L(this,He).debug(`Ready State: ${fS[L(this,xe).readyState]}`),i&&clearTimeout(i),Ae(this,yl,Ip).call(this),me(this,Hr,{code:void 0,reason:void 0}),L(this,st).emit("connected"),L(this,Me).flushOnReconnect&&this.flush(),n()},L(this,xe).onclose=s=>{try{i&&clearTimeout(i);const{code:a,reason:c}=s;r(c),L(this,He).debug("Socket closed. Close event:",{event:s}),L(this,He).debug(`Connection closed code: ${a}`),L(this,He).debug(`Connection closed reason: ${c}`),L(this,wn)||Ae(this,gl,_p).call(this,a,c)}catch(a){Ae(this,Do,ml).call(this,a)}},L(this,xe).onerror=s=>{Ae(this,Do,ml).call(this,s)},L(this,xe).onmessage=s=>Ae(this,kp,yS).call(this,s)}catch(i){Ae(this,Do,ml).call(this,i,r)}})})}send(e,n,r,i){const s={event:e,id:n,payload:r,metadata:i};if(L(this,Me).queueOnDisconnect&&(!L(this,xe)||L(this,xe).readyState!==1))return L(this,He).debug("Queuing message since socket is not connected!",s),L(this,jr).push(s),!1;const a=gS.encode(s);return Ae(this,No,vl).call(this,a)}emit(e,n,r,i){return this.send(e,n,r,i)}sendRaw(e){return Ae(this,No,vl).call(this,e)}receive(e,n){return L(this,st).on(e.toString(),n)}on(e,n){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){L(this,st).on(e,n);return}this.receive(e,n)}removeAllListeners(){L(this,st).removeAllListeners()}removeReceiver(e,n){this.removeListener(e,n)}removeListener(e,n){L(this,st).removeListener(e.toString(),n)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,st).listeners(e.toString()).map(n=>this.removeListener(e,n))}disconnect(){me(this,cr,!1),Ae(this,qs,Lo).call(this),this.removeAllListeners(),me(this,Hr,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,xe).close(1e3,"Sockrates disconnect method called.")}}xe=new WeakMap,js=new WeakMap,Me=new WeakMap,He=new WeakMap,jr=new WeakMap,st=new WeakMap,cr=new WeakMap,Hr=new WeakMap,wn=new WeakMap,Hs=new WeakMap,dr=new WeakMap,Tp=new WeakSet,vS=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Do=new WeakSet,ml=function(t,e){L(this,He).error("Error:",{error:t}),L(this,st).emit("errored",{error:t}),e==null||e(t)},kp=new WeakSet,yS=function(t){if(Ae(this,yl,Ip).call(this),t.data===kL){L(this,He).debug("Received ping from server"),Ae(this,No,vl).call(this,bL);return}const e=gS.decode(t.data),{id:n,payload:r}=e;L(this,He).debug("Received message",{event:e.event,messageID:n}),L(this,st).emit(e.event.toString(),{id:n,payload:r})},bp=new WeakSet,SS=function(){return L(this,xe).readyState===1},gl=new WeakSet,_p=function(t,e){me(this,Hr,{reason:e,code:t}),L(this,st).emit("disconnected",{code:t,reason:e})},wp=new WeakSet,ES=function(){const{reason:t,code:e}=L(this,Hr);e&&e!==1e3&&L(this,cr)&&L(this,Me).autoReconnect&&!L(this,wn)&&(L(this,He).debug(`Triggering reconnection due to ${t}.`),L(this,st).emit("reconnecting"),Ae(this,Oo,fl).call(this))},Oo=new WeakSet,fl=function(t=!0){return u(this,null,function*(){if(t&&L(this,wn)){L(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,wn)||L(this,dr).reset(),L(this,Me).maxReconnectionAttempts!==null&&L(this,dr).getAttempts()>=L(this,Me).maxReconnectionAttempts){L(this,st).emit("failed"),me(this,wn,!1);return}me(this,wn,!0),Ae(this,xo,Sl).call(this),Ae(this,qs,Lo).call(this);try{if(yield L(this,dr).wait(),L(this,cr)===!1)return;if(L(this,He).debug(`Reconnection attempt ${L(this,dr).getAttempts()}`),L(this,st).emit("reconnectAttempt",{attempt:L(this,dr).getAttempts()}),yield this.connect(),!Ae(this,bp,SS).call(this))throw Error("Reconnect Failed");me(this,wn,!1),me(this,Hr,{code:void 0,reason:void 0}),L(this,st).emit("reconnected")}catch(e){L(this,He).debug("Failed to reconnect."),L(this,st).emit("reconnectFailure",{attempt:L(this,dr).getAttempts()}),Ae(this,Oo,fl).call(this,!1)}})},No=new WeakSet,vl=function(t){try{return L(this,xe).send(t),!0}catch(e){return L(this,He).error(e.message),!1}},yl=new WeakSet,Ip=function(){this.config.disconnectOnPingTimeout&&(L(this,He).debug("Resetting ping timeout"),Ae(this,qs,Lo).call(this),me(this,Hs,setTimeout(()=>{var t;L(this,He).debug("Disconnecting the socket due to ping timeout"),me(this,cr,!0);const e=3002,n="Ping timeout";(t=L(this,xe))==null||t.close(e,n),Ae(this,gl,_p).call(this,e,n)},L(this,Me).pingTimeout)))},qs=new WeakSet,Lo=function(){L(this,Hs)&&(clearTimeout(L(this,Hs)),me(this,Hs,void 0))},xo=new WeakSet,Sl=function(){L(this,xe)&&(L(this,xe).onopen=void 0,L(this,xe).onerror=void 0,L(this,xe).onmessage=void 0,L(this,xe).onclose=void 0)};var wL=Object.defineProperty,IL=Object.getOwnPropertyDescriptor,El=(t,e,n,r)=>{for(var i=r>1?void 0:r?IL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&wL(e,n,i),i};const TS=65535,CL=3e3;var Hi,Ve,Ue,qe,In,qr,Tl,Cp,kl,Pp,kS;const bS=(kS=class{constructor(t,{peerId:e,meetingId:n,authToken:r,capabilities:i}){f(this,Ue),f(this,Tl),f(this,kl),f(this,Hi,void 0),f(this,Ve,void 0),g(this,"roomName"),g(this,"authToken"),g(this,"capabilities"),f(this,In,void 0),f(this,qr,void 0);var s;if(!e||!n||!r)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,In,void 0),v(this,qr,t),this.capabilities=i,this.roomName=n,this.authToken=r,v(this,Hi,H(this,Tl,Cp).call(this,e)),v(this,Ve,new _L(o(this,Hi),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:p})),this.handleSocketConnectionEvents()}get joinAttempted(){return o(this,Ue,qe).socketJoinAttempted}set joinAttempted(t){o(this,Ue,qe).socketJoinAttempted=t}get peerId(){return o(this,qr).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,Hi,H(this,Tl,Cp).call(this,t)),p.debug("SocketService:: Connection URL updated.")),o(this,Ve).updateURL(o(this,Hi))}static getSocketEdgeDomain(t){return es({servicePrefix:"socket-edge",baseURI:t})}get url(){return o(this,Hi)}connect(){return u(this,null,function*(){o(this,Ue,qe).socketJoinAttempted=!0,yield o(this,Ve).connect(),o(this,Ue,qe).socketJoinAttempted=!0,o(this,Ue,qe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){o(this,Ue,qe).socketJoinAttempted=!1,o(this,Ve).disconnect(),o(this,Ue,qe).socketJoinAttempted=!0,o(this,Ue,qe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return o(this,Ve).readyState===1}catch(t){return!1}}sendMessage(t,e,n){const r={};return S.injectContext(r),o(this,Ve).send(t,n!=null?n:H(this,kl,Pp).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,n,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:n,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:n,messageId:r,resp:i}){const s=i!=null?i:t;return new Promise((a,c)=>{const d=(T,b)=>{o(this,Ve).removeListener(s,T),o(this,Ve).removeListener(TS,b),o(this,Ve).removeListener(en.errorResponse,b),o(this,Ve).removeListener(pn.errorResponse,b)},l=r!=null?r:H(this,kl,Pp).call(this),h={};S.injectContext(h);const m=({id:T,payload:b})=>{if(l===T){let O;try{const A=yP.fromBinary(b);O=new Error(A.errorMessage)}catch(A){O=new Error("failed to parse error message",{cause:A});try{const F=TR.fromBinary(b);O=new Error(F.message)}catch(F){O=new Error("failed to parse error message",{cause:F})}}c(O),d(y,m)}},y=({id:T,payload:b})=>{l===T&&(a({id:T,payload:b}),d(y,m))};o(this,Ve).on(s,y),o(this,Ve).on(TS,m),o(this,Ve).on(en.errorResponse,m),o(this,Ve).on(pn.errorResponse,m),setTimeout(()=>{d(y,m),c(new Error(`request timeout for callback eventId:${t}`))},e),o(this,Ve).send(t,l,n,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){o(this,Ve).on(t,e)}onStateEvent(t,e){o(this,Ve).on(t,e)}removeListener(t,e){o(this,Ve).removeListener(t,e)}removeListeners(t){o(this,Ve).removeListeners(t)}flush(){return o(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){p.info("SocketService::Connected to socket-edge"),o(this,In)&&(clearTimeout(o(this,In)),v(this,In,void 0)),o(this,Ue,qe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var n;p.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:r,send:i}=(n=o(this,Ue,qe).mediaState)!=null?n:{};r!=null&&r.state&&(r==null?void 0:r.state)!==Rr.CONNECTED||i!=null&&i.state&&(i==null?void 0:i.state)!==Rr.CONNECTED?P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ue,qe).joinAttempted}):v(this,In,setTimeout(()=>{P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ue,qe).joinAttempted}),v(this,In,void 0)},CL)),o(this,Ue,qe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){p.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),o(this,Ue,qe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){p.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),o(this,Ue,qe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{p.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),o(this,Ue,qe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){p.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:o(this,Ue,qe).mediaJoinAttempted}}),o(this,In)&&(clearTimeout(o(this,In)),v(this,In,void 0)),P.emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:o(this,Ue,qe).mediaJoinAttempted}),o(this,Ue,qe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){p.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),P.emit(R.SOCKET_SERVICE_FAILED),o(this,Ue,qe).updateSocketConnectionState("failed")}))}},Hi=new WeakMap,Ve=new WeakMap,Ue=new WeakSet,qe=function(){return o(this,qr).getValue("connectionHandler")},In=new WeakMap,qr=new WeakMap,Tl=new WeakSet,Cp=function(t){let e=bS.getSocketEdgeDomain(o(this,qr).getValue("baseURI"));typeof Jc(o(this,qr),"socket_server_base")=="string"&&(e=Jc(o(this,qr),"socket_server_base"));const n=`wss://${e}`,r=new URL(`${n}/ws`),i=this.peerId,s=G(x({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Qc[a]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(s).forEach(([a,c])=>{r.searchParams.append(a,c.toString())}),r.href},kl=new WeakSet,Pp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},kS);let Vo=bS;El([S.trace("SocketService.connect")],Vo.prototype,"connect",1),El([S.trace("SocketService.disconnect")],Vo.prototype,"disconnect",1),El([S.trace("SocketService.sendMessagePromise")],Vo.prototype,"sendMessagePromise",1),El([S.trace("SocketService.sendMessagePromiseWithTimeout")],Vo.prototype,"sendMessagePromiseWithTimeout",1);const qi=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const n=KR.fromBinary(t),r=n.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:n.parentMeeting.id,title:n.parentMeeting.title,participants:(e=n.parentMeeting.participants)!=null?e:[]},meetings:r}}static handleTransferPeerRaw({payload:t}){const e=EA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=fv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return gv.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return lA.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield qi.socketService.sendMessagePromise(W.getConnectedRoomsDump);return qi.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield qi.socketService.sendMessagePromise(W.createConnectedRooms,XR.toBinary({payloads:t}));return gv.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(r=>({id:r})),n=yield qi.socketService.sendMessagePromise(W.deleteConnectedRooms,cA.toBinary({payloads:e}));return qi.handleConnectedRoomsDeletedRaw(n)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield qi.socketService.sendMessagePromise(W.movePeers,fA.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=qi;g(Ne,"socketService"),g(Ne,"currentMeetingId");var PL=Object.defineProperty,RL=Object.getOwnPropertyDescriptor,bl=(t,e,n,r)=>{for(var i=r>1?void 0:r?RL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&PL(e,n,i),i};const Gs=class{constructor(t,e){g(this,"apiBase"),g(this,"selfController"),g(this,"pollController"),g(this,"chatController"),g(this,"metaController"),g(this,"storesManager"),g(this,"stageController"),g(this,"pluginController"),g(this,"internalsController"),g(this,"recordingController"),g(this,"livestreamController"),g(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){var e,n;const{peerId:r,apiBase:i,authToken:s,meetingId:a,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(P.reset(),Nd.cleanup(),tS(t),Ie.isSupported()===!1)throw new w("Browser not supported","0010",!0);const l=OD(t,{authToken:s,baseURL:i,cachedUserDetails:d});l.setRoomName(a),l.setRoomUUID(a),l.setOrganizationId(c),l.setHeader("dyte-tracing-id",r),t.setValue("apiClient",l);const h=new gO;t.setValue("connectionHandler",h);const m=Gs.createSocketService(t),y=m.connect(),T=l.getUserDetails(),b=l.getPlugins();let O=tt.HIVE,A,F="";try{yield Gs.setupFlagsmith(t)}catch(Z){p.error("Failed to setup flagsmith",{error:Z})}try{yield y}catch(Z){p.error("[Controller]: Failed to connect to socket server:",{error:Z})}try{({sfu:O,meetingTitle:F}=yield l.getRoomNodeData()),A=yield T,p.info(`SFU ${O} is being used.`),t.setValue("presetName",A.preset.name),t.setValue("roomNodeOptions",{sfu:O})}catch(Z){p.error("Failed to get room metadata",{error:Z})}const V=ZO.init(A.preset,!t.getValue("modules").theme),K=Gs.setupControllers(m,t,A,b,F,V);iO(V)&&((e=Gs.createRoomNodeClient(t,m).partialJoinRoom(A.participant.name,a,void 0))==null||e.catch(Z=>{p.error("[Controller]: Failed to queue partial media room promise:",{error:Z})})),S.location.country=(n=l.ipInfo)==null?void 0:n.country;const{controllers:I}=yield K;return nC(),new Gs(i,I)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:n,baseURI:r,overrides:i,meetingId:s,organizationId:a}=t.getAllValues(),c=eC(s),d=G(x({entity:Au.PEER,clientId:a,isAnonUser:!a,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const l=(e=i==null?void 0:i.whitelabelled_flags_endpoint)==null||e?es({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield Q.identify(`${Au.PEER}_${n}`,JSON.parse(JSON.stringify(d)),!1,5e3,l,p),p.info("flagsmith::allFlags",{flags:JSON.stringify(Q.getAllFlags())},!0)}catch(l){p.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,n,r,i,s){return u(this,null,function*(){var a,c,d;const l=e.getValue("modules"),{preset:h,participant:m}=n,y=e.getValue("defaults"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:O}}=s;e.setValue("viewType",b),e.setValue("defaults",x({mediaConfiguration:{audio:{enableHighBitrate:(a=O.enableHighBitrate)!=null?a:!1,enableStereo:(c=O.enableStereo)!=null?c:!1}}},y));const A=EN.init(e,b,h.permissions);e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let F,V,K,I,Z,ae,_e,ce;const De=new rL(t);Ne.socketService=t;const Mt=new ll(t),M=new tn(t),k=new aL(t),_=Nd.create(t,e),j=new oL(t),Pe=new nL(t),Qe=new ci(t),B=yield Ur.init(e,_,m,A,s),C=yield zv.init(e,B.self,_,De,i);if(l.participant&&(ce=new rr(e,B.self,_,T)),(d=l.e2ee)!=null&&d.enabled&&l.e2ee.manager.init(p,P),l.chat&&(V=yield Zn.init(e,M,Qe,B.self,ce.participants)),l.internals&&(Z=yield ph.init()),l.livestream&&s.viewType===yt.Livestream&&Q.hasFeature(ie.LIVESTREAM)&&(_e=new py(B.self,Pe)),s.viewType!==yt.Chat){if(l.poll&&(F=yield Hv.init(e,B.self,Mt)),l.recording&&(ae=new ry(e,B.self,_)),l.stage&&(K=new Yv(e,k,_,B.self,ce.participants)),l.plugin){if(!ce)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const lr=yield r;I=yield _a.init(e,lr,j,M,V==null?void 0:V.chat,B.self,ce.participants,i)}if(l.pip){const lr=yield sC._init(e,B.self);e.setValue("pip",lr)}}const Xe={storesManager:new oN(e,j),pollController:F,selfController:B,metaController:C,chatController:V,stageController:K,pluginController:I,recordingController:ae,internalsController:Z,livestreamController:_e,participantController:ce};return{theme:s,permissions:A,controllers:Xe}})}static createRoomNodeClient(t,e){const{peerId:n,roomNodeOptions:r}=t.getAllValues(),{sfu:i}=r;return eS(t,i,{socket:e,peerId:n})}static createSocketService(t){const{peerId:e,meetingId:n,authToken:r}=t.getAllValues(),i=["PING"];return new Vo(t,{peerId:e,meetingId:n,authToken:r,capabilities:i})}};let Uo=Gs;bl([S.trace("Controller.init")],Uo,"init",1),bl([S.trace("setupFlagsmith")],Uo,"setupFlagsmith",1),bl([S.trace("Controller.createRoomNodeClient")],Uo,"createRoomNodeClient",1),bl([S.trace("Controller.createSocketService")],Uo,"createSocketService",1);var AL=Object.defineProperty,ML=Object.getOwnPropertyDescriptor,DL=(t,e,n,r)=>{for(var i=r>1?void 0:r?ML(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&AL(e,n,i),i},_l,Rp;class _S extends jt{constructor(e,n){super(),f(this,_l,void 0),g(this,"meetings",[]),g(this,"parentMeeting",null),f(this,Rp,void 0),v(this,Rp,e),v(this,_l,n.self)}get supportsConnectedMeetings(){return o(this,_l).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
22
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(n=>({id:n.id,title:n.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(n=>({meetingId:n.id,title:n.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(n),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,n,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:r.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,n,r),i})}moveParticipantsWithCustomPreset(e,n,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:r});return i.success&&this.moveSuccessHandler(e,n,r.map(s=>s.id)),i})}moveSuccessHandler(e,n,r){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),n===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(n===s.id){const a=s.participants.concat(r.map(c=>i.get(c)));return G(x({},s),{participants:a})}if(e===s.id){const a=s.participants.filter(c=>!r.includes(c.id));return G(x({},s),{participants:a})}return s})}}_l=new WeakMap,Rp=new WeakMap,DL([Nt({maxInvocations:60,period:60})],_S.prototype,"getConnectedMeetings",1);var OL=Object.defineProperty,NL=Object.getOwnPropertyDescriptor,Ap=(t,e,n,r)=>{for(var i=r>1?void 0:r?NL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&OL(e,n,i),i},Fo,Cn,Mp,Dp;const Gr=(Mp=class{constructor(t,e,n){g(this,"connectedMeetings"),f(this,Fo,void 0),f(this,Cn,void 0),f(this,Dp,void 0),v(this,Dp,t),v(this,Fo,n),this.connectedMeetings=new _S(t,e),this.setCurrentMeeting(e)}static init(t,e,n){return Gr.instance||(Gr.instance=new Gr(t,e,n)),Gr.instance.connectedMeetings.supportsConnectedMeetings&&(Gr.instance.setupEvents(),e.self.once("roomJoined",()=>Gr.instance.getConnectedMeetings())),Gr.instance}setCurrentMeeting(t){v(this,Cn,t),Ne.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(W.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(W.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(W.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(W.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(W.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:n}){var r,i,s,a;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
23
23
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);p.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",n);const c={video:o(this,Cn).self.videoEnabled,audio:o(this,Cn).self.audioEnabled};try{o(this,Cn).self.cleanupEvents(),yield o(this,Cn).leave("connected-meeting")}catch(l){p.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(i=(r=o(this,Cn))==null?void 0:r.meta)==null?void 0:i.meetingId}`,{error:l})}Ne.socketService=void 0,p.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${n}`);const d=yield PS.init(G(x({},o(this,Fo)),{cachedUserDetails:null,defaults:G(x(x({},o(this,Fo).defaults),c),{mediaHandler:o(this,Cn).self}),authToken:e}));p.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=o(this,Cn).self;d.self.setName(o(this,Cn).self.name),yield d.join(),l&&d.self.hide()}catch(l){p.error("ConnectedMeetingsController.joinRoom",{error:l})}return p.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(a=d==null?void 0:d.meta)==null?void 0:a.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(n=>({id:n.id,title:n.title,participants:n.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),n=new Map;this.connectedMeetings.meetings.forEach(r=>{n.set(r.id,r)}),e.forEach(r=>{n.has(r.id)?n.get(r.id).title=r.title:n.set(r.id,G(x({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(n.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.handleConnectedRoomsDeletedRaw(t).map(n=>n.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(n=>!e.includes(n.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Fo=new WeakMap,Cn=new WeakMap,Dp=new WeakMap,g(Mp,"instance"),Mp);let wl=Gr;Ap([S.trace("ConnectedMeetingsController.getConnectedMeetings")],wl.prototype,"getConnectedMeetings",1),Ap([S.trace("ConnectedMeetingsController.setupEvents")],wl.prototype,"setupEvents",1),Ap([S.trace("ConnectedMeetingsController.switchMeeting")],wl.prototype,"switchMeeting",1);class LL{constructor(){g(this,"battery"),g(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){p.error("Error getting battery",e)}})),g(this,"updateChargeInfo",()=>{var e;p.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),g(this,"updateLevelInfo",()=>{if(!this.battery){p.log("Battery level: Not known");return}p.log(`Battery level: ${this.battery.level*100}%`)}),g(this,"cleanup",()=>{var e,n;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(n=this.battery)==null||n.removeEventListener("levelchange",this.updateLevelInfo))})}}const wS=new LL;function xL(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:n,orgId:r,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!n)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const a=`https://api.${s}`;return{meetingId:n,orgId:r,participantId:i,baseURI:s,apiBase:a}}catch(n){throw p.error("constants::decodeAuthToken",{error:n,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var VL=Object.defineProperty,UL=Object.getOwnPropertyDescriptor,Il=(t,e,n,r)=>{for(var i=r>1?void 0:r?UL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&VL(e,n,i),i},dt,Cl,Pl,Op,IS,CS;let Jr=(CS=class{constructor(t,e){f(this,Op),f(this,dt,void 0),f(this,Cl,void 0),f(this,Pl,void 0),v(this,Pl,t),v(this,dt,e)}static init(t){return u(this,null,function*(){var e,n,r,i,s,a,c;QI(),Ie.init();const d=(n=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?n:Gi();wS.init();const{authToken:l,baseURI:h}=t,m=xL(l,h),{meetingId:y}=m,T=gc(m,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Jr.setupContext(d,t,y,T);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=T.participantId,S.meetingMetadata.organizationId=T.orgId,S.init(b,(i=(r=t.modules)==null?void 0:r.tracing)!=null?i:!0),p.info("DyteClient::init::options",{dyteClientInitOptions:G(x({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
24
- ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const O=yield Uo.init(b),A=new Jr(b,O);return H(c=A,Op,IS).call(c,t),A})}static setupContext(t,e,n,r){var i;const s=ri.createContext(t,e),a=x(x({},GI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",r.apiBase),s.setValue("baseURI",r.baseURI),s.setValue("userId",r.participantId),s.setValue("organizationId",r.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",JI({baseURI:r.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",gn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.91"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,dt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){wS.cleanup();const{selfController:e}=o(this,dt);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,dt).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,dt).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,dt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,dt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,dt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,dt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,dt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,Cl))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,dt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,dt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,dt).stageController)==null?void 0:t.stage}get stores(){return o(this,dt).storesManager}get __internals__(){var t;return(t=o(this,dt).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)})}},dt=new WeakMap,Cl=new WeakMap,Pl=new WeakMap,Op=new WeakSet,IS=function(t){v(this,Cl,wl.init(o(this,Pl),this,t))},CS);Il([ht("0002"),Ar.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Jr.prototype,"join",1),Il([ht("0003")],Jr.prototype,"leave",1),Il([ht("0001"),Ar.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Jr,"init",1),Jr=Il([ht("0000")],Jr);const PS=Jr;return PS}();
24
+ ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const O=yield Uo.init(b),A=new Jr(b,O);return H(c=A,Op,IS).call(c,t),A})}static setupContext(t,e,n,r){var i;const s=ri.createContext(t,e),a=x(x({},GI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",r.apiBase),s.setValue("baseURI",r.baseURI),s.setValue("userId",r.participantId),s.setValue("organizationId",r.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",JI({baseURI:r.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",gn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.92"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,dt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){wS.cleanup();const{selfController:e}=o(this,dt);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,dt).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,dt).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,dt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,dt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,dt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,dt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,dt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,Cl))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,dt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,dt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,dt).stageController)==null?void 0:t.stage}get stores(){return o(this,dt).storesManager}get __internals__(){var t;return(t=o(this,dt).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)})}},dt=new WeakMap,Cl=new WeakMap,Pl=new WeakMap,Op=new WeakSet,IS=function(t){v(this,Cl,wl.init(o(this,Pl),this,t))},CS);Il([ht("0002"),Ar.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Jr.prototype,"join",1),Il([ht("0003")],Jr.prototype,"leave",1),Il([ht("0001"),Ar.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Jr,"init",1),Jr=Il([ht("0000")],Jr);const PS=Jr;return PS}();
package/dist/index.cjs.js CHANGED
@@ -22,4 +22,4 @@ ${t}`}const Hs={maxInvocations:5,period:1};function Ft(t,e){return function(n,r,
22
22
  maxEnergy: ${o(this,pi)}`),i===-1/0||n<1e-6?{energy:0,isVoice:!1}:((!o(this,wr)||i<o(this,wr))&&v(this,wr,i),(!o(this,pi)||i>o(this,pi))&&v(this,pi,i),{energy:(i-o(this,wr))/(o(this,pi)-o(this,wr))*10||0,isVoice:r})},ld=new WeakSet,Vh=function(t){return t<5},Uh=new WeakSet,oS=function(t=o(this,Os)){var e;if(!o(this,Vn)||!t){Q.hasFeature(ie.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&p.debug(`AudioActivityReporter: No producerId or energy to report: ${o(this,Vn)}`);return}const n={producerId:o(this,Vn),energy:Math.round(t),silent:H(e=zd,ld,Vh).call(e,t)};v(this,Oo,n.silent),this.reportRequest(n)},ku=new WeakSet,af=function(t){const e=Math.log10(t);return Math.round(e)},f(Fh,ld),f(Fh,ku);const tL=()=>{const t=new window.AudioContext,e=t.createOscillator();e.type="triangle",e.frequency.setValueAtTime(20,t.currentTime);const n=t.createGain();n.gain.setValueAtTime(0,t.currentTime),e.connect(n);const r=t.createMediaStreamDestination();return n.connect(r),e.start(),r.stream.getAudioTracks()[0]},nL=()=>{var t,e;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(t=n==null?void 0:n.getSettings().height)!=null?t:720,r.width=(e=n==null?void 0:n.getSettings().width)!=null?e:1280;const i=r.getContext("2d");return i.fillStyle="black",i.fillRect(0,0,r.width,r.height),setInterval(()=>{i.fillStyle="black",i.fillRect(0,0,r.width,r.height)},1e3),r.captureStream().getVideoTracks()[0]};var rL=Object.defineProperty,iL=Object.getOwnPropertyDescriptor,he=(t,e,n,r)=>{for(var i=r>1?void 0:r?iL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&rL(e,n,i),i};const Pn=["video/VP9","video/VP8"];var ud,hd,bt,$,go,mi,Lt,fs,vs,gi,pd,Ir,fo,ys,Ss,xt,Gt,fi,Es,ht,_t,Ts,vo,Bh,cS,Wh,dS,jh,lS;class ue{constructor(e,n,r){f(this,fi),f(this,ht),f(this,Ts),f(this,Bh),f(this,Wh),f(this,jh),g(this,"context"),g(this,"authToken"),g(this,"e2ee"),f(this,ud,void 0),f(this,hd,void 0),f(this,bt,void 0),f(this,$,void 0),f(this,go,void 0),f(this,mi,void 0),f(this,Lt,void 0),f(this,fs,void 0),f(this,vs,void 0),f(this,gi,void 0),f(this,pd,void 0),f(this,Ir,void 0),f(this,fo,void 0),f(this,ys,void 0),f(this,Ss,void 0),f(this,xt,void 0),f(this,Gt,void 0),g(this,"partialJoinRoomPromise");var i,s;this.context=e;const{socket:a}=r;this.mediaJoined=!1,v(this,ys,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Ss,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,mi,n),v(this,bt,a),v(this,fs,!1),v(this,$,new XN(e,a,n)),v(this,Lt,o(this,$).events),v(this,Ir,new Set),v(this,xt,new Map),v(this,vs,!1),v(this,gi,new jd),n===rt.CF&&v(this,Gt,new Fh(o(this,$).socketHandler.audioActivity.bind(o(this,$).socketHandler))),this.e2ee=(s=(i=e.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,pd,Nd(()=>u(this,null,function*(){if(!o(this,fi,Es).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(o(this,hd),o(this,ud),{},!0,!0);c&&(P.emit(R.RESET_PRODUCER_STATE),P.emit(R.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return o(this,fi,Es).mediaJoined}set mediaJoined(e){o(this,fi,Es).mediaJoined=e}reset(e=!0){o(this,$).closeAllProducers(),o(this,$).closeAllConsumers(),o(this,xt).clear(),o(this,Ir).clear(),e&&(this.partialJoinRoomPromise=void 0,o(this,gi).stop(),o(this,$).stopAllTransports(),o(this,$).reset(),v(this,gi,new jd))}joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=!1){o(this,fi,Es).mediaJoinAttempted=!0,v(this,fs,!0),this.reset(a);const d=dt().ipInfo;if(d!=null&&d.loc&&!o(this,fo)){const h=d.loc.split(",");v(this,fo,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let l;try{return l=yield o(this,gi).push(()=>this._joinRoom(r,i,s,c,o(this,fo)),"joinRoom"),l}catch{l={roomJoined:!1}}return l.roomJoined||P.emit(R.ROOM_NODE_FAILED),l})}_partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){var s;const{ipInfo:a}=dt();let c=i;if(a!=null&&a.loc&&!i){const[h,m]=a.loc.split(",").map(parseFloat);c={latitude:h,longitude:m}}const d=(s=Q.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:s.toString(),l=UN(d);v(this,go,l),yield Cp((h,m)=>u(this,null,function*(){if(!o(this,bt).isConnected){m(new Error("socket is not connected"));return}h>0&&p.warn(`retrying sending join room request, count: ${h}`);try{yield o(this,$).socketHandler.joinRoom(n,e,l,r,c)}catch(y){throw p.error("failed to send join room request, error:",{error:y}),y}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield o(this,$).setupTransports({send:!0,recv:!0}),o(this,mi)!==rt.HIVE&&Q.hasFeature(ie.PRECREATE_PRODUCERS)&&(this.shareWebcam(nL()),this.shareMic(tL()))})}partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){return this.partialJoinRoomPromise=o(this,gi).push(()=>this._partialJoinRoom(e,n,r,i)),this.partialJoinRoomPromise})}_joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=null){v(this,hd,r);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,i,a,c)}catch(d){p.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:i,roomViewType:"groupCall",deviceInfo:G(x({},Pe.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};K.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return p.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:e}=yield o(this,$).socketHandler.notifySelfJoinComplete();return v(this,ud,e.roomUuid),v(this,vs,!0),v(this,fs,!1),!0}catch(e){return p.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){o(this,$).stopAllTransports(),v(this,vs,!1),o(this,fi,Es).mediaJoinAttempted=!1;const e={closeRoom:!1};o(this,bt).sendMessagePromise(o(this,Lt).leaveRoom,zC.toBinary(e)).then(n=>{var r;(r=NP.fromBinary(n.payload))!=null&&r.closed||p.warn("weird state on peer closed and should not happen")}).catch(n=>{p.error("error on sending leave room request",{error:n})}),K.callEnded(),S.destruct()})}getConsumers(){return o(this,$).consumers}activatePeers(e){return u(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,n="default"){return u(this,null,function*(){const r=new Set;e.forEach(s=>{s.screenShare&&s.kind==="video"&&r.add(s.producingPeerId)});const i=n==="default"?e.filter(s=>!r.has(s.producingPeerId)).filter(s=>s.kind!=="audio"):e;yield Promise.all(i.map(s=>{const a=o(this,$).producerIdToConsumerIdMap.get(s.producerId);if(!a){p.warn(`consumer not found in deactivate producers: ${s.producerId}`);return}return o(this,$).closeConsumer(a)}))})}createConsumers(e){return u(this,null,function*(){return e.length===0?Promise.resolve():o(this,$).createConsumers(e)})}closeConsumers(e){return u(this,null,function*(){if(!e.length)return;const n=e.reduce((r,i)=>{const s=o(this,$).producerIdToConsumerIdMap.get(i.producerId);return s?(r.push(s),r):(p.warn(`consumer not found in deactivate producers: ${i.producerId}`),r)},[]);yield o(this,$).closeConsumers(n)})}_shareWebcam(e,n){return u(this,null,function*(){const r=n==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=H(this,ht,_t).call(this,r);if(i){const h=yield i;if(o(this,$).producers.has(h)){const m=o(this,$).producers.get(h);if(!m.closed&&!navigator.isReactNative)return yield m.replaceTrack({track:e}),yield this.resumeWebcam(r),e;yield this.disableWebcam(n)}return this._shareWebcam(e,n)}const s=H(this,jh,lS).call(this,e,n),a=xd(this.context,"disableSimulcast"),c=o(this,mi)===rt.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!a&&Q.hasFeature(c)?(p.info(`Simulcast enabled for SFU: ${o(this,mi)}`),s.encodings=NO(e)):p.info(`Simulcast disabled for webcam producer, SFU: ${o(this,mi)}`),Q.hasFeature(ie.TRACK_HINT)&&(s.track.contentHint=Q.getValue(ie.TRACK_HINT));const d=()=>{p.info("Disabling video due to the producer closure"),o(this,xt).delete(r)},l=o(this,$).createProducer(s,d);return H(this,Ts,vo).call(this,r,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(e){return u(this,null,function*(){if(e===void 0)return null;if(Q.hasFeature(ie.FORCE_VIDEO_CODEC)){const n=Q.getValue(ie.FORCE_VIDEO_CODEC).toString();if(n)return p.debug(`Calling _shareWebcam with forced video codec: ${n}`),this._shareWebcam(e,n)}return yield Promise.all(Pn.map(n=>{var r,i;return((i=(r=o(this,go).sender)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===n))>=0&&o(this,Ss).get(n).size>0?(p.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(e,n)):e})),e})}shareScreen(e){return u(this,null,function*(){const{video:n,audio:r}=e;if(n===void 0)return;const i={track:n,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1},s=()=>{p.info("Disabling screenShare due to the producer closure"),o(this,xt).delete(ke.SCREENSHARE_VIDEO),o(this,xt).delete(ke.SCREENSHARE_AUDIO)},a=o(this,$).createProducer(i,s);H(this,Ts,vo).call(this,ke.SCREENSHARE_VIDEO,a.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},l=()=>{};c=o(this,$).createProducer(d,l),H(this,Ts,vo).call(this,ke.SCREENSHARE_AUDIO,c.then(h=>h.id))}yield Promise.all([a,c||Promise.resolve()]),K.screenShareStart()})}shareMic(e){return u(this,null,function*(){try{if(e===void 0)throw new Vt("track undefined");const n=H(this,ht,_t).call(this,ke.MIC);if(n){const a=yield n;if(o(this,$).producers.has(a)){const c=o(this,$).producers.get(a);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),o(this,Gt)&&(o(this,Gt).audioTrack=e,o(this,Gt).producerId=a,o(this,Gt).start());return}yield o(this,$).closeProducer(a,{stopTrack:!1})}yield this.shareMic(e);return}const r=H(this,Wh,dS).call(this,e),i=()=>{o(this,xt).delete(ke.MIC)},s=o(this,$).createProducer(r,i);H(this,Ts,vo).call(this,ke.MIC,s.then(a=>a.id)),yield s.then(a=>{o(this,Gt)&&(o(this,Gt).audioTrack=a.track,o(this,Gt).producerId=a.id,o(this,Gt).start())})}catch(n){throw new w(n)}})}pauseMic(){return u(this,null,function*(){var e;const n=yield H(this,ht,_t).call(this,ke.MIC),r=o(this,$).producers.get(n);if(!r){p.error("pauseMic::could_not_find_mic_producer");return}if(r.paused){p.info("pauseMic::mic_producer_already_paused");return}r.pause(),(e=o(this,Gt))==null||e.stop();const i={producerId:r.id,pause:!0};o(this,bt).sendMessage(o(this,Lt).toggleProducer,dc.toBinary(i))})}pauseWebcam(){return u(this,null,function*(){const e=yield H(this,ht,_t).call(this,ke.WEBCAM),n=yield H(this,ht,_t).call(this,ke.WEBCAM_BACKUP),r=o(this,$).producers.get(e),i=o(this,$).producers.get(n);if(!r&&!i){p.error("pauseWebcam::could_not_find_webcam_producer");return}const s=a=>{const c={producerId:a.id,pause:!0};o(this,bt).sendMessage(o(this,Lt).toggleProducer,dc.toBinary(c))};r&&(r.pause(),s(r)),i&&(i.pause(),s(i))})}resumeMic(){return u(this,null,function*(){const e=yield H(this,ht,_t).call(this,ke.MIC),n=o(this,$).producers.get(e);if(!n){p.error("resumeMic::could_not_find_mic_producer");return}if(!n.pause){p.info("resumeMic::mic_producer_already_resumed");return}n.resume(),n.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,n);const r={producerId:n.id,pause:!1};o(this,bt).sendMessage(o(this,Lt).toggleProducer,dc.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(e=ke.WEBCAM){const n=yield H(this,ht,_t).call(this,e),r=o(this,$).producers.get(n);if(!r){p.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){p.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};o(this,bt).sendMessage(o(this,Lt).toggleProducer,dc.toBinary(i))})}disableWebcam(e){return u(this,null,function*(){const n=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,r=yield H(this,ht,_t).call(this,n);H(this,Bh,cS).call(this,n),r&&(yield o(this,$).closeProducer(r))})}disableMic(){return u(this,null,function*(){var e;const n=yield H(this,ht,_t).call(this,ke.MIC);n&&(yield o(this,$).closeProducer(n)),(e=o(this,Gt))==null||e.stop(),o(this,xt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){p.info("screen_sharing_stopped"),K.screenShareStop();const e=yield H(this,ht,_t).call(this,ke.SCREENSHARE_VIDEO),n=yield H(this,ht,_t).call(this,ke.SCREENSHARE_AUDIO);e&&(yield o(this,$).closeProducer(e)),n&&(yield o(this,$).closeProducer(n)),o(this,Ir).clear(),o(this,xt).delete(ke.SCREENSHARE_VIDEO),o(this,xt).delete(ke.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(e,n){return u(this,null,function*(){if(e){const r=yield H(this,ht,_t).call(this,ke.WEBCAM),i=yield H(this,ht,_t).call(this,ke.WEBCAM_BACKUP);yield o(this,$).closeProducer(r,{stopTrack:!1}),yield o(this,$).closeProducer(i,{stopTrack:!1}),this.shareWebcam(e)}if(n){const r=yield H(this,ht,_t).call(this,ke.SCREENSHARE_VIDEO);yield o(this,$).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:n})}})}changeDisplayName(e,n){return u(this,null,function*(){const r={displayName:e,participantId:n!=null?n:this.peerId};if(!(yield o(this,$).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(e){return u(this,null,function*(){const n={participantId:e};if(!(yield o(this,$).socketHandler.kickPeer(n)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return u(this,null,function*(){const n={participantId:e!=null?e:""};try{yield o(this,bt).sendMessagePromise(o(this,Lt).globalPinPeer,sP.toBinary(n))}catch(r){p.error("Error in pinning peer:",{error:r})}})}validateScreenShare(e){return this.peerId===e.peerId&&o(this,$).producers.get(e.producerId)&&o(this,Ir).add(e.consumerPeerId),o(this,Ir).size}switchConsumersToLayer(e,n){return u(this,null,function*(){o(this,$).switchConsumersToLayer(e,n)})}handleSocketEvents(){return u(this,null,function*(){o(this,bt).on(o(this,Lt).peerProducerCreateBroadcast,({payload:e})=>{var n,r;if(this.mediaJoined)try{const{participantId:i,producerState:s}=hR.fromBinary(e);if(i===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===Un.AUDIO?"audio/opus":"video/VP8"),s.kind===Un.VIDEO&&!s.screenShare&&((r=(n=o(this,go).receiver)==null?void 0:n.video)==null?void 0:r.codecs.findIndex(a=>a.mimeType===Pn[0]))>=0&&o(this,ys).get(Pn[0]).has(i)&&s.mimeType!==Pn[0]){p.warn(`Ignoring producer: ${s.producerId}`);return}p.info(`producer created broadcast: ${i}, producer state: ${s}`),P.emit(R.NEW_PRODUCER,{peerId:i,producer:G(x({},s),{kind:s.kind===Un.AUDIO?"audio":"video",producingPeerId:i})})}catch(i){p.error("error in peer-producer-create-broadcast",{error:i})}}),o(this,bt).on(o(this,Lt).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,initiatorParticipantId:r,producerState:{kind:i,pause:s,producerId:a}}=ug.fromBinary(e),c=i===Un.AUDIO?"audio":"video";if(p.info(`producer toggle broadcast: ${n}, producerId: ${a}, kind:${c}, paused:${s} payload: ${JSON.stringify(ug.fromBinary(e))}`),n===this.peerId&&r!==this.peerId&&s&&P.emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),n===this.peerId)return;P.emit(R.PRODUCER_TOGGLE,{peerId:n,producerId:a,paused:s,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===a).forEach(d=>{d.paused!==s&&(p.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${s}`),s?(d.pause(),P.emit(R.CONSUMER_PAUSED,{id:d.id})):(d.resume(),P.emit(R.CONSUMER_RESUMED,{id:d.id})))})}catch(n){p.error("error in producer toggle broadcast handler",{error:n})}}),o(this,bt).on(o(this,Lt).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n}=Ju.fromBinary(e);if(n===this.peerId)return;p.info(`peer left broadcast:${n}`),o(this,Ir).delete(n),o(this,$).consumers.forEach(r=>{r.peerId===n&&r.close()}),P.emit(R.PEER_CLOSED,{id:n})}catch(n){p.error("error in peer left broadcast",{error:n})}}),o(this,bt).on(o(this,Lt).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,producerState:{producerId:r}}=gR.fromBinary(e);if(n===this.peerId)return;p.info(`producer closed broadcast:${n}`),P.emit(R.PRODUCER_CLOSED,{peerId:n,producerId:r});const i=o(this,$).producerIdToConsumerIdMap.get(r);if(!i){p.warn(`no consumer found for producer:${r}`);return}p.info(`closing consumer ${i}, producer id: ${r}`),o(this,$).closeConsumer(i).then(()=>{p.info(`closed consumer: ${i}`),o(this,$).producerIdToConsumerIdMap.delete(r),P.emit(R.CONSUMER_CLOSED,{id:i})}).catch(s=>{p.error("error closing consumer",{error:s})})}catch(n){p.error("error on producer close broadcast",{error:n})}}),o(this,bt).on(o(this,Lt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!o(this,fs)&&!o(this,vs)||(p.warn("media hub termination broadcast received, rejoining room"),P.emit(R.ROOM_NODE_DISCONNECTED),o(this,pd).call(this))})})}handleCallstatsEvents(){K.onConsumerScore(e=>{e.forEach((n,r)=>{const i=o(this,$).consumers.get(r);i&&P.emit(R.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:n.score,scoreStats:n})})}),K.onProducerScore(e=>{e.forEach((n,r)=>{const i=Array.from(o(this,$).producers.values()).find(s=>s.id===r);i&&P.emit(R.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:n.score,scoreStats:n})})})}handlePeerCapabilities(e,n){var r,i,s,a;for(let c=0;c<=Pn.length;c+=1){const d=Pn[c];if(((i=(r=n==null?void 0:n.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(l=>l.mimeType===d))>=0||c===Pn.length-1){o(this,Ss).get(d).add(e);break}}for(let c=0;c<=Pn.length;c+=1){const d=Pn[c];if(((a=(s=n==null?void 0:n.sender)==null?void 0:s.video)==null?void 0:a.codecs.findIndex(l=>l.mimeType===d))>=0||c===Pn.length-1){o(this,ys).get(d).add(e);break}}}handlePeerLeaving(e){Q.hasFeature(ie.FORCE_VIDEO_CODEC)||(o(this,ys).forEach(n=>n.delete(e)),o(this,Ss).forEach((n,r)=>{n.delete(e),n.size===0&&this.disableWebcam(r)}))}}ud=new WeakMap,hd=new WeakMap,bt=new WeakMap,$=new WeakMap,go=new WeakMap,mi=new WeakMap,Lt=new WeakMap,fs=new WeakMap,vs=new WeakMap,gi=new WeakMap,pd=new WeakMap,Ir=new WeakMap,fo=new WeakMap,ys=new WeakMap,Ss=new WeakMap,xt=new WeakMap,Gt=new WeakMap,fi=new WeakSet,Es=function(){return this.context.getValue("connectionHandler")},ht=new WeakSet,_t=function(t){return o(this,xt).get(t)},Ts=new WeakSet,vo=function(t,e){return o(this,xt).set(t,e)},Bh=new WeakSet,cS=function(t){return o(this,xt).delete(t)},Wh=new WeakSet,dS=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},jh=new WeakSet,lS=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};he([S.trace("MediaNodeClient.reset",{country:S.location.country})],ue.prototype,"reset",1);he([S.trace("MediaNodeClient.joinRoom")],ue.prototype,"joinRoom",1);he([S.trace("MediaNodeClient.completeJoinRoom")],ue.prototype,"completeJoinRoom",1);he([S.trace("MediaNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1);he([S.trace("MediaNodeClient.activatePeers")],ue.prototype,"activatePeers",1);he([S.trace("MediaNodeClient.deactivatePeers")],ue.prototype,"deactivatePeers",1);he([S.trace("MediaNodeClient.createConsumers")],ue.prototype,"createConsumers",1);he([S.trace("MediaNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1);he([S.trace("MediaNodeClient._shareWebcam")],ue.prototype,"_shareWebcam",1);he([S.trace("MediaNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1);he([S.trace("MediaNodeClient.shareScreen")],ue.prototype,"shareScreen",1);he([S.trace("MediaNodeClient.shareMic")],ue.prototype,"shareMic",1);he([S.trace("MediaNodeClient.pauseMic")],ue.prototype,"pauseMic",1);he([S.trace("MediaNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1);he([S.trace("MediaNodeClient.resumeMic")],ue.prototype,"resumeMic",1);he([S.trace("MediaNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1);he([S.trace("MediaNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1);he([S.trace("HiveClient.disableMic")],ue.prototype,"disableMic",1);he([S.trace("HiveClient.disableScreenShare")],ue.prototype,"disableScreenShare",1);he([S.trace("MediaNodeClient.muteSelf")],ue.prototype,"muteSelf",1);he([S.trace("MediaNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1);he([S.trace("MediaNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1);he([S.trace("MediaNodeClient.kickPeer")],ue.prototype,"kick",1);he([S.trace("MediaNodeClient.kickAllPeers")],ue.prototype,"kickAll",1);he([S.trace("MediaNodeClient.muteAll")],ue.prototype,"muteAll",1);he([S.trace("MediaNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1);he([S.trace("MediaNodeClient.disableAudio")],ue.prototype,"disableAudio",1);he([S.trace("MediaNodeClient.disableVideo")],ue.prototype,"disableVideo",1);he([S.trace("MediaNodeClient.pinPeer")],ue.prototype,"pinPeer",1);he([S.trace("MediaNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);function uS(t,e,n){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const i=new ue(t,e,n);return t.setValue("roomNodeClient",i),i}function hS(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{p.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var sL=Object.defineProperty,aL=Object.getOwnPropertyDescriptor,qi=(t,e,n,r)=>{for(var i=r>1?void 0:r?aL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&sL(e,n,i),i},Xr,Rn,St,en,ln,of;const pS=(of=class{constructor(t,e,n,r){f(this,en),g(this,"self"),g(this,"authToken"),f(this,Xr,void 0),g(this,"viewType"),f(this,Rn,void 0),f(this,St,void 0);const{socket:i}=n,s=t.getValue("authToken");this.self=e,v(this,St,t),this.viewType=r,this.authToken=s,v(this,Xr,i),v(this,Rn,n),e.config.viewType!==Rt.Chat&&this.setupEvents()}get peerId(){return o(this,St).getValue("peerId")}get mediaJoined(){return o(this,St).getValue("connectionHandler").mediaJoined}static init(t,e,n,r,i){return u(this,null,function*(){const s=dt(),a=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield st.__init__(t,n,r,i,i.name,c);if(navigator.product!=="ReactNative"){const l=!Q.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const h=yield d.getAllDevices();p.info("populated_full_device_list",{devices:JSON.stringify(h)}),K.devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),K.devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),K.devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),p.info("Callstats:: initializing");try{yield K.initialize({peerId:a,engineName:Pe.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Q.getAllFlags(),logger:p,apiHostnames:ry(t),skipConnectivityChecks:l}),p.info("Callstats:: initialized")}catch(m){p.error("Callstats:: initialization failed",{error:m})}}),0)}else p.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new pS(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:n,permissions:r,audioEnabled:i,videoEnabled:s,screenShareEnabled:a,screenShareTracks:c}=this.self;if(r.canProduceAudio&&i)try{yield o(this,en,ln).shareMic(e)}catch{this.self.disableAudio()}if(r.canProduceVideo&&s)try{const d=yield o(this,en,ln).shareWebcam(n);d&&d.id!==n.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield o(this,en,ln).shareWebcam(d))}catch{this.self.disableVideo()}if(r.canProduceScreenshare&&a)try{yield(t=o(this,en,ln))==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(){p.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(p.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){p.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(p.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){p.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){K.callEnded(),o(this,en,ln).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){P.on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),P.on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),P.on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),P.on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),P.on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),P.on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Q.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=Bs()),o(this,Xr).updateURL(e),S.resetPeerId(e),dt().setHeader("dyte-tracing-id",e),Ri.remapContext(e,o(this,St)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),P.on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),o(this,Rn).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),o(this,Rn).on(Hc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&P.emit(R.UPDATE_PERMISSIONS,e.patch)})}),o(this,Rn).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),o(this,Rn).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),o(this,Rn).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),P.onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),P.on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:n,scoreStats:r})=>{var i;const s=(i=n==null?void 0:n.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),P.on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),K.audioOff())})),P.on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),K.videoOff())})),P.onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),P.on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield o(this,Rn).joinRoom(this.self);o(this,Rn).socket.flush();const n=Ep(e.stageType);if(o(this,St).setValue("stageStatus",n,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),o(this,St).notify("stageStatus")}catch(e){throw p.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,n;if(t==="rejected"){try{(e=o(this,Xr))==null||e.disconnect()}catch{p.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),o(this,St).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),o(this,St).notify("stageStatus");try{(n=o(this,Xr))==null||n.disconnect()}catch{p.error("SelfController::leaveRoom::socketDisconnect")}hS(o(this,St)),Wd.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,n;const{peerId:r,viewType:i,meetingId:s,stageStatus:a,roomNodeOptions:c}=o(this,St).getAllValues(),{sfu:d}=c;try{if(i===Rt.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}uS(o(this,St),d,{socket:o(this,Xr),peerId:r})}const{roomJoined:l}=(n=yield(e=o(this,en,ln))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?n:{};if(!l)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw p.error("Error:SelfController.mediaRoomJoin",{error:l}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=o(this,St).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Rt.Webinar)&&o(this,en,ln)&&(o(this,en,ln).mediaJoined&&t!=="disconnected"&&(yield o(this,en,ln).leaveRoom()),!(t==="stageLeft"&&e===Rt.Livestream)&&(o(this,en,ln).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()})}},Xr=new WeakMap,Rn=new WeakMap,St=new WeakMap,en=new WeakSet,ln=function(){return o(this,St).getValue("roomNodeClient")},of);let Jr=pS;qi([S.trace("SelfController.resetSelf")],Jr.prototype,"resetSelf",1);qi([S.trace("SelfController.setupEvents")],Jr.prototype,"setupEvents",1);qi([S.trace("SelfController.joinRoom")],Jr.prototype,"joinRoom",1);qi([S.trace("SelfController.leaveRoom")],Jr.prototype,"leaveRoom",1);qi([S.trace("SelfController.joinMediaRoom")],Jr.prototype,"joinMediaRoom",1);qi([S.trace("SelfController.leaveMediaRoom")],Jr.prototype,"leaveMediaRoom",1);qi([S.trace("SelfController.init")],Jr,"init",1);var md;class oL{constructor(e){f(this,md,void 0),v(this,md,e)}on(e,n){let r;e===j.roomPeerCount?r=mg.fromBinary.bind(mg):r=wg.fromBinary.bind(wg),o(this,md).on(e,({payload:i})=>{const s=r(i);return n(s)})}}md=new WeakMap;var gd;class cL{constructor(e){f(this,gd,void 0),v(this,gd,e)}on(e,n){let r,i;switch(e){case j.transcript:{r=Ql.fromBinary.bind(Ql),i=Ql.create();break}default:{p.debug("AISocketHandler switch case hit default, event not accounted for.");break}}o(this,gd).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}gd=new WeakMap;var dL=Object.defineProperty,lL=Object.getOwnPropertyDescriptor,Dp=(t,e,n,r)=>{for(var i=r>1?void 0:r?lL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&dL(e,n,i),i},Cr;class bl{constructor(e){f(this,Cr,void 0),v(this,Cr,e)}getPolls(){return o(this,Cr).sendMessagePromise(Yn.getPolls)}createPoll(e,n,r=!1,i=!1){const s={anonymous:r,hideVotes:i,question:e,options:n};return o(this,Cr).sendMessage(Yn.createPoll,iD.toBinary(s))}votePoll(e,n){const r={index:n,pollId:e};return o(this,Cr).sendMessage(Yn.votePoll,aD.toBinary(r))}on(e,n){let r,i;switch(e){case Yn.updatePoll:case Yn.createPoll:case Yn.votePoll:{r=ru.fromBinary.bind(ru),i=ru.create();break}}o(this,Cr).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("pollSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}removeListeners(e){o(this,Cr).removeListeners(e)}}Cr=new WeakMap;Dp([S.trace("PollSocketHandler.getPolls")],bl.prototype,"getPolls",1);Dp([S.trace("PollSocketHandler.createPoll")],bl.prototype,"createPoll",1);Dp([S.trace("PollSocketHandler.votePoll")],bl.prototype,"votePoll",1);var Jt;class uL{constructor(e){f(this,Jt,void 0),v(this,Jt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield o(this,Jt).sendMessagePromise(j.getStageRequests);return e?nu.fromBinary(e):{stageRequests:[]}})}requestAccess(){o(this,Jt).sendMessage(j.requestStageAccess)}cancelRequestAccess(){o(this,Jt).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Jt).sendMessage(j.grantStageAccess,K1.toBinary(n))})}denyAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Jt).sendMessage(j.denyStageAccess,Y1.toBinary(n))})}joinStage(){return o(this,Jt).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const n={userIds:[e]};return o(this,Jt).sendMessagePromise(j.leaveStage,Cg.toBinary(n),void 0,j.peerStageStatusUpdate)}kick(e){const n={userIds:e};return o(this,Jt).sendMessagePromise(j.leaveStage,Cg.toBinary(n))}on(e,n){let r;switch(e){case j.grantStageAccess:case j.denyStageAccess:{r=void 0;break}case j.getStagePeers:{r=Ig.fromBinary.bind(Ig);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{r=nu.fromBinary.bind(nu);break}case j.peerStageStatusUpdate:{r=pg.fromBinary.bind(pg);break}}o(this,Jt).on(e,({payload:i,id:s})=>{if(!i||!r)return n(void 0,s);const a=r(i);return n(a,s)})}getPeerInfo(e){return u(this,null,function*(){const n=yield o(this,Jt).sendMessagePromise(j.getPeerInfo,py.toBinary({peerId:e}));return as.fromBinary(n.payload)})}}Jt=new WeakMap;var tt;class hL{constructor(e){f(this,tt,void 0),v(this,tt,e)}addPlugin(e,n){o(this,tt).sendMessage(z.addPlugin,u1.toBinary({pluginId:e,staggered:n}))}removePlugin(e){o(this,tt).sendMessage(z.removePlugin,p1.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield o(this,tt).sendMessagePromise(z.getPlugins);return e?x1.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,n,r){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(n))};o(this,tt).sendMessage(z.customPluginEventToRoom,b1.toBinary(i),r)}customPluginEventToPeers(e,n,r,i){const s={pluginId:e,peerIds:n,pluginData:new TextEncoder().encode(JSON.stringify(r))};o(this,tt).sendMessage(z.customPluginEventToPeers,w1.toBinary(s),i)}enablePluginForRoom(e,n){o(this,tt).sendMessage(z.enablePluginForRoom,g1.toBinary({pluginId:e}),n)}enablePluginForPeers(e,n,r){o(this,tt).sendMessage(z.enablePluginForPeers,S1.toBinary({pluginId:e,peerIds:n}),r)}disablePluginForRoom(e,n){o(this,tt).sendMessage(z.disablePluginForRoom,v1.toBinary({pluginId:e}),n)}disablePluginForPeers(e,n,r){o(this,tt).sendMessage(z.disablePluginForPeers,T1.toBinary({pluginId:e,peerIds:n}),r)}storeInsertKeys(e,n,r,i){const s={pluginId:e,storeName:n,insertKeys:r.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};o(this,tt).sendMessage(z.storeInsertKeys,Tg.toBinary(s),i)}storeGetKeys(e,n,r,i){const s={pluginId:e,storeName:n,getKeys:r.map(a=>({storeKey:a.key}))};o(this,tt).sendMessage(z.storeGetKeys,R1.toBinary(s),i)}storeDeleteKeys(e,n,r,i){const s={pluginId:e,storeName:n,deleteKeys:r.map(a=>({storeKey:a.key}))};o(this,tt).sendMessage(z.storeDeleteKeys,A1.toBinary(s),i)}storeDelete(e,n,r){o(this,tt).sendMessage(z.storeDelete,O1.toBinary({pluginId:e,storeName:n}),r)}getPluginDataOld(e,n){p.info("getPluginDataOld",{plugin:{id:e,storeName:n}})}storePluginDataOld(e,n,r){const i={pluginId:e,storeName:n,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};o(this,tt).sendMessage(z.storeInsertKeys,Tg.toBinary(i))}on(e,n){let r;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{r=Yu.fromBinary.bind(Yu);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{r=kg.fromBinary.bind(kg);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{r=_g.fromBinary.bind(_g);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{r=bg.fromBinary.bind(bg);break}}o(this,tt).on(e,({payload:i,id:s})=>{const a=r(i);return n(a,s)})}}tt=new WeakMap;var pL=Object.defineProperty,mL=(t,e,n)=>e in t?pL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gL=(t,e,n)=>(mL(t,typeof e!="symbol"?e+"":e,n),n),Op=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},L=(t,e,n)=>(Op(t,e,"read from private field"),n?n.call(t):e.get(t)),Ie=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},me=(t,e,n,r)=>(Op(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),De=(t,e,n)=>(Op(t,e,"access private method"),n),Yd={},fL={get exports(){return Yd},set exports(t){Yd=t}},Ns=typeof Reflect=="object"?Reflect:null,cf=Ns&&typeof Ns.apply=="function"?Ns.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},fd;Ns&&typeof Ns.ownKeys=="function"?fd=Ns.ownKeys:Object.getOwnPropertySymbols?fd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:fd=function(t){return Object.getOwnPropertyNames(t)};function vL(t){console&&console.warn&&console.warn(t)}var mS=Number.isNaN||function(t){return t!==t};function fe(){fe.init.call(this)}fL.exports=fe;Yd.once=TL;fe.EventEmitter=fe;fe.prototype._events=void 0;fe.prototype._eventsCount=0;fe.prototype._maxListeners=void 0;var df=10;function _l(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(fe,"defaultMaxListeners",{enumerable:!0,get:function(){return df},set:function(t){if(typeof t!="number"||t<0||mS(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");df=t}});fe.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};fe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||mS(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 gS(t){return t._maxListeners===void 0?fe.defaultMaxListeners:t._maxListeners}fe.prototype.getMaxListeners=function(){return gS(this)};fe.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var r=t==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[t];if(c===void 0)return!1;if(typeof c=="function")cf(c,this,e);else for(var d=c.length,l=ES(c,d),n=0;n<d;++n)cf(l[n],this,e);return!0};function fS(t,e,n,r){var i,s,a;if(_l(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),a=s[e]),a===void 0)a=s[e]=n,++t._eventsCount;else if(typeof a=="function"?a=s[e]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),i=gS(t),i>0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,vL(c)}return t}fe.prototype.addListener=function(t,e){return fS(this,t,e,!1)};fe.prototype.on=fe.prototype.addListener;fe.prototype.prependListener=function(t,e){return fS(this,t,e,!0)};function yL(){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 vS(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=yL.bind(r);return i.listener=n,r.wrapFn=i,i}fe.prototype.once=function(t,e){return _l(e),this.on(t,vS(this,t,e)),this};fe.prototype.prependOnceListener=function(t,e){return _l(e),this.prependListener(t,vS(this,t,e)),this};fe.prototype.removeListener=function(t,e){var n,r,i,s,a;if(_l(e),r=this._events,r===void 0)return this;if(n=r[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===e||n[s].listener===e){a=n[s].listener,i=s;break}if(i<0)return this;i===0?n.shift():SL(n,i),n.length===1&&(r[t]=n[0]),r.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};fe.prototype.off=fe.prototype.removeListener;fe.prototype.removeAllListeners=function(t){var e,n,r;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var i=Object.keys(n),s;for(r=0;r<i.length;++r)s=i[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function yS(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?EL(i):ES(i,i.length)}fe.prototype.listeners=function(t){return yS(this,t,!0)};fe.prototype.rawListeners=function(t){return yS(this,t,!1)};fe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):SS.call(t,e)};fe.prototype.listenerCount=SS;function SS(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}fe.prototype.eventNames=function(){return this._eventsCount>0?fd(this._events):[]};function ES(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function SL(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function EL(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function TL(t,e){return new Promise(function(n,r){function i(a){t.removeListener(e,s),r(a)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}TS(t,e,s,{once:!0}),e!=="error"&&kL(t,i,{once:!0})})}function kL(t,e,n){typeof t.on=="function"&&TS(t,"error",e,n)}function TS(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class bL extends T{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const lf=new bL;class kS{static encode(e){return lf.toBinary(e)}static decode(e){return lf.fromBinary(new Uint8Array(e))}}function _L(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Pr;class wL{constructor(e={}){gL(this,"opts"),Ie(this,Pr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},me(this,Pr,0)}wait(){return u(this,null,function*(){me(this,Pr,L(this,Pr)+1);const e=_L(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*NE(2,L(this,Pr))));yield new Promise(n=>{setTimeout(n,e)})})}getAttempts(){return L(this,Pr)}reset(){me(this,Pr,0)}}Pr=new WeakMap;const gr={debug:0,info:1,warn:2,error:3};var vi,yi;class IL{constructor(e){Ie(this,vi,void 0),Ie(this,yi,void 0),me(this,vi,console),me(this,yi,e)}debug(...e){gr[L(this,yi)]>gr.debug||L(this,vi).debug("[Sockrates]:",...e)}info(...e){gr[L(this,yi)]>gr.info||L(this,vi).info("[Sockrates]:",...e)}warn(...e){gr[L(this,yi)]>gr.warn||L(this,vi).warn("[Sockrates]:",...e)}error(...e){gr[L(this,yi)]>gr.error||L(this,vi).error("[Sockrates]:",...e)}}vi=new WeakMap,yi=new WeakMap;var bS=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(bS||{});const CL="2",PL="3";var Ue,ks,Ae,He,Rr,nt,tr,xr,Sn,bs,zn,Hh,_S,yo,vd,qh,wS,Gh,uf,Qd,Jh,$h,IS,No,yd,Lo,Xd,Zd,Kh,Ls,xo,Vo,el;class RL{constructor(e,n){var r;Ie(this,Hh),Ie(this,yo),Ie(this,qh),Ie(this,Gh),Ie(this,Qd),Ie(this,$h),Ie(this,No),Ie(this,Lo),Ie(this,Zd),Ie(this,Ls),Ie(this,Vo),Ie(this,Ue,void 0),Ie(this,ks,void 0),Ie(this,Ae,void 0),Ie(this,He,void 0),Ie(this,Rr,void 0),Ie(this,nt,void 0),Ie(this,tr,void 0),Ie(this,xr,void 0),Ie(this,Sn,void 0),Ie(this,bs,void 0),Ie(this,zn,void 0);var i,s,a,c,d,l,h,m,y;me(this,ks,e),me(this,Rr,[]),me(this,nt,new Yd),me(this,tr,!0),me(this,Sn,!1),me(this,Ae,n!=null?n:{}),(i=L(this,Ae)).autoReconnect!=null||(i.autoReconnect=!0),(s=L(this,Ae)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(a=L(this,Ae)).pingTimeout!=null||(a.pingTimeout=3e4),(c=L(this,Ae)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=L(this,Ae)).debug!=null||(d.debug=!0),(l=L(this,Ae)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=L(this,Ae)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=L(this,Ae)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(y=L(this,Ae)).flushOnReconnect!=null||(y.flushOnReconnect=!1),me(this,xr,{code:void 0,reason:void 0}),me(this,He,(r=L(this,Ae).logger)!=null?r:new IL(L(this,Ae).debug?"debug":"info")),me(this,zn,new wL)}get readyState(){var e;return(e=L(this,Ue))==null?void 0:e.readyState}get url(){return L(this,ks)}updateURL(e){me(this,ks,e),De(this,$h,IS).call(this)}get config(){return L(this,Ae)}get sendQueue(){return L(this,Rr)}flush(){if(!L(this,Ae).queueOnDisconnect)return!1;const e=[];return L(this,Rr).forEach(n=>{this.send(n.event,n.id,n.payload,n.metadata)||e.push(n)}),me(this,Rr,e),L(this,Rr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,He).debug("Websocket was already connecting or connected.");return}if(L(this,tr)!==!1)return new Promise((n,r)=>{De(this,Ls,xo).call(this),De(this,Vo,el).call(this);try{me(this,Ue,new WebSocket(De(this,Hh,_S).call(this,L(this,ks)))),L(this,Ue).binaryType="arraybuffer",L(this,He).debug("Connecting");const i=setTimeout(()=>{L(this,He).debug("Connection timeout. Closing socket"),me(this,tr,!0),De(this,Vo,el).call(this),L(this,Ue).close(3001,"Connection Timeout"),L(this,Ae).autoReconnect&&!L(this,Sn)&&(L(this,nt).emit("reconnecting"),De(this,No,yd).call(this)),r(new Error("Connection timed out!"))},L(this,Ae).connectionTimeout);L(this,Ue).onopen=()=>{L(this,He).debug(`Ready State: ${bS[L(this,Ue).readyState]}`),i&&clearTimeout(i),De(this,Zd,Kh).call(this),me(this,xr,{code:void 0,reason:void 0}),L(this,nt).emit("connected"),L(this,Ae).flushOnReconnect&&this.flush(),n()},L(this,Ue).onclose=s=>{try{i&&clearTimeout(i);const{code:a,reason:c}=s;r(c),L(this,He).debug("Socket closed. Close event:",{event:s}),L(this,He).debug(`Connection closed code: ${a}`),L(this,He).debug(`Connection closed reason: ${c}`),L(this,Sn)||De(this,Qd,Jh).call(this,a,c)}catch(a){De(this,yo,vd).call(this,a)}},L(this,Ue).onerror=s=>{De(this,yo,vd).call(this,s)},L(this,Ue).onmessage=s=>De(this,qh,wS).call(this,s)}catch(i){De(this,yo,vd).call(this,i,r)}})})}send(e,n,r,i){const s={event:e,id:n,payload:r,metadata:i};if(L(this,Ae).queueOnDisconnect&&(!L(this,Ue)||L(this,Ue).readyState!==1))return L(this,He).debug("Queuing message since socket is not connected!",s),L(this,Rr).push(s),!1;const a=kS.encode(s);return De(this,Lo,Xd).call(this,a)}emit(e,n,r,i){return this.send(e,n,r,i)}sendRaw(e){return De(this,Lo,Xd).call(this,e)}receive(e,n){return L(this,nt).on(e.toString(),n)}on(e,n){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){L(this,nt).on(e,n);return}this.receive(e,n)}removeAllListeners(){L(this,nt).removeAllListeners()}removeReceiver(e,n){this.removeListener(e,n)}removeListener(e,n){L(this,nt).removeListener(e.toString(),n)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,nt).listeners(e.toString()).map(n=>this.removeListener(e,n))}disconnect(){me(this,tr,!1),De(this,Ls,xo).call(this),this.removeAllListeners(),me(this,xr,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,Ue).close(1e3,"Sockrates disconnect method called.")}}Ue=new WeakMap,ks=new WeakMap,Ae=new WeakMap,He=new WeakMap,Rr=new WeakMap,nt=new WeakMap,tr=new WeakMap,xr=new WeakMap,Sn=new WeakMap,bs=new WeakMap,zn=new WeakMap,Hh=new WeakSet,_S=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)://.")},yo=new WeakSet,vd=function(t,e){L(this,He).error("Error:",{error:t}),L(this,nt).emit("errored",{error:t}),e==null||e(t)},qh=new WeakSet,wS=function(t){if(De(this,Zd,Kh).call(this),t.data===CL){L(this,He).debug("Received ping from server"),De(this,Lo,Xd).call(this,PL);return}const e=kS.decode(t.data),{id:n,payload:r}=e;L(this,He).debug("Received message",{event:e.event,messageID:n}),L(this,nt).emit(e.event.toString(),{id:n,payload:r})},Gh=new WeakSet,uf=function(){return L(this,Ue).readyState===1},Qd=new WeakSet,Jh=function(t,e){me(this,xr,{reason:e,code:t}),L(this,nt).emit("disconnected",{code:t,reason:e})},$h=new WeakSet,IS=function(){const{reason:t,code:e}=L(this,xr);e&&e!==1e3&&L(this,tr)&&L(this,Ae).autoReconnect&&!L(this,Sn)&&(L(this,He).debug(`Triggering reconnection due to ${t}.`),L(this,nt).emit("reconnecting"),De(this,No,yd).call(this))},No=new WeakSet,yd=function(t=!0){return u(this,null,function*(){if(t&&L(this,Sn)){L(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,Sn)||L(this,zn).reset(),L(this,Ae).maxReconnectionAttempts!==null&&L(this,zn).getAttempts()>=L(this,Ae).maxReconnectionAttempts){L(this,nt).emit("failed"),me(this,Sn,!1);return}me(this,Sn,!0),De(this,Vo,el).call(this),De(this,Ls,xo).call(this);try{if(yield L(this,zn).wait(),L(this,tr)===!1)return;if(L(this,He).debug(`Reconnection attempt ${L(this,zn).getAttempts()}`),L(this,nt).emit("reconnectAttempt",{attempt:L(this,zn).getAttempts()}),yield this.connect(),!De(this,Gh,uf).call(this))throw Error("Reconnect Failed");me(this,Sn,!1),me(this,xr,{code:void 0,reason:void 0}),L(this,nt).emit("reconnected")}catch{L(this,He).debug("Failed to reconnect."),L(this,nt).emit("reconnectFailure",{attempt:L(this,zn).getAttempts()}),De(this,No,yd).call(this,!1)}})},Lo=new WeakSet,Xd=function(t){try{return L(this,Ue).send(t),!0}catch(e){return L(this,He).error(e.message),!1}},Zd=new WeakSet,Kh=function(){this.config.disconnectOnPingTimeout&&(L(this,He).debug("Resetting ping timeout"),De(this,Ls,xo).call(this),me(this,bs,setTimeout(()=>{var t;L(this,He).debug("Disconnecting the socket due to ping timeout"),me(this,tr,!0);const e=3002,n="Ping timeout";(t=L(this,Ue))==null||t.close(e,n),De(this,Qd,Jh).call(this,e,n)},L(this,Ae).pingTimeout)))},Ls=new WeakSet,xo=function(){L(this,bs)&&(clearTimeout(L(this,bs)),me(this,bs,void 0))},Vo=new WeakSet,el=function(){L(this,Ue)&&(L(this,Ue).onopen=void 0,L(this,Ue).onerror=void 0,L(this,Ue).onmessage=void 0,L(this,Ue).onclose=void 0)};var ML=Object.defineProperty,AL=Object.getOwnPropertyDescriptor,wl=(t,e,n,r)=>{for(var i=r>1?void 0:r?AL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&ML(e,n,i),i};const hf=65535,DL=3e3;var Zr,Le,xe,Fe,un,fr,Mc,bu,Ac,_u,pf;const CS=(pf=class{constructor(t,{peerId:e,meetingId:n,authToken:r,capabilities:i}){f(this,xe),f(this,Mc),f(this,Ac),f(this,Zr,void 0),f(this,Le,void 0),g(this,"roomName"),g(this,"authToken"),g(this,"capabilities"),f(this,un,void 0),f(this,fr,void 0);var s;if(!e||!n||!r)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,un,void 0),v(this,fr,t),this.capabilities=i,this.roomName=n,this.authToken=r,v(this,Zr,H(this,Mc,bu).call(this,e)),v(this,Le,new RL(o(this,Zr),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:p})),this.handleSocketConnectionEvents()}get joinAttempted(){return o(this,xe,Fe).socketJoinAttempted}set joinAttempted(t){o(this,xe,Fe).socketJoinAttempted=t}get peerId(){return o(this,fr).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,Zr,H(this,Mc,bu).call(this,t)),p.debug("SocketService:: Connection URL updated.")),o(this,Le).updateURL(o(this,Zr))}static getSocketEdgeDomain(t){return As({servicePrefix:"socket-edge",baseURI:t})}get url(){return o(this,Zr)}connect(){return u(this,null,function*(){o(this,xe,Fe).socketJoinAttempted=!0,yield o(this,Le).connect(),o(this,xe,Fe).socketJoinAttempted=!0,o(this,xe,Fe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){o(this,xe,Fe).socketJoinAttempted=!1,o(this,Le).disconnect(),o(this,xe,Fe).socketJoinAttempted=!0,o(this,xe,Fe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return o(this,Le).readyState===1}catch{return!1}}sendMessage(t,e,n){const r={};return S.injectContext(r),o(this,Le).send(t,n!=null?n:H(this,Ac,_u).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,n,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:n,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:n,messageId:r,resp:i}){const s=i!=null?i:t;return new Promise((a,c)=>{const d=(E,b)=>{o(this,Le).removeListener(s,E),o(this,Le).removeListener(hf,b),o(this,Le).removeListener(rn.errorResponse,b),o(this,Le).removeListener(En.errorResponse,b)},l=r!=null?r:H(this,Ac,_u).call(this),h={};S.injectContext(h);const m=({id:E,payload:b})=>{if(l===E){let O;try{const M=_P.fromBinary(b);O=new Error(M.errorMessage)}catch(M){O=new Error("failed to parse error message",{cause:M});try{const F=CR.fromBinary(b);O=new Error(F.message)}catch(F){O=new Error("failed to parse error message",{cause:F})}}c(O),d(y,m)}},y=({id:E,payload:b})=>{l===E&&(a({id:E,payload:b}),d(y,m))};o(this,Le).on(s,y),o(this,Le).on(hf,m),o(this,Le).on(rn.errorResponse,m),o(this,Le).on(En.errorResponse,m),setTimeout(()=>{d(y,m),c(new Error(`request timeout for callback eventId:${t}`))},e),o(this,Le).send(t,l,n,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){o(this,Le).on(t,e)}onStateEvent(t,e){o(this,Le).on(t,e)}removeListener(t,e){o(this,Le).removeListener(t,e)}removeListeners(t){o(this,Le).removeListeners(t)}flush(){return o(this,Le).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){p.info("SocketService::Connected to socket-edge"),o(this,un)&&(clearTimeout(o(this,un)),v(this,un,void 0)),o(this,xe,Fe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var n;p.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:r,send:i}=(n=o(this,xe,Fe).mediaState)!=null?n:{};r!=null&&r.state&&(r==null?void 0:r.state)!==Wr.CONNECTED||i!=null&&i.state&&(i==null?void 0:i.state)!==Wr.CONNECTED?P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,xe,Fe).joinAttempted}):v(this,un,setTimeout(()=>{P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,xe,Fe).joinAttempted}),v(this,un,void 0)},DL)),o(this,xe,Fe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){p.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),o(this,xe,Fe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){p.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),o(this,xe,Fe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{p.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),o(this,xe,Fe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){p.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:o(this,xe,Fe).mediaJoinAttempted}}),o(this,un)&&(clearTimeout(o(this,un)),v(this,un,void 0)),P.emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:o(this,xe,Fe).mediaJoinAttempted}),o(this,xe,Fe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){p.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),P.emit(R.SOCKET_SERVICE_FAILED),o(this,xe,Fe).updateSocketConnectionState("failed")}))}},Zr=new WeakMap,Le=new WeakMap,xe=new WeakSet,Fe=function(){return o(this,fr).getValue("connectionHandler")},un=new WeakMap,fr=new WeakMap,Mc=new WeakSet,bu=function(t){let e=CS.getSocketEdgeDomain(o(this,fr).getValue("baseURI"));typeof xd(o(this,fr),"socket_server_base")=="string"&&(e=xd(o(this,fr),"socket_server_base"));const n=`wss://${e}`,r=new URL(`${n}/ws`),i=this.peerId,s=G(x({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Vd[a]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(s).forEach(([a,c])=>{r.searchParams.append(a,c.toString())}),r.href},Ac=new WeakSet,_u=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},pf);let Zo=CS;wl([S.trace("SocketService.connect")],Zo.prototype,"connect",1);wl([S.trace("SocketService.disconnect")],Zo.prototype,"disconnect",1);wl([S.trace("SocketService.sendMessagePromise")],Zo.prototype,"sendMessagePromise",1);wl([S.trace("SocketService.sendMessagePromiseWithTimeout")],Zo.prototype,"sendMessagePromiseWithTimeout",1);const Si=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const n=eM.fromBinary(t),r=n.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:n.parentMeeting.id,title:n.parentMeeting.title,participants:(e=n.parentMeeting.participants)!=null?e:[]},meetings:r}}static handleTransferPeerRaw({payload:t}){const e=IM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=my.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return vg.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return fM.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Si.socketService.sendMessagePromise(j.getConnectedRoomsDump);return Si.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Si.socketService.sendMessagePromise(j.createConnectedRooms,iM.toBinary({payloads:t}));return vg.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(r=>({id:r})),n=yield Si.socketService.sendMessagePromise(j.deleteConnectedRooms,mM.toBinary({payloads:e}));return Si.handleConnectedRoomsDeletedRaw(n)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Si.socketService.sendMessagePromise(j.movePeers,kM.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=Si;g(Ne,"socketService"),g(Ne,"currentMeetingId");var OL=Object.defineProperty,NL=Object.getOwnPropertyDescriptor,Il=(t,e,n,r)=>{for(var i=r>1?void 0:r?NL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&OL(e,n,i),i};const _s=class{constructor(t,e){g(this,"apiBase"),g(this,"selfController"),g(this,"pollController"),g(this,"chatController"),g(this,"metaController"),g(this,"storesManager"),g(this,"stageController"),g(this,"pluginController"),g(this,"internalsController"),g(this,"recordingController"),g(this,"livestreamController"),g(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){var e,n;const{peerId:r,apiBase:i,authToken:s,meetingId:a,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(P.reset(),Wd.cleanup(),hS(t),Pe.isSupported()===!1)throw new w("Browser not supported","0010",!0);const l=FD(t,{authToken:s,baseURL:i,cachedUserDetails:d});l.setRoomName(a),l.setRoomUUID(a),l.setOrganizationId(c),l.setHeader("dyte-tracing-id",r),t.setValue("apiClient",l);const h=new TO;t.setValue("connectionHandler",h);const m=_s.createSocketService(t),y=m.connect(),E=l.getUserDetails(),b=l.getPlugins();let O=rt.HIVE,M,F="";try{yield _s.setupFlagsmith(t)}catch(Z){p.error("Failed to setup flagsmith",{error:Z})}try{yield y}catch(Z){p.error("[Controller]: Failed to connect to socket server:",{error:Z})}try{({sfu:O,meetingTitle:F}=yield l.getRoomNodeData()),M=yield E,p.info(`SFU ${O} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:O})}catch(Z){p.error("Failed to get room metadata",{error:Z})}const V=sN.init(M.preset,!t.getValue("modules").theme),J=_s.setupControllers(m,t,M,b,F,V);lO(V)&&((e=_s.createRoomNodeClient(t,m).partialJoinRoom(M.participant.name,a,void 0))==null||e.catch(Z=>{p.error("[Controller]: Failed to queue partial media room promise:",{error:Z})})),S.location.country=(n=l.ipInfo)==null?void 0:n.country;const{controllers:I}=yield J;return cC(),new _s(i,I)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:n,baseURI:r,overrides:i,meetingId:s,organizationId:a}=t.getAllValues(),c=aC(s),d=G(x({entity:Hu.PEER,clientId:a,isAnonUser:!a,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Pe.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const l=(e=i==null?void 0:i.whitelabelled_flags_endpoint)==null||e?As({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield Q.identify(`${Hu.PEER}_${n}`,JSON.parse(JSON.stringify(d)),!1,5e3,l,p),p.info("flagsmith::allFlags",{flags:JSON.stringify(Q.getAllFlags())},!0)}catch{p.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,n,r,i,s){return u(this,null,function*(){var a,c,d;const l=e.getValue("modules"),{preset:h,participant:m}=n,y=e.getValue("defaults"),{sfu:E}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:O}}=s;e.setValue("viewType",b),e.setValue("defaults",x({mediaConfiguration:{audio:{enableHighBitrate:(a=O.enableHighBitrate)!=null?a:!1,enableStereo:(c=O.enableStereo)!=null?c:!1}}},y));const M=IN.init(e,b,h.permissions);e.setValue("maxPreferredStreams",Pe.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let F,V,J,I,Z,ae,Ee,ce;const Re=new cL(t);Ne.socketService=t;const vt=new bl(t),A=new sn(t),k=new uL(t),_=Wd.create(t,e),W=new hL(t),we=new oL(t),ze=new Ni(t),B=yield Jr.init(e,_,m,M,s),C=yield wy.init(e,B.self,_,Re,i);if(l.participant&&(ce=new lr(e,B.self,_,E)),(d=l.e2ee)!=null&&d.enabled&&l.e2ee.manager.init(p,P),l.chat&&(V=yield rr.init(e,A,ze,B.self,ce.participants)),l.internals&&(Z=yield kp.init()),l.livestream&&s.viewType===Rt.Livestream&&Q.hasFeature(ie.LIVESTREAM)&&(Ee=new Ny(B.self,we)),s.viewType!==Rt.Chat){if(l.poll&&(F=yield Ty.init(e,B.self,vt)),l.recording&&(ae=new Ry(e,B.self,_)),l.stage&&(J=new Iy(e,k,_,B.self,ce.participants)),l.plugin){if(!ce)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const Hn=yield r;I=yield zo.init(e,Hn,W,A,V==null?void 0:V.chat,B.self,ce.participants,i)}if(l.pip){const Hn=yield uC._init(e,B.self);e.setValue("pip",Hn)}}const Ye={storesManager:new pN(e,W),pollController:F,selfController:B,metaController:C,chatController:V,stageController:J,pluginController:I,recordingController:ae,internalsController:Z,livestreamController:Ee,participantController:ce};return{theme:s,permissions:M,controllers:Ye}})}static createRoomNodeClient(t,e){const{peerId:n,roomNodeOptions:r}=t.getAllValues(),{sfu:i}=r;return uS(t,i,{socket:e,peerId:n})}static createSocketService(t){const{peerId:e,meetingId:n,authToken:r}=t.getAllValues(),i=["PING"];return new Zo(t,{peerId:e,meetingId:n,authToken:r,capabilities:i})}};let ec=_s;Il([S.trace("Controller.init")],ec,"init",1);Il([S.trace("setupFlagsmith")],ec,"setupFlagsmith",1);Il([S.trace("Controller.createRoomNodeClient")],ec,"createRoomNodeClient",1);Il([S.trace("Controller.createSocketService")],ec,"createSocketService",1);var LL=Object.defineProperty,xL=Object.getOwnPropertyDescriptor,VL=(t,e,n,r)=>{for(var i=r>1?void 0:r?xL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&LL(e,n,i),i},Sd,zh;class PS extends zt{constructor(e,n){super(),f(this,Sd,void 0),g(this,"meetings",[]),g(this,"parentMeeting",null),f(this,zh,void 0),v(this,zh,e),v(this,Sd,n.self)}get supportsConnectedMeetings(){return o(this,Sd).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
23
23
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(n=>({id:n.id,title:n.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(n=>({meetingId:n.id,title:n.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(n),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,n,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:r.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,n,r),i})}moveParticipantsWithCustomPreset(e,n,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:r});return i.success&&this.moveSuccessHandler(e,n,r.map(s=>s.id)),i})}moveSuccessHandler(e,n,r){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),n===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(n===s.id){const a=s.participants.concat(r.map(c=>i.get(c)));return G(x({},s),{participants:a})}if(e===s.id){const a=s.participants.filter(c=>!r.includes(c.id));return G(x({},s),{participants:a})}return s})}}Sd=new WeakMap,zh=new WeakMap;VL([Ft({maxInvocations:60,period:60})],PS.prototype,"getConnectedMeetings",1);var UL=Object.defineProperty,FL=Object.getOwnPropertyDescriptor,Np=(t,e,n,r)=>{for(var i=r>1?void 0:r?FL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&UL(e,n,i),i},Ua,hn,wu,Iu;const Mr=(wu=class{constructor(t,e,n){g(this,"connectedMeetings"),f(this,Ua,void 0),f(this,hn,void 0),f(this,Iu,void 0),v(this,Iu,t),v(this,Ua,n),this.connectedMeetings=new PS(t,e),this.setCurrentMeeting(e)}static init(t,e,n){return Mr.instance||(Mr.instance=new Mr(t,e,n)),Mr.instance.connectedMeetings.supportsConnectedMeetings&&(Mr.instance.setupEvents(),e.self.once("roomJoined",()=>Mr.instance.getConnectedMeetings())),Mr.instance}setCurrentMeeting(t){v(this,hn,t),Ne.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:n}){var r,i,s,a;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
24
24
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);p.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",n);const c={video:o(this,hn).self.videoEnabled,audio:o(this,hn).self.audioEnabled};try{o(this,hn).self.cleanupEvents(),yield o(this,hn).leave("connected-meeting")}catch(l){p.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(i=(r=o(this,hn))==null?void 0:r.meta)==null?void 0:i.meetingId}`,{error:l})}Ne.socketService=void 0,p.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${n}`);const d=yield RS.init(G(x({},o(this,Ua)),{cachedUserDetails:null,defaults:G(x(x({},o(this,Ua).defaults),c),{mediaHandler:o(this,hn).self}),authToken:e}));p.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=o(this,hn).self;d.self.setName(o(this,hn).self.name),yield d.join(),l&&d.self.hide()}catch(l){p.error("ConnectedMeetingsController.joinRoom",{error:l})}return p.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(a=d==null?void 0:d.meta)==null?void 0:a.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(n=>({id:n.id,title:n.title,participants:n.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),n=new Map;this.connectedMeetings.meetings.forEach(r=>{n.set(r.id,r)}),e.forEach(r=>{n.has(r.id)?n.get(r.id).title=r.title:n.set(r.id,G(x({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(n.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.handleConnectedRoomsDeletedRaw(t).map(n=>n.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(n=>!e.includes(n.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Ua=new WeakMap,hn=new WeakMap,Iu=new WeakMap,g(wu,"instance"),wu);let Cl=Mr;Np([S.trace("ConnectedMeetingsController.getConnectedMeetings")],Cl.prototype,"getConnectedMeetings",1);Np([S.trace("ConnectedMeetingsController.setupEvents")],Cl.prototype,"setupEvents",1);Np([S.trace("ConnectedMeetingsController.switchMeeting")],Cl.prototype,"switchMeeting",1);class BL{constructor(){g(this,"battery"),g(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){p.error("Error getting battery",e)}})),g(this,"updateChargeInfo",()=>{var e;p.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),g(this,"updateLevelInfo",()=>{if(!this.battery){p.log("Battery level: Not known");return}p.log(`Battery level: ${this.battery.level*100}%`)}),g(this,"cleanup",()=>{var e,n;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(n=this.battery)==null||n.removeEventListener("levelchange",this.updateLevelInfo))})}}const mf=new BL;function WL(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:n,orgId:r,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!n)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const a=`https://api.${s}`;return{meetingId:n,orgId:r,participantId:i,baseURI:s,apiBase:a}}catch(n){throw p.error("constants::decodeAuthToken",{error:n,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var jL=Object.defineProperty,HL=Object.getOwnPropertyDescriptor,Pl=(t,e,n,r)=>{for(var i=r>1?void 0:r?HL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&jL(e,n,i),i},ot,Dc,Oc,Cu,gf,ff;let jr=(ff=class{constructor(t,e){f(this,Cu),f(this,ot,void 0),f(this,Dc,void 0),f(this,Oc,void 0),v(this,Oc,t),v(this,ot,e)}static init(t){return u(this,null,function*(){var e,n,r,i,s,a,c;rC(),Pe.init();const d=(n=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?n:Bs();mf.init();const{authToken:l,baseURI:h}=t,m=WL(l,h),{meetingId:y}=m,E=rl(m,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=jr.setupContext(d,t,y,E);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=E.participantId,S.meetingMetadata.organizationId=E.orgId,S.init(b,(i=(r=t.modules)==null?void 0:r.tracing)!=null?i:!0),p.info("DyteClient::init::options",{dyteClientInitOptions:G(x({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
25
- ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const O=yield ec.init(b),M=new jr(b,O);return H(c=M,Cu,gf).call(c,t),M})}static setupContext(t,e,n,r){var i;const s=Ri.createContext(t,e),a=x(x({},QI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",r.apiBase),s.setValue("baseURI",r.baseURI),s.setValue("userId",r.participantId),s.setValue("organizationId",r.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",XI({baseURI:r.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",kn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.91"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,ot);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){mf.cleanup();const{selfController:e}=o(this,ot);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,ot).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,ot).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,ot).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,ot).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,ot).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,ot).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,ot).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,Dc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,ot).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,ot).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,ot).stageController)==null?void 0:t.stage}get stores(){return o(this,ot).storesManager}get __internals__(){var t;return(t=o(this,ot).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},ot=new WeakMap,Dc=new WeakMap,Oc=new WeakMap,Cu=new WeakSet,gf=function(t){v(this,Dc,Cl.init(o(this,Oc),this,t))},ff);Pl([gt("0002"),Gr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],jr.prototype,"join",1);Pl([gt("0003")],jr.prototype,"leave",1);Pl([gt("0001"),Gr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],jr,"init",1);jr=Pl([gt("0000")],jr);const RS=jr;exports.RTKSelfMedia=By;exports.default=RS;
25
+ ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const O=yield ec.init(b),M=new jr(b,O);return H(c=M,Cu,gf).call(c,t),M})}static setupContext(t,e,n,r){var i;const s=Ri.createContext(t,e),a=x(x({},QI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",r.apiBase),s.setValue("baseURI",r.baseURI),s.setValue("userId",r.participantId),s.setValue("organizationId",r.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",XI({baseURI:r.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",kn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.92"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,ot);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){mf.cleanup();const{selfController:e}=o(this,ot);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,ot).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,ot).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,ot).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,ot).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,ot).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,ot).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,ot).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,Dc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,ot).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,ot).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,ot).stageController)==null?void 0:t.stage}get stores(){return o(this,ot).storesManager}get __internals__(){var t;return(t=o(this,ot).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},ot=new WeakMap,Dc=new WeakMap,Oc=new WeakMap,Cu=new WeakSet,gf=function(t){v(this,Dc,Cl.init(o(this,Oc),this,t))},ff);Pl([gt("0002"),Gr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],jr.prototype,"join",1);Pl([gt("0003")],jr.prototype,"leave",1);Pl([gt("0001"),Gr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],jr,"init",1);jr=Pl([gt("0000")],jr);const RS=jr;exports.RTKSelfMedia=By;exports.default=RS;
package/dist/index.es.js CHANGED
@@ -30696,7 +30696,7 @@ let ti = (Pf = class {
30696
30696
  var c;
30697
30697
  const n = Wi.createContext(t, e), a = N(N({}, YR), e == null ? void 0 : e.modules);
30698
30698
  return n.setValue("peerId", t), n.setValue("modules", a), n.setValue("sdkName", "web-core"), n.setValue("meetingId", r), n.setValue("apiBase", i.apiBase), n.setValue("baseURI", i.baseURI), n.setValue("userId", i.participantId), n.setValue("organizationId", i.orgId), n.setValue("authToken", e.authToken), n.setValue("overrides", (c = e.overrides) != null ? c : {}), n.setValue("env", QR({ baseURI: i.baseURI })), n.setValue("defaults", e.defaults || { audio: true, video: true }), n.setValue("onError", e.onError || (() => {
30699
- })), n.setValue("cachedUserDetails", ys(e.cachedUserDetails)), n.setValue("sdkVersion", "2.5.0-staging.91"), n;
30699
+ })), n.setValue("cachedUserDetails", ys(e.cachedUserDetails)), n.setValue("sdkVersion", "2.5.0-staging.92"), n;
30700
30700
  }
30701
30701
  join() {
30702
30702
  return u(this, null, function* () {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "0.5.0-staging.91",
3
+ "version": "0.5.0-staging.92",
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",