@100mslive/hms-video-store 0.11.0 → 0.11.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ka=Object.create;var tt=Object.defineProperty,qa=Object.defineProperties,ja=Object.getOwnPropertyDescriptor,Ja=Object.getOwnPropertyDescriptors,Qa=Object.getOwnPropertyNames,Wt=Object.getOwnPropertySymbols,hs=Object.getPrototypeOf,or=Object.prototype.hasOwnProperty,Ss=Object.prototype.propertyIsEnumerable,za=Reflect.get;var ps=(s,e,t)=>e in s?tt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,S=(s,e)=>{for(var t in e||(e={}))or.call(e,t)&&ps(s,t,e[t]);if(Wt)for(var t of Wt(e))Ss.call(e,t)&&ps(s,t,e[t]);return s},y=(s,e)=>qa(s,Ja(e));var nr=(s,e)=>{var t={};for(var i in s)or.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&Wt)for(var i of Wt(s))e.indexOf(i)<0&&Ss.call(s,i)&&(t[i]=s[i]);return t};var Ya=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Xa=(s,e)=>{for(var t in e)tt(s,t,{get:e[t],enumerable:!0})},ms=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qa(e))!or.call(s,r)&&r!==t&&tt(s,r,{get:()=>e[r],enumerable:!(i=ja(e,r))||i.enumerable});return s};var it=(s,e,t)=>(t=s!=null?Ka(hs(s)):{},ms(e||!s||!s.__esModule?tt(t,"default",{value:s,enumerable:!0}):t,s)),Za=s=>ms(tt({},"__esModule",{value:!0}),s);var q=(s,e,t)=>za(hs(s),t,e);var c=(s,e,t)=>new Promise((i,r)=>{var a=l=>{try{n(t.next(l))}catch(u){r(u)}},o=l=>{try{n(t.throw(l))}catch(u){r(u)}},n=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,o);n((t=t.apply(s,e)).next())});var Hr=Ya((Ud,Wo)=>{Wo.exports={version:"0.11.0",license:"MIT",main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist","src"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^1.0.1",uuid:"^8.3.2","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.36","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"4141fa5d88b73328867609b0ceaa5a5ac67135d0"}});var Gc={};Xa(Gc,{DeviceType:()=>wr,HMSAudioPluginType:()=>Zt,HMSLogLevel:()=>kr,HMSMessageType:()=>gs,HMSNotificationSeverity:()=>cr,HMSNotificationTypes:()=>qt,HMSPlaylistType:()=>dr,HMSPluginUnsupportedTypes:()=>ei,HMSReactiveStore:()=>Oe,HMSRecordingState:()=>Dr,HMSRoomState:()=>Kt,HMSStats:()=>Ze,HMSVideoPluginCanvasContextType:()=>ai,HMSVideoPluginType:()=>si,createDefaultStatsStore:()=>st,createDefaultStoreState:()=>rt,parsedUserAgent:()=>Se,selectAppData:()=>hn,selectAppDataByPath:()=>mn,selectAudioPlaylist:()=>Mr,selectAudioPlaylistTrackByPeerID:()=>In,selectAudioTrackByID:()=>Tn,selectAudioTrackByPeerID:()=>ua,selectAudioTrackVolume:()=>Yr,selectAudioVolumeByPeerID:()=>Nn,selectAuxiliaryAudioByPeerID:()=>bn,selectAuxiliaryTracksByPeerID:()=>yn,selectAvailableRoleNames:()=>Ao,selectBroadcastMessages:()=>ma,selectBroadcastMessagesUnreadCount:()=>Bn,selectCameraStreamByPeerID:()=>Mn,selectConnectionQualities:()=>so,selectConnectionQualityByPeerID:()=>An,selectDegradedTracks:()=>Mo,selectDevices:()=>ro,selectDidIJoinWithin:()=>dc,selectDominantSpeaker:()=>ho,selectEffectsKey:()=>_o,selectErrors:()=>vs,selectFullAppData:()=>Jt,selectHLSState:()=>Io,selectHMSBroadcastMessages:()=>ks,selectHMSMessages:()=>Ue,selectHMSMessagesCount:()=>yo,selectHMSStats:()=>Wa,selectHandRaisedPeers:()=>Uo,selectHasPeerHandRaised:()=>Jn,selectIsAllowedToPreviewMedia:()=>tc,selectIsAllowedToPublish:()=>ec,selectIsAllowedToSubscribe:()=>bo,selectIsAudioLocallyMuted:()=>zr,selectIsConnectedToRoom:()=>he,selectIsEffectsEnabled:()=>wo,selectIsInPreview:()=>Sr,selectIsLargeRoom:()=>Do,selectIsLocalAudioEnabled:()=>So,selectIsLocalAudioPluginPresent:()=>oc,selectIsLocalScreenShared:()=>zt,selectIsLocalVideoDisplayEnabled:()=>hr,selectIsLocalVideoEnabled:()=>Qt,selectIsLocalVideoPluginPresent:()=>ac,selectIsLocallyMutedByPeerID:()=>wn,selectIsPeerAudioEnabled:()=>Ln,selectIsPeerVideoEnabled:()=>Dn,selectIsRoleAllowedToPublish:()=>ic,selectIsScreenShareLocallyMutedByPeerID:()=>_n,selectIsSomeoneScreenSharing:()=>mo,selectLocalAudioTrackID:()=>Y,selectLocalMediaSettings:()=>ur,selectLocalPeer:()=>j,selectLocalPeerID:()=>ne,selectLocalPeerName:()=>co,selectLocalPeerRole:()=>lt,selectLocalPeerRoleName:()=>lo,selectLocalTrackIDs:()=>pr,selectLocalVideoTrackID:()=>$,selectMessageByMessageID:()=>zn,selectMessageIDsInOrder:()=>lr,selectMessagesByPeerID:()=>Fn,selectMessagesByRole:()=>Gn,selectMessagesMap:()=>dt,selectMessagesUnreadCountByPeerID:()=>Wn,selectMessagesUnreadCountByRole:()=>$n,selectPeerAudioByID:()=>Pn,selectPeerByCondition:()=>nc,selectPeerByID:()=>W,selectPeerCount:()=>ao,selectPeerMetadata:()=>jn,selectPeerName:()=>Qn,selectPeerNameByID:()=>gn,selectPeerScreenSharing:()=>ys,selectPeerSharingAudio:()=>go,selectPeerSharingAudioPlaylist:()=>vo,selectPeerSharingVideoPlaylist:()=>fo,selectPeers:()=>ie,selectPeersByCondition:()=>cc,selectPeersByRole:()=>Kn,selectPeersByRoles:()=>qn,selectPeersMap:()=>F,selectPeersScreenSharing:()=>To,selectPeersWithAudioStatus:()=>Yn,selectPermissions:()=>gr,selectPollByID:()=>Xr,selectPolls:()=>xo,selectPollsMap:()=>Tr,selectPreviewRole:()=>mr,selectPreviewRoleName:()=>Es,selectRTMPState:()=>Ho,selectRecentError:()=>to,selectRecordingState:()=>Ro,selectRemotePeers:()=>po,selectRoleByRoleName:()=>ga,selectRoleChangeRequest:()=>Zn,selectRolesMap:()=>re,selectRoom:()=>x,selectRoomID:()=>io,selectRoomStartTime:()=>Lo,selectRoomStarted:()=>Po,selectRoomState:()=>J,selectScreenAudioTrackByID:()=>fn,selectScreenShareAudioByPeerID:()=>Qr,selectScreenShareByPeerID:()=>Cn,selectScreenSharesByPeerId:()=>Jr,selectScreenVideoTrackByID:()=>vn,selectScreenshareAudioVolumeByPeerID:()=>On,selectSessionId:()=>Co,selectSessionMetadata:()=>Oo,selectSessionStore:()=>Sn,selectSimulcastLayerByTrack:()=>xn,selectSpeakers:()=>Ms,selectTemplateAppData:()=>No,selectTrackAudioByID:()=>kn,selectTrackByID:()=>kt,selectTracksMap:()=>D,selectUnreadHMSBroadcastMessagesCount:()=>Eo,selectUnreadHMSMessagesCount:()=>ko,selectVideoPlaylist:()=>yr,selectVideoPlaylistAudioTrackByPeerID:()=>Hn,selectVideoPlaylistVideoTrackByPeerID:()=>Rn,selectVideoTrackByID:()=>jr,selectVideoTrackByPeerID:()=>la,selectWhiteboard:()=>Vo,selectWhiteboards:()=>Ps,simulcastMapping:()=>be});module.exports=Za(Gc);var Kt=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Kt||{});var rt=()=>({room:{id:"",isConnected:!1,name:"",peers:[],localPeer:"",roomState:"Disconnected",recording:{browser:{running:!1},server:{running:!1},hls:{running:!1}},rtmp:{running:!1},hls:{running:!1,variants:[]},sessionId:""},peers:{},tracks:{},playlist:{audio:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1},video:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1}},messages:{byID:{},allIDs:[]},speakers:{},connectionQualities:{},settings:{audioInputDeviceId:"",audioOutputDeviceId:"",videoInputDeviceId:""},devices:{audioInput:[],audioOutput:[],videoInput:[]},roles:{},roleChangeRequests:[],errors:[],sessionStore:{},templateAppData:{},polls:{},whiteboards:{},hideLocalPeer:!1}),st=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var gs=(e=>(e.CHAT="chat",e))(gs||{});var cr=(t=>(t.INFO="info",t.ERROR="error",t))(cr||{}),qt=(C=>(C.PEER_JOINED="PEER_JOINED",C.PEER_LEFT="PEER_LEFT",C.PEER_LIST="PEER_LIST",C.NEW_MESSAGE="NEW_MESSAGE",C.ERROR="ERROR",C.RECONNECTING="RECONNECTING",C.RECONNECTED="RECONNECTED",C.TRACK_ADDED="TRACK_ADDED",C.TRACK_REMOVED="TRACK_REMOVED",C.TRACK_MUTED="TRACK_MUTED",C.TRACK_UNMUTED="TRACK_UNMUTED",C.TRACK_DEGRADED="TRACK_DEGRADED",C.TRACK_RESTORED="TRACK_RESTORED",C.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",C.ROLE_UPDATED="ROLE_UPDATED",C.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",C.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",C.ROOM_ENDED="ROOM_ENDED",C.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",C.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",C.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",C.NAME_UPDATED="NAME_UPDATED",C.METADATA_UPDATED="METADATA_UPDATED",C.POLL_CREATED="POLL_CREATED",C.POLL_STARTED="POLL_STARTED",C.POLL_STOPPED="POLL_STOPPED",C.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",C.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",C))(qt||{});var dr=(t=>(t.audio="audio",t.video="video",t))(dr||{});var E=require("reselect");function Ie(s,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let a=s[r];eo(a)&&(i=at(a)?a:i,t=ot(a)?a:t)}return{video:t,audio:i}}function at(s){return s&&s.type==="audio"}function ot(s){return s&&s.type==="video"}function eo(s){return s&&s.source==="screen"}function jt(s){return s&&s.source==="audioplaylist"}function nt(s){return s&&s.source==="videoplaylist"}function Ts(s){return s?!!(s!=null&&s.degraded):!1}function xe(s,e){return e&&s.tracks[e]?s.tracks[e].enabled:!1}function fs(s,e){return e&&s.tracks[e]?s.tracks[e].displayEnabled:!1}function ct(s){var r;let e=!1,t=!1,i=!1;return(r=s==null?void 0:s.publishParams)!=null&&r.allowed&&(e=s.publishParams.allowed.includes("video"),t=s.publishParams.allowed.includes("audio"),i=s.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}var x=s=>s.room,vs=s=>s.errors,to=(0,E.createSelector)(vs,s=>s.length===0?null:s.at(-1)),io=(0,E.createSelector)(x,s=>s.id),F=s=>s.peers,dt=s=>s.messages.byID,lr=s=>s.messages.allIDs,D=s=>s.tracks,ur=s=>s.settings,Jt=s=>s.appData,ro=s=>s.devices,Ms=s=>s.speakers,so=s=>s.connectionQualities,he=(0,E.createSelector)([x],s=>s&&s.isConnected),ao=(0,E.createSelector)([he,x],(s,e)=>s?e.peerCount!==void 0?e.peerCount||1:e.peers.length:Math.max(e.peerCount!==void 0?e.peerCount:e.peers.length-1,0)),oo=s=>s.hideLocalPeer,ie=(0,E.createSelector)([x,F,oo],(s,e,t)=>t?s.peers.filter(i=>s.localPeer!==i).map(i=>e[i]):s.peers.map(i=>e[i])),no=(0,E.createSelector)(D,s=>Object.values(s)),j=(0,E.createSelector)(x,F,(s,e)=>e[s.localPeer]),ne=(0,E.createSelector)(x,s=>s.localPeer),co=(0,E.createSelector)(j,s=>s==null?void 0:s.name),lo=(0,E.createSelector)(j,s=>s==null?void 0:s.roleName),Y=(0,E.createSelector)(j,s=>s==null?void 0:s.audioTrack),$=(0,E.createSelector)(j,s=>s==null?void 0:s.videoTrack),uo=(0,E.createSelector)(j,s=>s==null?void 0:s.auxiliaryTracks),pr=(0,E.createSelector)([Y,$,uo],(s,e,t)=>{let i=t?[...t]:[];return s&&i.unshift(s),e&&i.unshift(e),i}),po=(0,E.createSelector)(ie,s=>s.filter(e=>!e.isLocal)),ho=(0,E.createSelector)(F,Ms,(s,e)=>{let t=Object.entries(e).sort((i,r)=>{var n,l;let a=((n=i[1])==null?void 0:n.audioLevel)||0;return(((l=r[1])==null?void 0:l.audioLevel)||0)>a?1:-1});if(t.length>0&&t[0][1].audioLevel&&t[0][1].audioLevel>0){let i=t[0][1].peerID;if(i in s)return s[i]}return null}),So=s=>{let e=j(s);return xe(s,e==null?void 0:e.audioTrack)},Qt=s=>{let e=j(s);return xe(s,e==null?void 0:e.videoTrack)},hr=s=>{let e=j(s);return fs(s,e==null?void 0:e.videoTrack)},zt=(0,E.createSelector)(j,D,(s,e)=>{let{video:t,audio:i}=Ie(e,s);return!!(t||i)}),ys=(0,E.createSelector)(F,D,(s,e)=>{let t;for(let i in s){let r=s[i],{video:a,audio:o}=Ie(e,r);if(a)return r;o&&!t&&(t=r)}return t}),mo=(0,E.createSelector)(ys,s=>!!s),go=(0,E.createSelector)(F,D,(s,e)=>{for(let t in s){let i=s[t],{audio:r,video:a}=Ie(e,i);if(!a&&r)return i}}),To=(0,E.createSelector)(F,D,(s,e)=>{let t=[],i=[];for(let r in s){let a=s[r],{video:o,audio:n}=Ie(e,a);o?t.push(a):n&&i.push(a)}return t.concat(i)}),fo=(0,E.createSelector)(F,D,(s,e)=>{for(let t in e){let i=e[t];if(nt(i)&&ot(i)&&i.peerId)return s[i.peerId]}}),vo=(0,E.createSelector)(F,D,(s,e)=>{for(let t in e){let i=e[t];if(jt(i)&&i.peerId)return s[i.peerId]}}),Mo=(0,E.createSelector)(no,s=>s.filter(Ts)),yo=(0,E.createSelector)(lr,s=>s.length),ko=(0,E.createSelector)(dt,s=>Object.values(s).filter(e=>!e.read).length),Ue=(0,E.createSelector)(lr,dt,(s,e)=>{let t=[];return s.forEach(i=>{t.push(e[i])}),t}),ks=(0,E.createSelector)(Ue,s=>s.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),Eo=(0,E.createSelector)(ks,s=>s.filter(e=>!e.read).length),J=(0,E.createSelector)([x],s=>s&&s.roomState),Sr=(0,E.createSelector)(J,s=>s==="Preview"),Po=(0,E.createSelector)(x,s=>s.roomState!=="Disconnected"),re=s=>s.roles,Ao=(0,E.createSelector)([re],s=>Object.keys(s)),lt=(0,E.createSelector)([j,re],(s,e)=>s!=null&&s.roleName?e[s.roleName]:null),Es=s=>{var e;return(e=s.preview)==null?void 0:e.asRole},mr=(0,E.createSelector)([Es,re],(s,e)=>s?e[s]:null),bo=(0,E.createSelector)([lt],s=>{var e;return(e=s==null?void 0:s.subscribeParams)!=null&&e.subscribeToRoles?s.subscribeParams.subscribeToRoles.length>0:!1}),gr=(0,E.createSelector)(lt,s=>s==null?void 0:s.permissions),Ro=(0,E.createSelector)(x,s=>s.recording),Ho=(0,E.createSelector)(x,s=>s.rtmp),Io=(0,E.createSelector)(x,s=>s.hls),Co=(0,E.createSelector)(x,s=>s.sessionId),Lo=(0,E.createSelector)(x,s=>s.startedAt),Do=(0,E.createSelector)(x,s=>!!s.isLargeRoom),wo=(0,E.createSelector)(x,s=>!!s.isEffectsEnabled),_o=(0,E.createSelector)(x,s=>s.effectsKey),No=s=>s.templateAppData,Oo=s=>s.sessionMetadata,Tr=s=>s.polls,xo=s=>Object.values(s.polls),Uo=(0,E.createSelector)(ie,s=>s.filter(e=>e.isHandRaised)),Ps=s=>s.whiteboards,Vo=(0,E.createSelector)(Ps,s=>Object.values(s)[0]);var fr=require("reselect");var As=(s="audio")=>e=>e.playlist[s].list,vr=(s="audio")=>e=>e.playlist[s].selection,bs=(s="audio")=>e=>e.playlist[s].progress,Rs=(s="audio")=>e=>e.playlist[s].currentTime,Hs=(s="audio")=>e=>e.playlist[s].playbackRate,Is=(s="audio")=>e=>e.playlist[s].volume,Cs=(s="audio")=>(0,fr.createSelector)(As(s),e=>Object.values(e)),Ls=(s="audio")=>(0,fr.createSelector)(As(s),vr(s),(e,t)=>{if(t.id)return e[t.id]}),Mr={selection:vr("audio"),progress:bs("audio"),currentTime:Rs("audio"),playbackRate:Hs("audio"),volume:Is("audio"),list:Cs("audio"),selectedItem:Ls("audio")},yr={selection:vr("video"),progress:bs("video"),currentTime:Rs("video"),playbackRate:Hs("video"),volume:Is("video"),list:Cs("video"),selectedItem:Ls("video")};var H=require("reselect");function A(s){return e=>t=>s(t,e)}var kr=(l=>(l[l.VERBOSE=0]="VERBOSE",l[l.DEBUG=1]="DEBUG",l[l.INFO=2]="INFO",l[l.WARN=3]="WARN",l[l.TIME=4]="TIME",l[l.TIMEEND=5]="TIMEEND",l[l.ERROR=6]="ERROR",l[l.NONE=7]="NONE",l))(kr||{}),Bo=typeof window!="undefined"&&typeof window.expect!="undefined",d=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let a=performance.measure(r,r);this.log(1,t,r,a==null?void 0:a.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(a){this.log(1,t,r,a)}break}}}};d.level=Bo?7:0;var Ve=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var ws=require("ua-parser-js"),Se=new ws.UAParser,N=typeof window!="undefined",Ds,Ce=typeof window=="undefined"&&!((Ds=Se.getBrowser().name)!=null&&Ds.toLowerCase().includes("electron"));var Fo=()=>!Ce,id=Fo(),Yt=()=>Se.getDevice().type==="mobile",_s=()=>typeof document!="undefined"&&document.hidden,Er=()=>{var s;return((s=Se.getOS().name)==null?void 0:s.toLowerCase())==="ios"};var Xt=s=>s?`{
1
+ "use strict";var Ja=Object.create;var tt=Object.defineProperty,Qa=Object.defineProperties,za=Object.getOwnPropertyDescriptor,Ya=Object.getOwnPropertyDescriptors,Xa=Object.getOwnPropertyNames,Wt=Object.getOwnPropertySymbols,hs=Object.getPrototypeOf,or=Object.prototype.hasOwnProperty,Ss=Object.prototype.propertyIsEnumerable,Za=Reflect.get;var ps=(s,e,t)=>e in s?tt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,S=(s,e)=>{for(var t in e||(e={}))or.call(e,t)&&ps(s,t,e[t]);if(Wt)for(var t of Wt(e))Ss.call(e,t)&&ps(s,t,e[t]);return s},y=(s,e)=>Qa(s,Ya(e));var nr=(s,e)=>{var t={};for(var i in s)or.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&Wt)for(var i of Wt(s))e.indexOf(i)<0&&Ss.call(s,i)&&(t[i]=s[i]);return t};var eo=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),to=(s,e)=>{for(var t in e)tt(s,t,{get:e[t],enumerable:!0})},ms=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xa(e))!or.call(s,r)&&r!==t&&tt(s,r,{get:()=>e[r],enumerable:!(i=za(e,r))||i.enumerable});return s};var it=(s,e,t)=>(t=s!=null?Ja(hs(s)):{},ms(e||!s||!s.__esModule?tt(t,"default",{value:s,enumerable:!0}):t,s)),io=s=>ms(tt({},"__esModule",{value:!0}),s);var q=(s,e,t)=>Za(hs(s),t,e);var c=(s,e,t)=>new Promise((i,r)=>{var a=l=>{try{n(t.next(l))}catch(u){r(u)}},o=l=>{try{n(t.throw(l))}catch(u){r(u)}},n=l=>l.done?i(l.value):Promise.resolve(l.value).then(a,o);n((t=t.apply(s,e)).next())});var Hr=eo((Gd,jo)=>{jo.exports={version:"0.11.1-alpha.0",license:"MIT",main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist","src"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^1.0.1",uuid:"^8.3.2","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.36","@types/uuid":"^8.3.0","jest-canvas-mock":"^2.3.1","jsdom-worker":"^0.3.0",tslib:"^2.2.0"},description:"@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow",keywords:["video","webrtc","conferencing","100ms"],gitHead:"37788eb004f63672aae22043c6ad6b2debaff74c"}});var Kc={};to(Kc,{DeviceType:()=>wr,HMSAudioPluginType:()=>Zt,HMSLogLevel:()=>kr,HMSMessageType:()=>gs,HMSNotificationSeverity:()=>cr,HMSNotificationTypes:()=>qt,HMSPlaylistType:()=>dr,HMSPluginUnsupportedTypes:()=>ei,HMSReactiveStore:()=>Oe,HMSRecordingState:()=>Dr,HMSRoomState:()=>Kt,HMSStats:()=>Ze,HMSVideoPluginCanvasContextType:()=>ai,HMSVideoPluginType:()=>si,createDefaultStatsStore:()=>st,createDefaultStoreState:()=>rt,parsedUserAgent:()=>ce,selectAppData:()=>gn,selectAppDataByPath:()=>fn,selectAudioPlaylist:()=>Mr,selectAudioPlaylistTrackByPeerID:()=>Dn,selectAudioTrackByID:()=>Mn,selectAudioTrackByPeerID:()=>Sa,selectAudioTrackVolume:()=>Yr,selectAudioVolumeByPeerID:()=>Un,selectAuxiliaryAudioByPeerID:()=>In,selectAuxiliaryTracksByPeerID:()=>Pn,selectAvailableRoleNames:()=>Ho,selectBroadcastMessages:()=>fa,selectBroadcastMessagesUnreadCount:()=>$n,selectCameraStreamByPeerID:()=>En,selectConnectionQualities:()=>no,selectConnectionQualityByPeerID:()=>Hn,selectDegradedTracks:()=>Eo,selectDevices:()=>oo,selectDidIJoinWithin:()=>pc,selectDominantSpeaker:()=>go,selectEffectsKey:()=>xo,selectErrors:()=>vs,selectFullAppData:()=>Jt,selectHLSState:()=>Do,selectHMSBroadcastMessages:()=>ks,selectHMSMessages:()=>Ue,selectHMSMessagesCount:()=>Po,selectHMSStats:()=>ja,selectHandRaisedPeers:()=>Fo,selectHasPeerHandRaised:()=>Yn,selectIsAllowedToPreviewMedia:()=>sc,selectIsAllowedToPublish:()=>rc,selectIsAllowedToSubscribe:()=>Io,selectIsAudioLocallyMuted:()=>zr,selectIsConnectedToRoom:()=>Se,selectIsEffectsEnabled:()=>Oo,selectIsInPreview:()=>Sr,selectIsLargeRoom:()=>No,selectIsLocalAudioEnabled:()=>To,selectIsLocalAudioPluginPresent:()=>dc,selectIsLocalScreenShared:()=>zt,selectIsLocalVideoDisplayEnabled:()=>hr,selectIsLocalVideoEnabled:()=>Qt,selectIsLocalVideoPluginPresent:()=>cc,selectIsLocallyMutedByPeerID:()=>On,selectIsPeerAudioEnabled:()=>_n,selectIsPeerVideoEnabled:()=>Nn,selectIsRoleAllowedToPublish:()=>ac,selectIsScreenShareLocallyMutedByPeerID:()=>xn,selectIsSomeoneScreenSharing:()=>fo,selectLocalAudioTrackID:()=>Y,selectLocalMediaSettings:()=>ur,selectLocalPeer:()=>j,selectLocalPeerID:()=>ne,selectLocalPeerName:()=>po,selectLocalPeerRole:()=>lt,selectLocalPeerRoleName:()=>ho,selectLocalTrackIDs:()=>pr,selectLocalVideoTrackID:()=>$,selectMessageByMessageID:()=>Zn,selectMessageIDsInOrder:()=>lr,selectMessagesByPeerID:()=>Wn,selectMessagesByRole:()=>Kn,selectMessagesMap:()=>dt,selectMessagesUnreadCountByPeerID:()=>jn,selectMessagesUnreadCountByRole:()=>qn,selectPeerAudioByID:()=>Rn,selectPeerByCondition:()=>lc,selectPeerByID:()=>W,selectPeerCount:()=>co,selectPeerMetadata:()=>zn,selectPeerName:()=>Xn,selectPeerNameByID:()=>vn,selectPeerScreenSharing:()=>ys,selectPeerSharingAudio:()=>vo,selectPeerSharingAudioPlaylist:()=>ko,selectPeerSharingVideoPlaylist:()=>yo,selectPeers:()=>ie,selectPeersByCondition:()=>uc,selectPeersByRole:()=>Jn,selectPeersByRoles:()=>Qn,selectPeersMap:()=>F,selectPeersScreenSharing:()=>Mo,selectPeersWithAudioStatus:()=>ec,selectPermissions:()=>gr,selectPollByID:()=>Xr,selectPolls:()=>Bo,selectPollsMap:()=>Tr,selectPreviewRole:()=>mr,selectPreviewRoleName:()=>Es,selectRTMPState:()=>Lo,selectRecentError:()=>so,selectRecordingState:()=>Co,selectRemotePeers:()=>mo,selectRoleByRoleName:()=>va,selectRoleChangeRequest:()=>ic,selectRolesMap:()=>re,selectRoom:()=>x,selectRoomID:()=>ao,selectRoomStartTime:()=>_o,selectRoomStarted:()=>Ro,selectRoomState:()=>J,selectScreenAudioTrackByID:()=>yn,selectScreenShareAudioByPeerID:()=>Qr,selectScreenShareByPeerID:()=>wn,selectScreenSharesByPeerId:()=>Jr,selectScreenVideoTrackByID:()=>kn,selectScreenshareAudioVolumeByPeerID:()=>Vn,selectSessionId:()=>wo,selectSessionMetadata:()=>Vo,selectSessionStore:()=>Tn,selectSimulcastLayerByTrack:()=>Bn,selectSpeakers:()=>Ms,selectTemplateAppData:()=>Uo,selectTrackAudioByID:()=>An,selectTrackByID:()=>kt,selectTracksMap:()=>D,selectUnreadHMSBroadcastMessagesCount:()=>bo,selectUnreadHMSMessagesCount:()=>Ao,selectVideoPlaylist:()=>yr,selectVideoPlaylistAudioTrackByPeerID:()=>Ln,selectVideoPlaylistVideoTrackByPeerID:()=>Cn,selectVideoTrackByID:()=>jr,selectVideoTrackByPeerID:()=>ha,selectWhiteboard:()=>Go,selectWhiteboards:()=>Ps,simulcastMapping:()=>be});module.exports=io(Kc);var Kt=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Kt||{});var rt=()=>({room:{id:"",isConnected:!1,name:"",peers:[],localPeer:"",roomState:"Disconnected",recording:{browser:{running:!1},server:{running:!1},hls:{running:!1}},rtmp:{running:!1},hls:{running:!1,variants:[]},sessionId:""},peers:{},tracks:{},playlist:{audio:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1},video:{list:{},selection:{id:"",hasPrevious:!1,hasNext:!1},progress:0,volume:0,currentTime:0,playbackRate:1}},messages:{byID:{},allIDs:[]},speakers:{},connectionQualities:{},settings:{audioInputDeviceId:"",audioOutputDeviceId:"",videoInputDeviceId:""},devices:{audioInput:[],audioOutput:[],videoInput:[]},roles:{},roleChangeRequests:[],errors:[],sessionStore:{},templateAppData:{},polls:{},whiteboards:{},hideLocalPeer:!1}),st=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var gs=(e=>(e.CHAT="chat",e))(gs||{});var cr=(t=>(t.INFO="info",t.ERROR="error",t))(cr||{}),qt=(C=>(C.PEER_JOINED="PEER_JOINED",C.PEER_LEFT="PEER_LEFT",C.PEER_LIST="PEER_LIST",C.NEW_MESSAGE="NEW_MESSAGE",C.ERROR="ERROR",C.RECONNECTING="RECONNECTING",C.RECONNECTED="RECONNECTED",C.TRACK_ADDED="TRACK_ADDED",C.TRACK_REMOVED="TRACK_REMOVED",C.TRACK_MUTED="TRACK_MUTED",C.TRACK_UNMUTED="TRACK_UNMUTED",C.TRACK_DEGRADED="TRACK_DEGRADED",C.TRACK_RESTORED="TRACK_RESTORED",C.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",C.ROLE_UPDATED="ROLE_UPDATED",C.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",C.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",C.ROOM_ENDED="ROOM_ENDED",C.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",C.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",C.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",C.NAME_UPDATED="NAME_UPDATED",C.METADATA_UPDATED="METADATA_UPDATED",C.POLL_CREATED="POLL_CREATED",C.POLL_STARTED="POLL_STARTED",C.POLL_STOPPED="POLL_STOPPED",C.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",C.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",C))(qt||{});var dr=(t=>(t.audio="audio",t.video="video",t))(dr||{});var E=require("reselect");function Ie(s,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let a=s[r];ro(a)&&(i=at(a)?a:i,t=ot(a)?a:t)}return{video:t,audio:i}}function at(s){return s&&s.type==="audio"}function ot(s){return s&&s.type==="video"}function ro(s){return s&&s.source==="screen"}function jt(s){return s&&s.source==="audioplaylist"}function nt(s){return s&&s.source==="videoplaylist"}function Ts(s){return s?!!(s!=null&&s.degraded):!1}function xe(s,e){return e&&s.tracks[e]?s.tracks[e].enabled:!1}function fs(s,e){return e&&s.tracks[e]?s.tracks[e].displayEnabled:!1}function ct(s){var r;let e=!1,t=!1,i=!1;return(r=s==null?void 0:s.publishParams)!=null&&r.allowed&&(e=s.publishParams.allowed.includes("video"),t=s.publishParams.allowed.includes("audio"),i=s.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}var x=s=>s.room,vs=s=>s.errors,so=(0,E.createSelector)(vs,s=>s.length===0?null:s.at(-1)),ao=(0,E.createSelector)(x,s=>s.id),F=s=>s.peers,dt=s=>s.messages.byID,lr=s=>s.messages.allIDs,D=s=>s.tracks,ur=s=>s.settings,Jt=s=>s.appData,oo=s=>s.devices,Ms=s=>s.speakers,no=s=>s.connectionQualities,Se=(0,E.createSelector)([x],s=>s&&s.isConnected),co=(0,E.createSelector)([Se,x],(s,e)=>s?e.peerCount!==void 0?e.peerCount||1:e.peers.length:Math.max(e.peerCount!==void 0?e.peerCount:e.peers.length-1,0)),lo=s=>s.hideLocalPeer,ie=(0,E.createSelector)([x,F,lo],(s,e,t)=>t?s.peers.filter(i=>s.localPeer!==i).map(i=>e[i]):s.peers.map(i=>e[i])),uo=(0,E.createSelector)(D,s=>Object.values(s)),j=(0,E.createSelector)(x,F,(s,e)=>e[s.localPeer]),ne=(0,E.createSelector)(x,s=>s.localPeer),po=(0,E.createSelector)(j,s=>s==null?void 0:s.name),ho=(0,E.createSelector)(j,s=>s==null?void 0:s.roleName),Y=(0,E.createSelector)(j,s=>s==null?void 0:s.audioTrack),$=(0,E.createSelector)(j,s=>s==null?void 0:s.videoTrack),So=(0,E.createSelector)(j,s=>s==null?void 0:s.auxiliaryTracks),pr=(0,E.createSelector)([Y,$,So],(s,e,t)=>{let i=t?[...t]:[];return s&&i.unshift(s),e&&i.unshift(e),i}),mo=(0,E.createSelector)(ie,s=>s.filter(e=>!e.isLocal)),go=(0,E.createSelector)(F,Ms,(s,e)=>{let t=Object.entries(e).sort((i,r)=>{var n,l;let a=((n=i[1])==null?void 0:n.audioLevel)||0;return(((l=r[1])==null?void 0:l.audioLevel)||0)>a?1:-1});if(t.length>0&&t[0][1].audioLevel&&t[0][1].audioLevel>0){let i=t[0][1].peerID;if(i in s)return s[i]}return null}),To=s=>{let e=j(s);return xe(s,e==null?void 0:e.audioTrack)},Qt=s=>{let e=j(s);return xe(s,e==null?void 0:e.videoTrack)},hr=s=>{let e=j(s);return fs(s,e==null?void 0:e.videoTrack)},zt=(0,E.createSelector)(j,D,(s,e)=>{let{video:t,audio:i}=Ie(e,s);return!!(t||i)}),ys=(0,E.createSelector)(F,D,(s,e)=>{let t;for(let i in s){let r=s[i],{video:a,audio:o}=Ie(e,r);if(a)return r;o&&!t&&(t=r)}return t}),fo=(0,E.createSelector)(ys,s=>!!s),vo=(0,E.createSelector)(F,D,(s,e)=>{for(let t in s){let i=s[t],{audio:r,video:a}=Ie(e,i);if(!a&&r)return i}}),Mo=(0,E.createSelector)(F,D,(s,e)=>{let t=[],i=[];for(let r in s){let a=s[r],{video:o,audio:n}=Ie(e,a);o?t.push(a):n&&i.push(a)}return t.concat(i)}),yo=(0,E.createSelector)(F,D,(s,e)=>{for(let t in e){let i=e[t];if(nt(i)&&ot(i)&&i.peerId)return s[i.peerId]}}),ko=(0,E.createSelector)(F,D,(s,e)=>{for(let t in e){let i=e[t];if(jt(i)&&i.peerId)return s[i.peerId]}}),Eo=(0,E.createSelector)(uo,s=>s.filter(Ts)),Po=(0,E.createSelector)(lr,s=>s.length),Ao=(0,E.createSelector)(dt,s=>Object.values(s).filter(e=>!e.read).length),Ue=(0,E.createSelector)(lr,dt,(s,e)=>{let t=[];return s.forEach(i=>{t.push(e[i])}),t}),ks=(0,E.createSelector)(Ue,s=>s.filter(e=>{var t;return!e.recipientPeer&&!(e.recipientRoles&&((t=e.recipientRoles)==null?void 0:t.length)>0)})),bo=(0,E.createSelector)(ks,s=>s.filter(e=>!e.read).length),J=(0,E.createSelector)([x],s=>s&&s.roomState),Sr=(0,E.createSelector)(J,s=>s==="Preview"),Ro=(0,E.createSelector)(x,s=>s.roomState!=="Disconnected"),re=s=>s.roles,Ho=(0,E.createSelector)([re],s=>Object.keys(s)),lt=(0,E.createSelector)([j,re],(s,e)=>s!=null&&s.roleName?e[s.roleName]:null),Es=s=>{var e;return(e=s.preview)==null?void 0:e.asRole},mr=(0,E.createSelector)([Es,re],(s,e)=>s?e[s]:null),Io=(0,E.createSelector)([lt],s=>{var e;return(e=s==null?void 0:s.subscribeParams)!=null&&e.subscribeToRoles?s.subscribeParams.subscribeToRoles.length>0:!1}),gr=(0,E.createSelector)(lt,s=>s==null?void 0:s.permissions),Co=(0,E.createSelector)(x,s=>s.recording),Lo=(0,E.createSelector)(x,s=>s.rtmp),Do=(0,E.createSelector)(x,s=>s.hls),wo=(0,E.createSelector)(x,s=>s.sessionId),_o=(0,E.createSelector)(x,s=>s.startedAt),No=(0,E.createSelector)(x,s=>!!s.isLargeRoom),Oo=(0,E.createSelector)(x,s=>!!s.isEffectsEnabled),xo=(0,E.createSelector)(x,s=>s.effectsKey),Uo=s=>s.templateAppData,Vo=s=>s.sessionMetadata,Tr=s=>s.polls,Bo=s=>Object.values(s.polls),Fo=(0,E.createSelector)(ie,s=>s.filter(e=>e.isHandRaised)),Ps=s=>s.whiteboards,Go=(0,E.createSelector)(Ps,s=>Object.values(s)[0]);var fr=require("reselect");var As=(s="audio")=>e=>e.playlist[s].list,vr=(s="audio")=>e=>e.playlist[s].selection,bs=(s="audio")=>e=>e.playlist[s].progress,Rs=(s="audio")=>e=>e.playlist[s].currentTime,Hs=(s="audio")=>e=>e.playlist[s].playbackRate,Is=(s="audio")=>e=>e.playlist[s].volume,Cs=(s="audio")=>(0,fr.createSelector)(As(s),e=>Object.values(e)),Ls=(s="audio")=>(0,fr.createSelector)(As(s),vr(s),(e,t)=>{if(t.id)return e[t.id]}),Mr={selection:vr("audio"),progress:bs("audio"),currentTime:Rs("audio"),playbackRate:Hs("audio"),volume:Is("audio"),list:Cs("audio"),selectedItem:Ls("audio")},yr={selection:vr("video"),progress:bs("video"),currentTime:Rs("video"),playbackRate:Hs("video"),volume:Is("video"),list:Cs("video"),selectedItem:Ls("video")};var H=require("reselect");function A(s){return e=>t=>s(t,e)}var kr=(l=>(l[l.VERBOSE=0]="VERBOSE",l[l.DEBUG=1]="DEBUG",l[l.INFO=2]="INFO",l[l.WARN=3]="WARN",l[l.TIME=4]="TIME",l[l.TIMEEND=5]="TIMEEND",l[l.ERROR=6]="ERROR",l[l.NONE=7]="NONE",l))(kr||{}),$o=typeof window!="undefined"&&typeof window.expect!="undefined",d=class{static v(e,...t){this.log(0,e,...t)}static d(e,...t){this.log(1,e,...t)}static i(e,...t){this.log(2,e,...t)}static w(e,...t){this.log(3,e,...t)}static e(e,...t){this.log(6,e,...t)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,t,...i){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(t,...i);break}case 1:{console.debug(t,...i);break}case 2:{console.info(t,...i);break}case 3:{console.warn(t,...i);break}case 6:{console.error(t,...i);break}case 4:{performance.mark(i[0]);break}case 5:{let r=i[0];try{let a=performance.measure(r,r);this.log(1,t,r,a==null?void 0:a.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(a){this.log(1,t,r,a)}break}}}};d.level=$o?7:0;var Ve=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var Ns=require("ua-parser-js"),ce=new Ns.UAParser,N=typeof window!="undefined",Ds,Ce=typeof window=="undefined"&&!((Ds=ce.getBrowser().name)!=null&&Ds.toLowerCase().includes("electron"));var Wo=()=>!Ce,ad=Wo(),Yt=()=>ce.getDevice().type==="mobile",Os=()=>typeof document!="undefined"&&document.hidden,Er=()=>{var s;return((s=ce.getOS().name)==null?void 0:s.toLowerCase())==="ios"},ws,_s,xs=((_s=(ws=ce.getBrowser())==null?void 0:ws.name)==null?void 0:_s.toLowerCase())==="firefox";var Xt=s=>s?`{
2
2
  trackId: ${s.id};
3
3
  kind: ${s.kind};
4
4
  enabled: ${s.enabled};
@@ -13,7 +13,7 @@
13
13
  source: ${this.source};
14
14
  enabled: ${this.enabled};
15
15
  nativeTrack: ${Xt(this.nativeTrack)};
16
- }`}};var Ee=class extends ke{constructor(t,i,r){super(t,i,r);this.type="audio";this.audioElement=null;if(i.kind!=="audio")throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?this.audioElement.volume*100:null}setVolume(t){return c(this,null,function*(){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");yield this.subscribeToAudio(t===0?!1:this.enabled),this.audioElement&&(this.audioElement.volume=t/100)})}setAudioElement(t){d.d("[HMSAudioTrack]",this.logIdentifier,"adding audio element",`${this}`,t),this.audioElement=t}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(t){return c(this,null,function*(){var i;if(!t){d.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){d.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId),this.outputDevice=t)}catch(r){d.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof me&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var Fs=require("uuid");function Go(){if(N&&window){let s=window.location.hostname;return s==="localhost"||s==="127.0.0.1"?"LOCAL":s.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var Be=Go();var Os=require("uuid");var v={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var T=class s extends Error{constructor(t,i,r,a,o,n=!1){super(a);this.code=t;this.name=i;this.message=a;this.description=o;this.isTerminal=n;Object.setPrototypeOf(this,s.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
16
+ }`}};var Ee=class extends ke{constructor(t,i,r){super(t,i,r);this.type="audio";this.audioElement=null;if(i.kind!=="audio")throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?this.audioElement.volume*100:null}setVolume(t){return c(this,null,function*(){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");yield this.subscribeToAudio(t===0?!1:this.enabled),this.audioElement&&(this.audioElement.volume=t/100)})}setAudioElement(t){d.d("[HMSAudioTrack]",this.logIdentifier,"adding audio element",`${this}`,t),this.audioElement=t}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(t){return c(this,null,function*(){var i;if(!t){d.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){d.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&(xs||(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId)),this.outputDevice=t)}catch(r){d.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof me&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};var Ws=require("uuid");function Ko(){if(N&&window){let s=window.location.hostname;return s==="localhost"||s==="127.0.0.1"?"LOCAL":s.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var Be=Ko();var Vs=require("uuid");var v={WebSocketConnectionErrors:{FAILED_TO_CONNECT:1e3,WEBSOCKET_CONNECTION_LOST:1003,ABNORMAL_CLOSE:1006},APIErrors:{SERVER_ERRORS:2e3,INIT_CONFIG_NOT_AVAILABLE:2002,ENDPOINT_UNREACHABLE:2003,INVALID_TOKEN_FORMAT:2004},TracksErrors:{GENERIC_TRACK:3e3,CANT_ACCESS_CAPTURE_DEVICE:3001,DEVICE_NOT_AVAILABLE:3002,DEVICE_IN_USE:3003,DEVICE_LOST_MIDWAY:3004,NOTHING_TO_RETURN:3005,INVALID_VIDEO_SETTINGS:3006,CODEC_CHANGE_NOT_PERMITTED:3007,AUTOPLAY_ERROR:3008,OVER_CONSTRAINED:3009,NO_AUDIO_DETECTED:3010,SYSTEM_DENIED_PERMISSION:3011,CURRENT_TAB_NOT_SHARED:3012,AUDIO_PLAYBACK_ERROR:3013,SELECTED_DEVICE_MISSING:3014},WebrtcErrors:{CREATE_OFFER_FAILED:4001,CREATE_ANSWER_FAILED:4002,SET_LOCAL_DESCRIPTION_FAILED:4003,SET_REMOTE_DESCRIPTION_FAILED:4004,ICE_FAILURE:4005,ICE_DISCONNECTED:4006,STATS_FAILED:4007},WebsocketMethodErrors:{SERVER_ERRORS:5e3,ALREADY_JOINED:5001,CANNOT_JOIN_PREVIEW_IN_PROGRESS:5002},GenericErrors:{NOT_CONNECTED:6e3,SIGNALLING:6001,UNKNOWN:6002,NOT_READY:6003,JSON_PARSING_FAILED:6004,TRACK_METADATA_MISSING:6005,RTC_TRACK_MISSING:6006,PEER_METADATA_MISSING:6007,INVALID_ROLE:6008,PREVIEW_IN_PROGRESS:6009,MISSING_MEDIADEVICES:6010,MISSING_RTCPEERCONNECTION:6011,LOCAL_STORAGE_ACCESS_DENIED:6012,VALIDATION_FAILED:6013},PlaylistErrors:{NO_ENTRY_TO_PLAY:8001,NO_ENTRY_IS_PLAYING:8002}};var T=class s extends Error{constructor(t,i,r,a,o,n=!1){super(a);this.code=t;this.name=i;this.message=a;this.description=o;this.isTerminal=n;Object.setPrototypeOf(this,s.prototype),this.action=r.toString()}toAnalyticsProperties(){return{error_name:this.name,error_code:this.code,error_message:this.message,error_description:this.description,action:this.action,is_terminal:this.isTerminal}}addNativeError(t){this.nativeError=t}toString(){var t;return`{
17
17
  code: ${this.code};
18
18
  name: ${this.name};
19
19
  action: ${this.action};
@@ -21,7 +21,7 @@
21
21
  description: ${this.description};
22
22
  isTerminal: ${this.isTerminal};
23
23
  nativeError: ${(t=this.nativeError)==null?void 0:t.message};
24
- }`}};function Pr(s){switch(s){case"join":return"JOIN";case"offer":return"PUBLISH";case"answer":return"SUBSCRIBE";case"track-update":return"TRACK";default:return"NONE"}}var $o=["join","offer","answer","trickle","on-error","JOIN"],h={WebSocketConnectionErrors:{FailedToConnect(s,e=""){return new T(v.WebSocketConnectionErrors.FAILED_TO_CONNECT,"WebsocketFailedToConnect",s,`[WS]: ${e}`,`[WS]: ${e}`)},WebSocketConnectionLost(s,e=""){return new T(v.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,"WebSocketConnectionLost",s,"Network connection lost ",e)},AbnormalClose(s,e=""){return new T(v.WebSocketConnectionErrors.ABNORMAL_CLOSE,"WebSocketAbnormalClose",s,"Websocket closed abnormally",e)}},APIErrors:{ServerErrors(s,e,t="",i=!0){return new T(s,"ServerErrors",e,`[${e}]: Server error ${t}`,t,i)},EndpointUnreachable(s,e=""){return new T(v.APIErrors.ENDPOINT_UNREACHABLE,"EndpointUnreachable",s,`Endpoint is not reachable - ${e}`,e)},InvalidTokenFormat(s,e=""){return new T(v.APIErrors.INVALID_TOKEN_FORMAT,"InvalidTokenFormat",s,`Token is not in proper JWT format - ${e}`,e,!0)},InitConfigNotAvailable(s,e=""){return new T(v.APIErrors.INIT_CONFIG_NOT_AVAILABLE,"InitError",s,`[INIT]: ${e}`,`[INIT]: ${e}`)}},TracksErrors:{GenericTrack(s,e=""){return new T(v.TracksErrors.GENERIC_TRACK,"GenericTrack",s,`[TRACK]: ${e}`,`[TRACK]: ${e}`)},CantAccessCaptureDevice(s,e,t=""){return new T(v.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,"CantAccessCaptureDevice",s,`User denied permission to access capture device - ${e}`,t)},DeviceNotAvailable(s,e,t=""){return new T(v.TracksErrors.DEVICE_NOT_AVAILABLE,"DeviceNotAvailable",s,`[TRACK]: Capture device is no longer available - ${e}`,t)},DeviceInUse(s,e,t=""){return new T(v.TracksErrors.DEVICE_IN_USE,"DeviceInUse",s,`[TRACK]: Capture device is in use by another application - ${e}`,t)},DeviceLostMidway(s,e,t=""){return new T(v.TracksErrors.DEVICE_LOST_MIDWAY,"DeviceLostMidway",s,`Lost access to capture device midway - ${e}`,t)},NothingToReturn(s,e="",t="There is no media to return. Please select either video or audio or both."){return new T(v.TracksErrors.NOTHING_TO_RETURN,"NothingToReturn",s,t,e)},InvalidVideoSettings(s,e=""){return new T(v.TracksErrors.INVALID_VIDEO_SETTINGS,"InvalidVideoSettings",s,"Cannot enable simulcast when no video settings are provided",e)},AutoplayBlocked(s,e=""){return new T(v.TracksErrors.AUTOPLAY_ERROR,"AutoplayBlocked",s,"Autoplay blocked because the user didn't interact with the document first",e)},CodecChangeNotPermitted(s,e=""){return new T(v.TracksErrors.CODEC_CHANGE_NOT_PERMITTED,"CodecChangeNotPermitted",s,"Codec can't be changed mid call.",e)},OverConstrained(s,e,t=""){return new T(v.TracksErrors.OVER_CONSTRAINED,"OverConstrained",s,`[TRACK]: Requested constraints cannot be satisfied with the device hardware - ${e}`,t)},NoAudioDetected(s,e="Please check the mic or use another audio input"){return new T(v.TracksErrors.NO_AUDIO_DETECTED,"NoAudioDetected",s,"No audio input detected from microphone",e)},SystemDeniedPermission(s,e,t=""){return new T(v.TracksErrors.SYSTEM_DENIED_PERMISSION,"SystemDeniedPermission",s,`Operating System denied permission to access capture device - ${e}`,t)},CurrentTabNotShared(){return new T(v.TracksErrors.CURRENT_TAB_NOT_SHARED,"CurrentTabNotShared","TRACK","The app requires you to share the current tab","You must screen share the current tab in order to proceed")},AudioPlaybackError(s){return new T(v.TracksErrors.AUDIO_PLAYBACK_ERROR,"Audio playback error","TRACK",s,s)},SelectedDeviceMissing(s){return new T(v.TracksErrors.SELECTED_DEVICE_MISSING,"SelectedDeviceMissing","TRACK",`Could not detect selected ${s} device`,`Please check connection to the ${s} device`,!1)}},WebrtcErrors:{CreateOfferFailed(s,e=""){return new T(v.WebrtcErrors.CREATE_OFFER_FAILED,"CreateOfferFailed",s,`[${s.toString()}]: Failed to create offer. `,e)},CreateAnswerFailed(s,e=""){return new T(v.WebrtcErrors.CREATE_ANSWER_FAILED,"CreateAnswerFailed",s,`[${s.toString()}]: Failed to create answer. `,e)},SetLocalDescriptionFailed(s,e=""){return new T(v.WebrtcErrors.SET_LOCAL_DESCRIPTION_FAILED,"SetLocalDescriptionFailed",s,`[${s.toString()}]: Failed to set offer. `,e)},SetRemoteDescriptionFailed(s,e=""){return new T(v.WebrtcErrors.SET_REMOTE_DESCRIPTION_FAILED,"SetRemoteDescriptionFailed",s,`[${s.toString()}]: Failed to set answer. `,e,!0)},ICEFailure(s,e="",t=!1){return new T(v.WebrtcErrors.ICE_FAILURE,"ICEFailure",s,`[${s.toString()}]: Ice connection state FAILED`,e,t)},ICEDisconnected(s,e=""){return new T(v.WebrtcErrors.ICE_DISCONNECTED,"ICEDisconnected",s,`[${s.toString()}]: Ice connection state DISCONNECTED`,e)},StatsFailed(s,e=""){return new T(v.WebrtcErrors.STATS_FAILED,"StatsFailed",s,`Failed to WebRTC get stats - ${e}`,e)}},WebsocketMethodErrors:{ServerErrors(s,e,t){return new T(s,"ServerErrors",e,t,t,$o.includes(e))},AlreadyJoined(s,e=""){return new T(v.WebsocketMethodErrors.ALREADY_JOINED,"AlreadyJoined",s,"[JOIN]: You have already joined this room.",e)},CannotJoinPreviewInProgress(s,e=""){return new T(v.WebsocketMethodErrors.CANNOT_JOIN_PREVIEW_IN_PROGRESS,"CannotJoinPreviewInProgress",s,"[JOIN]: Cannot join if preview is in progress",e)}},GenericErrors:{NotConnected(s,e=""){return new T(v.GenericErrors.NOT_CONNECTED,"NotConnected",s,"Client is not connected",e)},Signalling(s,e){return new T(v.GenericErrors.SIGNALLING,"Signalling",s,`Unknown signalling error: ${s.toString()} ${e} `,e)},Unknown(s,e){return new T(v.GenericErrors.UNKNOWN,"Unknown",s,`Unknown exception: ${e}`,e)},NotReady(s,e=""){return new T(v.GenericErrors.NOT_READY,"NotReady",s,e,e)},JsonParsingFailed(s,e,t=""){return new T(v.GenericErrors.JSON_PARSING_FAILED,"JsonParsingFailed",s,`Failed to parse JSON message - ${e}`,t)},TrackMetadataMissing(s,e=""){return new T(v.GenericErrors.TRACK_METADATA_MISSING,"TrackMetadataMissing",s,"Track Metadata Missing",e)},RTCTrackMissing(s,e=""){return new T(v.GenericErrors.RTC_TRACK_MISSING,"RTCTrackMissing",s,"RTC Track missing",e)},PeerMetadataMissing(s,e=""){return new T(v.GenericErrors.PEER_METADATA_MISSING,"PeerMetadataMissing",s,"Peer Metadata Missing",e)},ValidationFailed(s,e){return new T(v.GenericErrors.VALIDATION_FAILED,"ValidationFailed","VALIDATION",s,e?JSON.stringify(e):"")},InvalidRole(s,e){return new T(v.GenericErrors.INVALID_ROLE,"InvalidRole",s,"Invalid role. Join with valid role",e,!0)},PreviewAlreadyInProgress(s,e=""){return new T(v.GenericErrors.PREVIEW_IN_PROGRESS,"PreviewAlreadyInProgress",s,"[Preview]: Cannot join if preview is in progress",e)},LocalStorageAccessDenied(s="Access to localStorage has been denied"){return new T(v.GenericErrors.LOCAL_STORAGE_ACCESS_DENIED,"LocalStorageAccessDenied","NONE","LocalStorageAccessDenied",s)},MissingMediaDevices(){return new T(v.GenericErrors.MISSING_MEDIADEVICES,"MissingMediaDevices","JOIN","navigator.mediaDevices is undefined. 100ms SDK won't work on this website as WebRTC is not supported on HTTP endpoints(missing navigator.mediaDevices). Please ensure you're using the SDK either on localhost or a valid HTTPS endpoint.","",!0)},MissingRTCPeerConnection(){return new T(v.GenericErrors.MISSING_RTCPEERCONNECTION,"MissingRTCPeerConnection","JOIN","RTCPeerConnection which is a core requirement for WebRTC call was not found, this could be due to an unsupported browser or browser extensions blocking WebRTC","",!0)}},MediaPluginErrors:{PlatformNotSupported(s,e=""){return new T(7001,"PlatformNotSupported",s,"Check HMS Docs to see the list of supported platforms",e)},InitFailed(s,e=""){return new T(7002,"InitFailed",s,"Plugin init failed",e)},ProcessingFailed(s,e=""){return new T(7003,"ProcessingFailed",s,"Plugin processing failed",e)},AddAlreadyInProgress(s,e=""){return new T(7004,"AddAlreadyInProgress",s,"Plugin add already in progress",e)},DeviceNotSupported(s,e=""){return new T(7005,"DeviceNotSupported",s,"Check HMS Docs to see the list of supported devices",e)}},PlaylistErrors:{NoEntryToPlay(s,e){return new T(v.PlaylistErrors.NO_ENTRY_TO_PLAY,"NoEntryToPlay",s,"Reached end of playlist",e)},NoEntryPlaying(s,e){return new T(v.PlaylistErrors.NO_ENTRY_IS_PLAYING,"NoEntryIsPlaying",s,"No entry is playing at this time",e)}}};var Ar=class{constructor(){this.valuesMap=new Map}getItem(e){return this.valuesMap.has(e)?String(this.valuesMap.get(e)):null}setItem(e,t){this.valuesMap.set(e,t)}removeItem(e){this.valuesMap.delete(e)}clear(){this.valuesMap.clear()}key(e){if(arguments.length===0)throw new TypeError("Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present.");return Array.from(this.valuesMap.keys())[e]}get length(){return this.valuesMap.size}},Ns=()=>{try{N&&!localStorage&&(window.localStorage=new Ar)}catch(s){d.e("Error initialising localStorage",h.GenericErrors.LocalStorageAccessDenied())}};var ce=class{constructor(e){this.key=e;this.storage=null}getStorage(){try{return N&&!this.storage&&(Ns(),this.storage=window.localStorage),this.storage}catch(e){return d.e("Error initialising localStorage",h.GenericErrors.LocalStorageAccessDenied()),null}}get(){var i;let e=(i=this.getStorage())==null?void 0:i.getItem(this.key);return e?JSON.parse(e):void 0}set(e){var i;let t=JSON.stringify(e);(i=this.getStorage())==null||i.setItem(this.key,t)}clear(){var e;(e=this.getStorage())==null||e.removeItem(this.key)}};var xs=()=>{let s,e=new ce("hms-analytics-deviceId"),t=e.get();return t?s=t:(s=(0,Os.v4)(),e.set(s)),s};var Us="[VALIDATIONS]";function se(s){return s!=null}var br=()=>{if(!se(RTCPeerConnection)){let s=h.GenericErrors.MissingRTCPeerConnection();throw d.e(Us,s),s}},Rr=()=>{if(!se(navigator.mediaDevices)){let s=h.GenericErrors.MissingMediaDevices();throw d.e(Us,s),s}};var Vs=Hr().version;function ut(s="prod",e){let t="web",i=Be!=="LOCAL"&&s==="prod"?"prod":"debug";if(Ce)return Bs({os:"web_nodejs",os_version:process.version,sdk:t,sdk_version:Vs,env:i,domain:Be,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:"node",framework_version:process.version,framework_sdk_version:e==null?void 0:e.sdkVersion});let r=Se.getOS(),a=Se.getDevice(),o=Se.getBrowser(),n=Ir(`web_${r.name}`),l=r.version||"",u=Ir(`${o.name}_${o.version}`),p=u;return a.type&&(p=`${Ir(`${a.vendor}_${a.type}`)}/${u}`),Bs({os:n,os_version:l,sdk:t,sdk_version:Vs,device_model:p,env:i,domain:Be,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:e==null?void 0:e.type,framework_version:e==null?void 0:e.version,framework_sdk_version:e==null?void 0:e.sdkVersion})}function Ir(s){return s.replace(/ /g,"_")}var Bs=(s,e=",")=>Object.keys(s).filter(t=>se(s[t])).map(t=>`${t}:${s[t]}`).join(e);var I=class{constructor({name:e,level:t,properties:i,includesPII:r,timestamp:a}){this.metadata={peer:{},userAgent:ut()};this.name=e,this.level=t,this.includesPII=r||!1,this.properties=i||{},this.timestamp=a||new Date().getTime(),this.event_id=(0,Fs.v4)(),this.device_id=xs()}toSignalParams(){return{name:this.name,info:y(S({},this.properties),{timestamp:this.timestamp,domain:Be}),timestamp:new Date().getTime()}}};var M=class{static connect(e,t,i=new Date,r=new Date,a){let o=this.eventNameFor("connect",e===void 0),n=e?2:1,l=this.getPropertiesWithError(y(S({},t),{[this.KEY_REQUESTED_AT]:i==null?void 0:i.getTime(),[this.KEY_RESPONDED_AT]:r==null?void 0:r.getTime(),endpoint:a}),e);return new I({name:o,level:n,properties:l})}static disconnect(e,t){let i="disconnected",r=e?2:1,a=this.getPropertiesWithError(t,e);return new I({name:i,level:r,properties:a})}static preview(i){var r=i,{error:e}=r,t=nr(r,["error"]);let a=this.eventNameFor("preview",e===void 0),o=e?2:1,n=this.getPropertiesWithError(t,e);return new I({name:a,level:o,properties:n})}static join(i){var r=i,{error:e}=r,t=nr(r,["error"]);let a=this.eventNameFor("join",e===void 0),o=e?2:1,n=this.getPropertiesWithError(y(S({},t),{is_preview_called:!!t.is_preview_called}),e);return new I({name:a,level:o,properties:n})}static publish({devices:e,settings:t,error:i}){let r=this.eventNameFor("publish",i===void 0),a=i?2:1,o=this.getPropertiesWithError({devices:e,audio:t==null?void 0:t.audio,video:t==null?void 0:t.video},i);return new I({name:r,level:a,properties:o})}static hlsPlayerError(e){return new I({name:"hlsPlayerError",level:2,properties:this.getErrorProperties(e)})}static subscribeFail(e){let t=this.eventNameFor("subscribe",!1),i=2,r=this.getErrorProperties(e);return new I({name:t,level:i,properties:r})}static leave(){return new I({name:"leave",level:1})}static autoplayError(){return new I({name:"autoplayError",level:2})}static audioPlaybackError(e){return new I({name:"audioPlaybackError",level:2,properties:this.getErrorProperties(e)})}static deviceChange({selection:e,type:t,devices:i,error:r}){let a=this.eventNameFor(r?"publish":`device.${t}`,r===void 0),o=r?2:1,n=this.getPropertiesWithError({selection:e,devices:i},r);return new I({name:a,level:o,properties:n})}static performance(e){let t="perf.stats",i=1,r=e.toAnalyticsProperties();return new I({name:t,level:i,properties:r})}static rtcStats(e){let t="rtc.stats",i=1,r=e.toAnalyticsProperties();return new I({name:t,level:i,properties:r})}static rtcStatsFailed(e){let t="rtc.stats.failed",i=2;return new I({name:t,level:i,properties:this.getErrorProperties(e)})}static degradationStats(e,t){let i="video.degradation.stats",r=1,a={degradedAt:e.degradedAt,trackId:e.trackId};if(!t&&e.degradedAt instanceof Date){let o=new Date,n=o.valueOf()-e.degradedAt.valueOf();a=y(S({},a),{duration:n,restoredAt:o})}return new I({name:i,level:r,properties:a})}static audioDetectionFail(e,t){let i=this.getPropertiesWithError({device:t},e),r=2,a="audiopresence.failed";return new I({name:a,level:r,properties:i})}static previewNetworkQuality(e){return new I({name:"perf.networkquality.preview",level:e.error?2:1,properties:e})}static publishStats(e){return new I({name:"publisher.stats",level:1,properties:e})}static subscribeStats(e){return new I({name:"subscriber.stats",level:1,properties:e})}static eventNameFor(e,t){return`${e}.${t?"success":"failed"}`}static getPropertiesWithError(e,t){let i=this.getErrorProperties(t);return e=S(S({},i),e),e}static getErrorProperties(e){return e?e instanceof T?e.toAnalyticsProperties():{error_name:e.name,error_message:e.message,error_description:e.cause}:{}}};M.KEY_REQUESTED_AT="requested_at",M.KEY_RESPONDED_AT="responded_at";var Cr=class{constructor(){this.storage=new ce("hms-device-selection");this.remember=!1;this.TAG="[HMSDeviceStorage]"}setDevices(e){this.devices=e}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find(o=>this.isSame({deviceId:t,groupId:i},o));if(!r){d.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);return}let a=this.storage.get()||{};a[e]=r,this.storage.set(a)}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}},Q=new Cr;var Zt=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Zt||{}),ei=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(ei||{});var ge=class{static failure(e,t){let i="mediaPlugin.failed",r=2,a=S({plugin_name:e},t.toAnalyticsProperties());return new I({name:i,level:r,properties:a})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",a=2,o=S({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new I({name:r,level:a,properties:o})}static audioPluginStats({pluginName:e,duration:t,loadTime:i,sampleRate:r}){let a="mediaPlugin.stats",o=1,n={plugin_name:e,duration:t,load_time:i,sampleRate:r};return new I({name:a,level:o,properties:n})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:a,inputFrameRate:o,pluginFrameRate:n}){let l="mediaPlugin.stats",u=1,p={plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:a,input_frame_rate:o,plugin_frame_rate:n};return new I({name:l,level:u,properties:p})}};var ti=class{constructor(e){this.eventBus=e;this.TAG="[AudioPluginsAnalytics]";this.initTime={},this.addedTimestamps={},this.pluginAdded={},this.pluginSampleRate={}}added(e,t){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.pluginSampleRate[e]=t}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],sampleRate:this.pluginSampleRate[e]};this.eventBus.analytics.publish(ge.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ge.audioPluginFailure(e,this.pluginSampleRate[e],t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let a=h.MediaPluginErrors.InitFailed("AUDIO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.e(this.TAG,a),this.failure(e,a),a}i&&(this.initTime[e]=i)})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.pluginAdded[e],delete this.pluginSampleRate[e]}};var Ko=48e3,qo=()=>navigator.userAgent.indexOf("Firefox")!==-1,pt=class{constructor(e,t){this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new ti(t),this.createAudioContext()}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){d.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let r=h.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,r),d.w("can't add another plugin when previous add is in progress"),r}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(this.pluginsMap.get(t)){d.w(this.TAG,`plugin - ${t} already added.`);return}yield this.validateAndThrow(t,e);try{this.pluginsMap.size===0?yield this.initAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(t,this.audioContext.sampleRate),yield this.analytics.initWithTime(t,()=>c(this,null,function*(){return e.init()})),this.pluginsMap.set(t,e),yield this.processPlugin(e),yield this.connectToDestination()}catch(r){throw d.e(this.TAG,"failed to add plugin",r),r}})}validatePlugin(e){return e.checkSupport(this.audioContext)}validateAndThrow(e,t){return c(this,null,function*(){let i=this.validatePlugin(t);if(i.isSupported)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=h.MediaPluginErrors.PlatformNotSupported("AUDIO_PLUGINS","platform not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}else if(i.errType==="DEVICE_NOT_SUPPORTED"){let r=h.MediaPluginErrors.DeviceNotSupported("AUDIO_PLUGINS","audio device not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}})}removePlugin(e){return c(this,null,function*(){yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),d.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()})}cleanup(){return c(this,null,function*(){var e,t,i;for(let r of this.pluginsMap.values())yield this.removePluginInternal(r);yield this.hmsTrack.setProcessedTrack(void 0),(e=this.sourceNode)==null||e.disconnect(),(t=this.prevAudioNode)==null||t.disconnect(),(i=this.outputTrack)==null||i.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0})}closeContext(){return c(this,null,function*(){var e;(e=this.audioContext)==null||e.close(),this.audioContext=void 0})}reprocessPlugins(){return c(this,null,function*(){if(this.pluginsMap.size===0||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initAudioNodes();for(let t of e)yield this.addPlugin(t)})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){if(!this.sourceNode){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e)}if(!this.destinationNode){this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0];try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw d.e(this.TAG,"error in setting processed track",e),e}}}})}processPlugin(e){return c(this,null,function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();d.e(this.TAG,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}})}connectToDestination(){return c(this,null,function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){d.e(this.TAG,"error in connecting to destination node",e)}})}removePluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!this.pluginsMap.get(t)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}createAudioContext(){this.audioContext||(qo()?this.audioContext=new AudioContext:this.audioContext=new AudioContext({sampleRate:Ko}))}};var Lr=it(require("webrtc-adapter"));function jo(s,e){let t=s.toLowerCase();return t.includes("device not found")?h.TracksErrors.DeviceNotAvailable("TRACK",e,s):t.includes("permission denied")?h.TracksErrors.CantAccessCaptureDevice("TRACK",e,s):h.TracksErrors.GenericTrack("TRACK",s)}function Jo(s,e=""){if(Lr.default.browserDetails.browser==="chrome"&&s.name==="NotAllowedError"&&s.message.includes("denied by system"))return h.TracksErrors.SystemDeniedPermission("TRACK",e,s.message);if(Lr.default.browserDetails.browser==="firefox"&&s.name==="NotFoundError"){let i=h.TracksErrors.SystemDeniedPermission("TRACK",e,s.message);return i.description=`Capture device is either blocked at Operating System level or not available - ${e}`,i}switch(s.name){case"OverconstrainedError":return h.TracksErrors.OverConstrained("TRACK",e,s.constraint);case"NotAllowedError":return h.TracksErrors.CantAccessCaptureDevice("TRACK",e,s.message);case"NotFoundError":return h.TracksErrors.DeviceNotAvailable("TRACK",e,s.message);case"NotReadableError":return h.TracksErrors.DeviceInUse("TRACK",e,s.message);case"TypeError":return h.TracksErrors.NothingToReturn("TRACK",s.message);default:return jo(s.message,e)}}function Fe(s,e){let t=Jo(s,e);return t.addNativeError(s),t}function Gs(s){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:s?s.toConstraints():!1})).getAudioTracks()[0]}catch(e){throw Fe(e,"audio")}})}function $s(s){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:s?s.toConstraints():!1})).getVideoTracks()[0]}catch(e){throw Fe(e,"video")}})}function de(s){return"canvas"in s||s.label==="MediaStreamAudioDestinationNode"||s.label===""}var Pe={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=new AudioContext),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(s){d.e("AudioContext",s)}})}};var Ae=class{constructor(e=1/0){this.capacity=e;this.storage=[]}size(){return this.storage.length}toList(){return this.storage.slice(0)}enqueue(e){this.size()===this.capacity&&this.dequeue(),this.storage.push(e)}dequeue(){return this.storage.shift()}aggregate(e){return e(this.storage)}};var zo=`(function metronomeWorkerSetup() {
24
+ }`}};function Pr(s){switch(s){case"join":return"JOIN";case"offer":return"PUBLISH";case"answer":return"SUBSCRIBE";case"track-update":return"TRACK";default:return"NONE"}}var qo=["join","offer","answer","trickle","on-error","JOIN"],h={WebSocketConnectionErrors:{FailedToConnect(s,e=""){return new T(v.WebSocketConnectionErrors.FAILED_TO_CONNECT,"WebsocketFailedToConnect",s,`[WS]: ${e}`,`[WS]: ${e}`)},WebSocketConnectionLost(s,e=""){return new T(v.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,"WebSocketConnectionLost",s,"Network connection lost ",e)},AbnormalClose(s,e=""){return new T(v.WebSocketConnectionErrors.ABNORMAL_CLOSE,"WebSocketAbnormalClose",s,"Websocket closed abnormally",e)}},APIErrors:{ServerErrors(s,e,t="",i=!0){return new T(s,"ServerErrors",e,`[${e}]: Server error ${t}`,t,i)},EndpointUnreachable(s,e=""){return new T(v.APIErrors.ENDPOINT_UNREACHABLE,"EndpointUnreachable",s,`Endpoint is not reachable - ${e}`,e)},InvalidTokenFormat(s,e=""){return new T(v.APIErrors.INVALID_TOKEN_FORMAT,"InvalidTokenFormat",s,`Token is not in proper JWT format - ${e}`,e,!0)},InitConfigNotAvailable(s,e=""){return new T(v.APIErrors.INIT_CONFIG_NOT_AVAILABLE,"InitError",s,`[INIT]: ${e}`,`[INIT]: ${e}`)}},TracksErrors:{GenericTrack(s,e=""){return new T(v.TracksErrors.GENERIC_TRACK,"GenericTrack",s,`[TRACK]: ${e}`,`[TRACK]: ${e}`)},CantAccessCaptureDevice(s,e,t=""){return new T(v.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,"CantAccessCaptureDevice",s,`User denied permission to access capture device - ${e}`,t)},DeviceNotAvailable(s,e,t=""){return new T(v.TracksErrors.DEVICE_NOT_AVAILABLE,"DeviceNotAvailable",s,`[TRACK]: Capture device is no longer available - ${e}`,t)},DeviceInUse(s,e,t=""){return new T(v.TracksErrors.DEVICE_IN_USE,"DeviceInUse",s,`[TRACK]: Capture device is in use by another application - ${e}`,t)},DeviceLostMidway(s,e,t=""){return new T(v.TracksErrors.DEVICE_LOST_MIDWAY,"DeviceLostMidway",s,`Lost access to capture device midway - ${e}`,t)},NothingToReturn(s,e="",t="There is no media to return. Please select either video or audio or both."){return new T(v.TracksErrors.NOTHING_TO_RETURN,"NothingToReturn",s,t,e)},InvalidVideoSettings(s,e=""){return new T(v.TracksErrors.INVALID_VIDEO_SETTINGS,"InvalidVideoSettings",s,"Cannot enable simulcast when no video settings are provided",e)},AutoplayBlocked(s,e=""){return new T(v.TracksErrors.AUTOPLAY_ERROR,"AutoplayBlocked",s,"Autoplay blocked because the user didn't interact with the document first",e)},CodecChangeNotPermitted(s,e=""){return new T(v.TracksErrors.CODEC_CHANGE_NOT_PERMITTED,"CodecChangeNotPermitted",s,"Codec can't be changed mid call.",e)},OverConstrained(s,e,t=""){return new T(v.TracksErrors.OVER_CONSTRAINED,"OverConstrained",s,`[TRACK]: Requested constraints cannot be satisfied with the device hardware - ${e}`,t)},NoAudioDetected(s,e="Please check the mic or use another audio input"){return new T(v.TracksErrors.NO_AUDIO_DETECTED,"NoAudioDetected",s,"No audio input detected from microphone",e)},SystemDeniedPermission(s,e,t=""){return new T(v.TracksErrors.SYSTEM_DENIED_PERMISSION,"SystemDeniedPermission",s,`Operating System denied permission to access capture device - ${e}`,t)},CurrentTabNotShared(){return new T(v.TracksErrors.CURRENT_TAB_NOT_SHARED,"CurrentTabNotShared","TRACK","The app requires you to share the current tab","You must screen share the current tab in order to proceed")},AudioPlaybackError(s){return new T(v.TracksErrors.AUDIO_PLAYBACK_ERROR,"Audio playback error","TRACK",s,s)},SelectedDeviceMissing(s){return new T(v.TracksErrors.SELECTED_DEVICE_MISSING,"SelectedDeviceMissing","TRACK",`Could not detect selected ${s} device`,`Please check connection to the ${s} device`,!1)}},WebrtcErrors:{CreateOfferFailed(s,e=""){return new T(v.WebrtcErrors.CREATE_OFFER_FAILED,"CreateOfferFailed",s,`[${s.toString()}]: Failed to create offer. `,e)},CreateAnswerFailed(s,e=""){return new T(v.WebrtcErrors.CREATE_ANSWER_FAILED,"CreateAnswerFailed",s,`[${s.toString()}]: Failed to create answer. `,e)},SetLocalDescriptionFailed(s,e=""){return new T(v.WebrtcErrors.SET_LOCAL_DESCRIPTION_FAILED,"SetLocalDescriptionFailed",s,`[${s.toString()}]: Failed to set offer. `,e)},SetRemoteDescriptionFailed(s,e=""){return new T(v.WebrtcErrors.SET_REMOTE_DESCRIPTION_FAILED,"SetRemoteDescriptionFailed",s,`[${s.toString()}]: Failed to set answer. `,e,!0)},ICEFailure(s,e="",t=!1){return new T(v.WebrtcErrors.ICE_FAILURE,"ICEFailure",s,`[${s.toString()}]: Ice connection state FAILED`,e,t)},ICEDisconnected(s,e=""){return new T(v.WebrtcErrors.ICE_DISCONNECTED,"ICEDisconnected",s,`[${s.toString()}]: Ice connection state DISCONNECTED`,e)},StatsFailed(s,e=""){return new T(v.WebrtcErrors.STATS_FAILED,"StatsFailed",s,`Failed to WebRTC get stats - ${e}`,e)}},WebsocketMethodErrors:{ServerErrors(s,e,t){return new T(s,"ServerErrors",e,t,t,qo.includes(e))},AlreadyJoined(s,e=""){return new T(v.WebsocketMethodErrors.ALREADY_JOINED,"AlreadyJoined",s,"[JOIN]: You have already joined this room.",e)},CannotJoinPreviewInProgress(s,e=""){return new T(v.WebsocketMethodErrors.CANNOT_JOIN_PREVIEW_IN_PROGRESS,"CannotJoinPreviewInProgress",s,"[JOIN]: Cannot join if preview is in progress",e)}},GenericErrors:{NotConnected(s,e=""){return new T(v.GenericErrors.NOT_CONNECTED,"NotConnected",s,"Client is not connected",e)},Signalling(s,e){return new T(v.GenericErrors.SIGNALLING,"Signalling",s,`Unknown signalling error: ${s.toString()} ${e} `,e)},Unknown(s,e){return new T(v.GenericErrors.UNKNOWN,"Unknown",s,`Unknown exception: ${e}`,e)},NotReady(s,e=""){return new T(v.GenericErrors.NOT_READY,"NotReady",s,e,e)},JsonParsingFailed(s,e,t=""){return new T(v.GenericErrors.JSON_PARSING_FAILED,"JsonParsingFailed",s,`Failed to parse JSON message - ${e}`,t)},TrackMetadataMissing(s,e=""){return new T(v.GenericErrors.TRACK_METADATA_MISSING,"TrackMetadataMissing",s,"Track Metadata Missing",e)},RTCTrackMissing(s,e=""){return new T(v.GenericErrors.RTC_TRACK_MISSING,"RTCTrackMissing",s,"RTC Track missing",e)},PeerMetadataMissing(s,e=""){return new T(v.GenericErrors.PEER_METADATA_MISSING,"PeerMetadataMissing",s,"Peer Metadata Missing",e)},ValidationFailed(s,e){return new T(v.GenericErrors.VALIDATION_FAILED,"ValidationFailed","VALIDATION",s,e?JSON.stringify(e):"")},InvalidRole(s,e){return new T(v.GenericErrors.INVALID_ROLE,"InvalidRole",s,"Invalid role. Join with valid role",e,!0)},PreviewAlreadyInProgress(s,e=""){return new T(v.GenericErrors.PREVIEW_IN_PROGRESS,"PreviewAlreadyInProgress",s,"[Preview]: Cannot join if preview is in progress",e)},LocalStorageAccessDenied(s="Access to localStorage has been denied"){return new T(v.GenericErrors.LOCAL_STORAGE_ACCESS_DENIED,"LocalStorageAccessDenied","NONE","LocalStorageAccessDenied",s)},MissingMediaDevices(){return new T(v.GenericErrors.MISSING_MEDIADEVICES,"MissingMediaDevices","JOIN","navigator.mediaDevices is undefined. 100ms SDK won't work on this website as WebRTC is not supported on HTTP endpoints(missing navigator.mediaDevices). Please ensure you're using the SDK either on localhost or a valid HTTPS endpoint.","",!0)},MissingRTCPeerConnection(){return new T(v.GenericErrors.MISSING_RTCPEERCONNECTION,"MissingRTCPeerConnection","JOIN","RTCPeerConnection which is a core requirement for WebRTC call was not found, this could be due to an unsupported browser or browser extensions blocking WebRTC","",!0)}},MediaPluginErrors:{PlatformNotSupported(s,e=""){return new T(7001,"PlatformNotSupported",s,"Check HMS Docs to see the list of supported platforms",e)},InitFailed(s,e=""){return new T(7002,"InitFailed",s,"Plugin init failed",e)},ProcessingFailed(s,e=""){return new T(7003,"ProcessingFailed",s,"Plugin processing failed",e)},AddAlreadyInProgress(s,e=""){return new T(7004,"AddAlreadyInProgress",s,"Plugin add already in progress",e)},DeviceNotSupported(s,e=""){return new T(7005,"DeviceNotSupported",s,"Check HMS Docs to see the list of supported devices",e)}},PlaylistErrors:{NoEntryToPlay(s,e){return new T(v.PlaylistErrors.NO_ENTRY_TO_PLAY,"NoEntryToPlay",s,"Reached end of playlist",e)},NoEntryPlaying(s,e){return new T(v.PlaylistErrors.NO_ENTRY_IS_PLAYING,"NoEntryIsPlaying",s,"No entry is playing at this time",e)}}};var Ar=class{constructor(){this.valuesMap=new Map}getItem(e){return this.valuesMap.has(e)?String(this.valuesMap.get(e)):null}setItem(e,t){this.valuesMap.set(e,t)}removeItem(e){this.valuesMap.delete(e)}clear(){this.valuesMap.clear()}key(e){if(arguments.length===0)throw new TypeError("Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present.");return Array.from(this.valuesMap.keys())[e]}get length(){return this.valuesMap.size}},Us=()=>{try{N&&!localStorage&&(window.localStorage=new Ar)}catch(s){d.e("Error initialising localStorage",h.GenericErrors.LocalStorageAccessDenied())}};var de=class{constructor(e){this.key=e;this.storage=null}getStorage(){try{return N&&!this.storage&&(Us(),this.storage=window.localStorage),this.storage}catch(e){return d.e("Error initialising localStorage",h.GenericErrors.LocalStorageAccessDenied()),null}}get(){var i;let e=(i=this.getStorage())==null?void 0:i.getItem(this.key);return e?JSON.parse(e):void 0}set(e){var i;let t=JSON.stringify(e);(i=this.getStorage())==null||i.setItem(this.key,t)}clear(){var e;(e=this.getStorage())==null||e.removeItem(this.key)}};var Bs=()=>{let s,e=new de("hms-analytics-deviceId"),t=e.get();return t?s=t:(s=(0,Vs.v4)(),e.set(s)),s};var Fs="[VALIDATIONS]";function se(s){return s!=null}var br=()=>{if(!se(RTCPeerConnection)){let s=h.GenericErrors.MissingRTCPeerConnection();throw d.e(Fs,s),s}},Rr=()=>{if(!se(navigator.mediaDevices)){let s=h.GenericErrors.MissingMediaDevices();throw d.e(Fs,s),s}};var Gs=Hr().version;function ut(s="prod",e){let t="web",i=Be!=="LOCAL"&&s==="prod"?"prod":"debug";if(Ce)return $s({os:"web_nodejs",os_version:process.version,sdk:t,sdk_version:Gs,env:i,domain:Be,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:"node",framework_version:process.version,framework_sdk_version:e==null?void 0:e.sdkVersion});let r=ce.getOS(),a=ce.getDevice(),o=ce.getBrowser(),n=Ir(`web_${r.name}`),l=r.version||"",u=Ir(`${o.name}_${o.version}`),p=u;return a.type&&(p=`${Ir(`${a.vendor}_${a.type}`)}/${u}`),$s({os:n,os_version:l,sdk:t,sdk_version:Gs,device_model:p,env:i,domain:Be,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:e==null?void 0:e.type,framework_version:e==null?void 0:e.version,framework_sdk_version:e==null?void 0:e.sdkVersion})}function Ir(s){return s.replace(/ /g,"_")}var $s=(s,e=",")=>Object.keys(s).filter(t=>se(s[t])).map(t=>`${t}:${s[t]}`).join(e);var I=class{constructor({name:e,level:t,properties:i,includesPII:r,timestamp:a}){this.metadata={peer:{},userAgent:ut()};this.name=e,this.level=t,this.includesPII=r||!1,this.properties=i||{},this.timestamp=a||new Date().getTime(),this.event_id=(0,Ws.v4)(),this.device_id=Bs()}toSignalParams(){return{name:this.name,info:y(S({},this.properties),{timestamp:this.timestamp,domain:Be}),timestamp:new Date().getTime()}}};var M=class{static connect(e,t,i=new Date,r=new Date,a){let o=this.eventNameFor("connect",e===void 0),n=e?2:1,l=this.getPropertiesWithError(y(S({},t),{[this.KEY_REQUESTED_AT]:i==null?void 0:i.getTime(),[this.KEY_RESPONDED_AT]:r==null?void 0:r.getTime(),endpoint:a}),e);return new I({name:o,level:n,properties:l})}static disconnect(e,t){let i="disconnected",r=e?2:1,a=this.getPropertiesWithError(t,e);return new I({name:i,level:r,properties:a})}static preview(i){var r=i,{error:e}=r,t=nr(r,["error"]);let a=this.eventNameFor("preview",e===void 0),o=e?2:1,n=this.getPropertiesWithError(t,e);return new I({name:a,level:o,properties:n})}static join(i){var r=i,{error:e}=r,t=nr(r,["error"]);let a=this.eventNameFor("join",e===void 0),o=e?2:1,n=this.getPropertiesWithError(y(S({},t),{is_preview_called:!!t.is_preview_called}),e);return new I({name:a,level:o,properties:n})}static publish({devices:e,settings:t,error:i}){let r=this.eventNameFor("publish",i===void 0),a=i?2:1,o=this.getPropertiesWithError({devices:e,audio:t==null?void 0:t.audio,video:t==null?void 0:t.video},i);return new I({name:r,level:a,properties:o})}static hlsPlayerError(e){return new I({name:"hlsPlayerError",level:2,properties:this.getErrorProperties(e)})}static subscribeFail(e){let t=this.eventNameFor("subscribe",!1),i=2,r=this.getErrorProperties(e);return new I({name:t,level:i,properties:r})}static leave(){return new I({name:"leave",level:1})}static autoplayError(){return new I({name:"autoplayError",level:2})}static audioPlaybackError(e){return new I({name:"audioPlaybackError",level:2,properties:this.getErrorProperties(e)})}static deviceChange({selection:e,type:t,devices:i,error:r}){let a=this.eventNameFor(r?"publish":`device.${t}`,r===void 0),o=r?2:1,n=this.getPropertiesWithError({selection:e,devices:i},r);return new I({name:a,level:o,properties:n})}static performance(e){let t="perf.stats",i=1,r=e.toAnalyticsProperties();return new I({name:t,level:i,properties:r})}static rtcStats(e){let t="rtc.stats",i=1,r=e.toAnalyticsProperties();return new I({name:t,level:i,properties:r})}static rtcStatsFailed(e){let t="rtc.stats.failed",i=2;return new I({name:t,level:i,properties:this.getErrorProperties(e)})}static degradationStats(e,t){let i="video.degradation.stats",r=1,a={degradedAt:e.degradedAt,trackId:e.trackId};if(!t&&e.degradedAt instanceof Date){let o=new Date,n=o.valueOf()-e.degradedAt.valueOf();a=y(S({},a),{duration:n,restoredAt:o})}return new I({name:i,level:r,properties:a})}static audioDetectionFail(e,t){let i=this.getPropertiesWithError({device:t},e),r=2,a="audiopresence.failed";return new I({name:a,level:r,properties:i})}static previewNetworkQuality(e){return new I({name:"perf.networkquality.preview",level:e.error?2:1,properties:e})}static publishStats(e){return new I({name:"publisher.stats",level:1,properties:e})}static subscribeStats(e){return new I({name:"subscriber.stats",level:1,properties:e})}static eventNameFor(e,t){return`${e}.${t?"success":"failed"}`}static getPropertiesWithError(e,t){let i=this.getErrorProperties(t);return e=S(S({},i),e),e}static getErrorProperties(e){return e?e instanceof T?e.toAnalyticsProperties():{error_name:e.name,error_message:e.message,error_description:e.cause}:{}}};M.KEY_REQUESTED_AT="requested_at",M.KEY_RESPONDED_AT="responded_at";var Cr=class{constructor(){this.storage=new de("hms-device-selection");this.remember=!1;this.TAG="[HMSDeviceStorage]"}setDevices(e){this.devices=e}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find(o=>this.isSame({deviceId:t,groupId:i},o));if(!r){d.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);return}let a=this.storage.get()||{};a[e]=r,this.storage.set(a)}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}},Q=new Cr;var Zt=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(Zt||{}),ei=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(ei||{});var ge=class{static failure(e,t){let i="mediaPlugin.failed",r=2,a=S({plugin_name:e},t.toAnalyticsProperties());return new I({name:i,level:r,properties:a})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",a=2,o=S({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new I({name:r,level:a,properties:o})}static audioPluginStats({pluginName:e,duration:t,loadTime:i,sampleRate:r}){let a="mediaPlugin.stats",o=1,n={plugin_name:e,duration:t,load_time:i,sampleRate:r};return new I({name:a,level:o,properties:n})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:a,inputFrameRate:o,pluginFrameRate:n}){let l="mediaPlugin.stats",u=1,p={plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:a,input_frame_rate:o,plugin_frame_rate:n};return new I({name:l,level:u,properties:p})}};var ti=class{constructor(e){this.eventBus=e;this.TAG="[AudioPluginsAnalytics]";this.initTime={},this.addedTimestamps={},this.pluginAdded={},this.pluginSampleRate={}}added(e,t){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.pluginSampleRate[e]=t}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],sampleRate:this.pluginSampleRate[e]};this.eventBus.analytics.publish(ge.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ge.audioPluginFailure(e,this.pluginSampleRate[e],t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let a=h.MediaPluginErrors.InitFailed("AUDIO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.e(this.TAG,a),this.failure(e,a),a}i&&(this.initTime[e]=i)})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.pluginAdded[e],delete this.pluginSampleRate[e]}};var Jo=48e3,Qo=()=>navigator.userAgent.indexOf("Firefox")!==-1,pt=class{constructor(e,t){this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new ti(t),this.createAudioContext()}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){d.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let r=h.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,r),d.w("can't add another plugin when previous add is in progress"),r}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(this.pluginsMap.get(t)){d.w(this.TAG,`plugin - ${t} already added.`);return}yield this.validateAndThrow(t,e);try{this.pluginsMap.size===0?yield this.initAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(t,this.audioContext.sampleRate),yield this.analytics.initWithTime(t,()=>c(this,null,function*(){return e.init()})),this.pluginsMap.set(t,e),yield this.processPlugin(e),yield this.connectToDestination()}catch(r){throw d.e(this.TAG,"failed to add plugin",r),r}})}validatePlugin(e){return e.checkSupport(this.audioContext)}validateAndThrow(e,t){return c(this,null,function*(){let i=this.validatePlugin(t);if(i.isSupported)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=h.MediaPluginErrors.PlatformNotSupported("AUDIO_PLUGINS","platform not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}else if(i.errType==="DEVICE_NOT_SUPPORTED"){let r=h.MediaPluginErrors.DeviceNotSupported("AUDIO_PLUGINS","audio device not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}})}removePlugin(e){return c(this,null,function*(){yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),d.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()})}cleanup(){return c(this,null,function*(){var e,t,i;for(let r of this.pluginsMap.values())yield this.removePluginInternal(r);yield this.hmsTrack.setProcessedTrack(void 0),(e=this.sourceNode)==null||e.disconnect(),(t=this.prevAudioNode)==null||t.disconnect(),(i=this.outputTrack)==null||i.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0})}closeContext(){return c(this,null,function*(){var e;(e=this.audioContext)==null||e.close(),this.audioContext=void 0})}reprocessPlugins(){return c(this,null,function*(){if(this.pluginsMap.size===0||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initAudioNodes();for(let t of e)yield this.addPlugin(t)})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){if(!this.sourceNode){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e)}if(!this.destinationNode){this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0];try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw d.e(this.TAG,"error in setting processed track",e),e}}}})}processPlugin(e){return c(this,null,function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();d.e(this.TAG,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}})}connectToDestination(){return c(this,null,function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){d.e(this.TAG,"error in connecting to destination node",e)}})}removePluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!this.pluginsMap.get(t)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}createAudioContext(){this.audioContext||(Qo()?this.audioContext=new AudioContext:this.audioContext=new AudioContext({sampleRate:Jo}))}};var Lr=it(require("webrtc-adapter"));function zo(s,e){let t=s.toLowerCase();return t.includes("device not found")?h.TracksErrors.DeviceNotAvailable("TRACK",e,s):t.includes("permission denied")?h.TracksErrors.CantAccessCaptureDevice("TRACK",e,s):h.TracksErrors.GenericTrack("TRACK",s)}function Yo(s,e=""){if(Lr.default.browserDetails.browser==="chrome"&&s.name==="NotAllowedError"&&s.message.includes("denied by system"))return h.TracksErrors.SystemDeniedPermission("TRACK",e,s.message);if(Lr.default.browserDetails.browser==="firefox"&&s.name==="NotFoundError"){let i=h.TracksErrors.SystemDeniedPermission("TRACK",e,s.message);return i.description=`Capture device is either blocked at Operating System level or not available - ${e}`,i}switch(s.name){case"OverconstrainedError":return h.TracksErrors.OverConstrained("TRACK",e,s.constraint);case"NotAllowedError":return h.TracksErrors.CantAccessCaptureDevice("TRACK",e,s.message);case"NotFoundError":return h.TracksErrors.DeviceNotAvailable("TRACK",e,s.message);case"NotReadableError":return h.TracksErrors.DeviceInUse("TRACK",e,s.message);case"TypeError":return h.TracksErrors.NothingToReturn("TRACK",s.message);default:return zo(s.message,e)}}function Fe(s,e){let t=Yo(s,e);return t.addNativeError(s),t}function Ks(s){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({audio:s?s.toConstraints():!1})).getAudioTracks()[0]}catch(e){throw Fe(e,"audio")}})}function qs(s){return c(this,null,function*(){try{return(yield navigator.mediaDevices.getUserMedia({video:s?s.toConstraints():!1})).getVideoTracks()[0]}catch(e){throw Fe(e,"video")}})}function le(s){return"canvas"in s||s.label==="MediaStreamAudioDestinationNode"||s.label===""}var Pe={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=new AudioContext),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(s){d.e("AudioContext",s)}})}};var Ae=class{constructor(e=1/0){this.capacity=e;this.storage=[]}size(){return this.storage.length}toList(){return this.storage.slice(0)}enqueue(e){this.size()===this.capacity&&this.dequeue(),this.storage.push(e)}dequeue(){return this.storage.shift()}aggregate(e){return e(this.storage)}};var Zo=`(function metronomeWorkerSetup() {
25
25
  function ticker() {
26
26
  self.postMessage('tick');
27
27
  }
@@ -35,11 +35,11 @@
35
35
  break;
36
36
  }
37
37
  };
38
- })()`;function X(s){if(s<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,s)})}function le(s){if(s<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return X(s);let e=new Worker(URL.createObjectURL(new Blob([zo],{type:"application/javascript"})));return e.postMessage(["start",s]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function ii(s,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{s.apply(r,i)},e)}}var Yo=35,Xo=5,ri=class{constructor(e,t,i){this.track=e;this.audioLevelEvent=t;this.silenceEvent=i;this.TAG="[TrackAudioLevelMonitor]";this.audioLevel=0;this.isMonitored=!1;this.interval=100;this.historyInterval=700;this.history=new Ae(this.historyInterval/this.interval);this.detectSilence=()=>c(this,null,function*(){let i=0;for(;this.isMonitored;){if(this.track.enabled)if(this.isSilentThisInstant()){if(i++,i>50){this.silenceEvent.publish({track:this.track});break}}else break;yield X(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r)}catch(r){d.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>d.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}this.sendAudioLevel(0),this.isMonitored=!1}loop(){return c(this,null,function*(){for(;this.isMonitored;)this.sendAudioLevel(this.getMaxAudioLevelOverPeriod()),yield X(this.interval)})}sendAudioLevel(e=0){if(e=e>Yo?e:0,Math.abs(this.audioLevel-e)>Xo){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=this.calculateAudioLevel();return e!==void 0&&this.history.enqueue(e),this.history.aggregate(t=>Math.max(...t))}calculateAudioLevel(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(e);let t=.009,i=t;for(let o of e)i=Math.max(i,(o-128)/128);let r=(Math.log(t)-Math.log(i))/Math.log(t);return Math.ceil(Math.min(Math.max(r*100,0),100))}isSilentThisInstant(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);return this.analyserNode.getByteTimeDomainData(e),!e.some(t=>t!==128&&t!==0)}createAnalyserNodeForStream(e){let t=Pe.getAudioContext(),i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i}};var Dr=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Dr||{});var be={f:"high",h:"medium",q:"low"};var wr=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(wr||{});var ae=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._advanced=[{googEchoCancellation:{exact:!0}},{googExperimentalEchoCancellation:{exact:!0}},{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{googHighpassFilter:{exact:!0}},{googAudioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}build(){return new Le(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced)}},Le=class{constructor(e,t,i,r,a){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=a}toConstraints(){return{deviceId:this.deviceId,advanced:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var ee=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new De(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},De=class{constructor(e,t,i,r,a,o,n,l){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=a,this.advanced=o,this.facingMode=l}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Yt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var ht=class{constructor(){this._video=new ee().build();this._audio=new ae().build();this._screen=new ee().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw h.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw h.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new Ge(this._video,this._audio,this._simulcast,this._screen||void 0)}},Ge=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=S(S({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=S(S({},this.video.toAnalyticsProperties()),e)),e}};function Ks(s,e){return function(i){return i in s&&s[i]!==e[i]}}var oe=class s extends Ee{constructor(t,i,r,a,o=new ae().build()){super(t,i,r);this.eventBus=a;this.TAG="[HMSLocalAudioTrack]";this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){document.visibilityState==="visible"&&(yield this.replaceTrackWith(this.settings))});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){d.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Ks(t,this.settings);r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("advanced")&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){Ks(t,this.settings)("deviceId")&&(this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,yield this.replaceTrackWith(t),i||Q.updateSelection("audioInput",{deviceId:t.deviceId,groupId:this.nativeTrack.getSettings().groupId}))});t.tracks.push(this),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!de(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new pt(this,a),this.setFirstTrackId(i.id),Er()&&N&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();let r=!!this.audioLevelMonitor;try{let a=yield Gs(t);a.enabled=this.enabled,d.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",a),yield this.stream.replaceStreamTrack(i,a),this.nativeTrack=a,yield this.replaceSenderTrack(),r&&this.initAudioLevelMonitor()}catch(a){throw this.isPublished&&this.eventBus.analytics.publish(M.publish({error:a})),a}try{yield this.pluginsManager.reprocessPlugins()}catch(a){this.eventBus.audioPluginFailed.publish(a)}})}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(t&&de(this.nativeTrack)&&(yield this.replaceTrackWith(this.settings)),yield q(s.prototype,this,"setEnabled").call(this,t),t&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),this.eventBus.localAudioEnabled.publish({enabled:t,track:this}))})}isPublishedTrackId(t){return this.publishedTrackId===t}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(de(this.nativeTrack)){this.settings=r;return}yield this.handleDeviceChange(r,i),yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.pluginsManager.getPlugins()}addPlugin(t){return c(this,null,function*(){return this.pluginsManager.addPlugin(t)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}setProcessedTrack(t){return c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack()})}initAudioLevelMonitor(){this.audioLevelMonitor&&this.destroyAudioLevelMonitor(),d.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new ri(this,this.eventBus.trackAudioLevelUpdate,this.eventBus.localAudioSilence),this.audioLevelMonitor.start(),this.audioLevelMonitor.detectSilence()}destroyAudioLevelMonitor(){var t;(t=this.audioLevelMonitor)==null||t.stop(),this.audioLevelMonitor=void 0}cleanup(){return c(this,null,function*(){var t;q(s.prototype,this,"cleanup").call(this),yield this.pluginsManager.cleanup(),yield this.pluginsManager.closeContext(),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,this.destroyAudioLevelMonitor(),Er()&&N&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:a,deviceId:o,advanced:n}=S(S({},this.settings),t);return new Le(i,r,a,o,n)}};var te=class s extends Ee{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield q(s.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var $e=class extends ke{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=0;if(i.kind!=="video")throw new Error("Expected 'track' kind = 'video'")}setVideoHandler(t){this.videoHandler=t}hasSinks(){return this.sinkCount>0}getSinks(){return this.videoHandler.getVideoElements()||[]}attach(t){this.videoHandler.addVideoElement(t)}detach(t){this.videoHandler.removeVideoElement(t)}addSink(t){this.addSinkInternal(t,this.nativeTrack)}removeSink(t){t.srcObject!==null&&(t.srcObject=null,this.reduceSinkCount())}cleanup(){super.cleanup(),this.videoHandler.cleanup()}addSinkInternal(t,i){let r=t.srcObject;if(r!==null&&r instanceof MediaStream){let a=r.getVideoTracks()[0];if((a==null?void 0:a.id)===i.id){if(!a.muted&&a.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}t.srcObject=new MediaStream([i]),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}};var Qs=require("uuid");var St={none:-1,low:0,medium:1,high:2},Zo=.5,qs=(s,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...s].sort((o,n)=>St[o.layer]-St[n.layer]),a=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:l}=r[o],u=n[i];if(a<=u){t=l;break}else{let p=r[o+1],m=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((a-u)/(m-u)<Zo){t=l;break}}}return t};var _r=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=N&&typeof window.IntersectionObserver!="undefined";return e||d.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},js=new _r;var Nr=class{constructor(){this.TAG="[HMSResizeObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t,i={box:"border-box"})=>{var r;this.createObserver(),this.unobserve(e),(r=this.resizeObserver)==null||r.observe(e,i),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.resizeObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(ii(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=N&&typeof window.ResizeObserver!="undefined";return e||d.w(this.TAG,"Resize Observer is not supported"),e}},Js=new Nr;var We=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(d.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(d.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof _)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=(0,Qs.v4)()}updateSinks(e=!1){for(let t of this.videoElements)this.track.enabled?this.track.addSink(t,e):this.track.removeSink(t,e)}addVideoElement(e){return c(this,null,function*(){var t;this.videoElements.has(e)||(this.init(),d.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&d.w(this.TAG,`${this.track}`,`the track is added to ${this.videoElements.size} video elements, while this may be intentional, it's likely that there is a bug leading to unnecessary creation of video elements in the UI`),(t=this.intersectionObserver)!=null&&t.isSupported()?this.intersectionObserver.observe(e,this.handleIntersection):N&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof _&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),d.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){N&&(this.resizeObserver=Js,this.intersectionObserver=js)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,a=e.offsetHeight,{hidden:o}=e,{opacity:n,display:l}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+a>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&l!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof _)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:a}=i;if(r===0||a===0)continue;let o=qs(this.track.getSimulcastDefinitions(),{width:r,height:a});e?e=St[o]>St[e]?o:e:e=o}e&&(d.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var si=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(si||{}),ai=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(ai||{});var mt=class{constructor(){this.total=0;this.count=0}add(e){this.count++,this.total+=e}getAvg(){return Math.floor(this.total/this.count)}reset(){this.total=0,this.count=0}};var oi=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new mt,this.addedTimestamps={},this.processingAvgs={},this.pluginAdded={},this.pluginInputFrameRate={},this.pluginFrameRate={}}added(e,t,i){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.processingAvgs[e]=new mt,this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t}removed(e){var t;if(this.pluginAdded[e]){let i={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],avgPreProcessingTime:this.preProcessingAvgs.getAvg(),avgProcessingTime:(t=this.processingAvgs[e])==null?void 0:t.getAvg(),inputFrameRate:this.pluginInputFrameRate[e],pluginFrameRate:this.pluginFrameRate[e]};this.eventBus.analytics.publish(ge.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ge.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let a=h.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.e(this.TAG,a),this.failure(e,a),a}i&&(this.initTime[e]=i)})}preProcessWithTime(e){return c(this,null,function*(){let t=yield this.timeInMs(e);this.preProcessingAvgs.add(t)})}processWithTime(e,t){return c(this,null,function*(){var r;let i;try{i=yield this.timeInMs(t)}catch(a){let o=h.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${a.message||a}`);throw d.e(this.TAG,o),this.failure(e,o),o}i&&((r=this.processingAvgs[e])==null||r.add(i))})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.processingAvgs[e],delete this.pluginAdded[e],delete this.pluginInputFrameRate[e],delete this.pluginFrameRate[e]}};var zs=24,en=320,tn=240,gt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new oi(t),this.canvases=new Array}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e,t){return c(this,null,function*(){var i;if(this.pluginAddInProgress){let r=(i=e.getName)==null?void 0:i.call(e);if(!r||r===""){d.w("no name provided by the plugin");return}let a=h.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,a),d.w("can't add another plugin when previous add is in progress"),a}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e,t)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e,t){return c(this,null,function*(){var o,n;let i=(o=e.getName)==null?void 0:o.call(e);if(!i||i===""){d.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){d.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||zs,a=0;t&&t>0?(d.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(a=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(d.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),d.i(this.TAG,"numFrames to skip processing",a),this.pluginNumFramesToSkip[i]=a,this.pluginNumFramesSkipped[i]=a,this.validateAndThrow(i,e);try{if(yield this.analytics.initWithTime(i,()=>c(this,null,function*(){return yield e.init()})),this.pluginsMap.set(i,e),this.pluginsMap.size+1>this.canvases.length)for(let l=this.canvases.length;l<=this.pluginsMap.size;l++)this.canvases[l]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(l){throw d.e(this.TAG,"failed to add plugin",l),yield this.removePlugin(e),l}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=h.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=h.MediaPluginErrors.DeviceNotSupported("VIDEO_PLUGINS","video device not supported, see docs"),this.analytics.failure(e,r),r}}}removePlugin(e){return c(this,null,function*(){let t=e.getName();if(!this.pluginsMap.get(t)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(d.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.stopPluginsLoop()),e.stop(),this.analytics.removed(t)})}removePluginEntry(e){this.pluginsMap.delete(e),this.pluginNumFramesToSkip[e]&&delete this.pluginNumFramesToSkip[e],this.pluginNumFramesSkipped[e]&&delete this.pluginNumFramesSkipped[e]}waitForRestart(){return c(this,null,function*(){if(!(!this.pluginsLoopRunning||this.pluginsLoopState==="running"))for(;this.pluginsLoopState==="paused";)yield le(100)})}cleanup(){return c(this,null,function*(){var e;for(let t of this.pluginsMap.values())yield this.removePlugin(t);(e=this.outputTrack)==null||e.stop()})}initElementsAndStream(e){this.inputCanvas||(this.inputCanvas=document.createElement("canvas")),this.outputCanvas=document.createElement("canvas"),this.inputVideo||(this.inputVideo=document.createElement("video")),this.inputCanvas.getContext("2d"),this.outputCanvas.getContext(e||"2d");let t=this.outputCanvas.captureStream();this.outputTrack=t.getVideoTracks()[0]}startPluginsLoop(e){return c(this,null,function*(){if(!this.pluginsLoopRunning){this.initElementsAndStream(e),this.pluginsLoopRunning=!0;try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(t){throw this.pluginsLoopRunning=!1,d.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{d.d(this.TAG,"processLoop stopped")})}})}stopPluginsLoop(){return c(this,null,function*(){var e;this.pluginsLoopRunning=!1,yield this.hmsTrack.setProcessedTrack(void 0),this.resetCanvases(),(e=this.outputTrack)==null||e.stop(),this.inputVideo&&(this.inputVideo.srcObject=null,this.inputVideo=void 0)})}pluginsLoop(){return c(this,null,function*(){for(;this.pluginsLoopRunning;){let e=this.hmsTrack.getMediaTrackSettings().frameRate||zs,t=Math.floor(1e3/e);if(!this.hmsTrack.enabled||this.hmsTrack.nativeTrack.readyState==="ended"){this.pluginsLoopState==="running"&&this.resetCanvases(),this.pluginsLoopState="paused",yield le(t);continue}let i=0;try{yield this.analytics.preProcessWithTime(()=>c(this,null,function*(){return yield this.doPreProcessing()}));let r=Date.now();yield this.processFramesThroughPlugins(),i=Math.floor(Date.now()-r),i>t&&(i=t)}catch(r){d.e(this.TAG,"error in plugins loop",r)}this.pluginsLoopState="running",yield le(t-i)}})}doPreProcessing(){return c(this,null,function*(){yield this.addTrackToVideo(),yield this.updateInputCanvas()})}processFramesThroughPlugins(){return c(this,null,function*(){this.canvases[0]=this.inputCanvas;let e=0;for(let t of this.pluginsMap.values()){let i=t.getName();if(t){try{let r=this.checkIfSkipRequired(i);if(t.getPluginType()==="TRANSFORM"){let a=(o,n)=>c(this,null,function*(){try{yield t.processVideoFrame(o,n,r)}catch(l){d.e(this.TAG,`error in processing plugin ${i}`,l)}});if(r)e===this.pluginsMap.size-1?yield a(this.canvases[e],this.outputCanvas):yield a(this.canvases[e],this.canvases[e+1]);else{let o=this.canvases[e],n=this.canvases[e+1];e===this.pluginsMap.size-1?yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return a(o,this.outputCanvas)})):yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return a(o,n)}))}}else t.getPluginType()==="ANALYZE"&&!r&&(yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return yield t.processVideoFrame(this.inputCanvas)})))}catch(r){d.e(this.TAG,`error in processing plugin ${i}`,r),yield this.removePlugin(t)}e++}}})}addTrackToVideo(){return c(this,null,function*(){var t;if(!this.inputVideo)return;let e=this.inputVideo.srcObject;e!==null&&e instanceof MediaStream&&((t=e.getVideoTracks()[0])==null?void 0:t.id)===this.hmsTrack.nativeTrack.id||(this.inputVideo.pause(),this.inputVideo.srcObject=new MediaStream([this.hmsTrack.nativeTrack]),this.inputVideo.muted=!0,this.inputVideo.playsInline=!0,yield this.inputVideo.play())})}updateInputCanvas(){return c(this,null,function*(){if(!this.inputCanvas||!this.inputVideo)return;let{width:e=en,height:t=tn}=this.hmsTrack.getMediaTrackSettings();this.inputCanvas.height!==t&&(this.inputCanvas.height=t),this.inputCanvas.width!==e&&(this.inputCanvas.width=e),this.inputCanvas.getContext("2d").drawImage(this.inputVideo,0,0,e,t)})}resetCanvases(){if(!this.outputCanvas||!this.inputCanvas)return;let e=this.inputCanvas.getContext("2d");e&&(e.fillStyle="rgb(0, 0, 0)",e.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height)),this.canvases=[]}checkIfSkipRequired(e){let t=!1;return this.pluginNumFramesSkipped[e]<this.pluginNumFramesToSkip[e]?(this.pluginNumFramesSkipped[e]++,t=!0):(t=!1,this.pluginNumFramesSkipped[e]=0),t}};var ni=class{constructor(){this.plugins=new Set}addPlugins(e){e.forEach(t=>this.plugins.add(t))}removePlugins(e){e.forEach(t=>{t.stop(),this.plugins.delete(t)})}applyPlugins(e){let t=e;for(let i of this.plugins)try{t=i.apply(t)}catch(r){d.e("Could not apply plugin",r,i)}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}};var Ys=require("uuid");var rn=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],ci=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),d.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){d.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...rn,...e].reduce((t,i)=>y(S({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var Or={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default"},ue,di,Te=class s{constructor(e,t,i,r,a){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=a;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=Or){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,a=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),l=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let m={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};m.audio&&this.analyticsTimer.start("local_audio_track_time"),m.video&&this.analyticsTimer.start("local_video_track_time");try{d.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:m}),a=yield this.getLocalTracks(m,t,l)}catch(g){a=yield this.retryGetLocalTracks(g,t,m,l)}return m.audio&&this.analyticsTimer.end("local_audio_track_time"),m.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&a.push(o),n&&i&&!p&&a.push(n),a})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(M.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new Ge(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}getLocalScreen(e){return c(this,null,function*(){var m;let t=yield this.getOrDefaultScreenshareConfig(e),i=this.getScreenshareSettings(t.videoOnly),r={video:y(S({},i==null?void 0:i.video.toConstraints(!0)),{displaySurface:t.displaySurface}),preferCurrentTab:t.preferCurrentTab,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio};if(i!=null&&i.audio){let g=(m=i==null?void 0:i.audio)==null?void 0:m.toConstraints();delete g.advanced,r.audio=y(S({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}let a;try{d.d("retrieving screenshare with ",{config:t},{constraints:r}),a=yield navigator.mediaDevices.getDisplayMedia(r)}catch(g){d.w(this.TAG,"error in getting screenshare - ",g);let f=Fe(g,"screen");throw this.eventBus.analytics.publish(M.publish({error:f,devices:this.deviceManager.getDevices(),settings:new Ge(i==null?void 0:i.video,i==null?void 0:i.audio,!1)})),f}let o=[],n=new we(a),l=a.getVideoTracks()[0],u=new U(n,l,"screen",this.eventBus,i==null?void 0:i.video);u.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(u,t.forceCurrentTab);u.isCurrentTab=g,yield u.cropTo(t.cropTarget)}catch(g){throw a.getTracks().forEach(f=>f.stop()),g}o.push(u);let p=a.getAudioTracks()[0];if(p){let g=new oe(n,p,"screen",this.eventBus,i==null?void 0:i.audio);o.push(g)}return d.v(this.TAG,"getLocalScreen",o),o})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:(0,Ys.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),d.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw d.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),h.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){d.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,l,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((l=e==null?void 0:e.getSettings())==null?void 0:l.height)||240,r=1;ue||(ue=document.createElement("canvas"),ue.width=t,ue.height=i,(u=ue.getContext("2d"))==null||u.fillRect(0,0,t,i)),di||(di=setInterval(()=>{let p=ue==null?void 0:ue.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=ue.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=Pe.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(di),di=void 0,ue=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),a=this.getErrorType(i,r);throw Fe(t,a)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new ht().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof T&&e.action==="TRACK"){this.observer.onFailure(e);let a=e.code===v.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(a){let l=new ht().video(new De).audio(new Le).build();d.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,l,r)}catch(u){let p=u instanceof T?u.nativeError:u,m=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let g=h.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");g.addNativeError(p),m=g}return yield this.retryGetLocalTracks(m,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,d.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(l){return d.w(this.TAG,"Fetch empty tacks failed",l),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(l),yield this.getLocalTracks(i,t,r)}}else return d.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"unknown(video or audio)"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(s.getEmptyAudioTrack()),e.video==="empty"&&t.push(s.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),a=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield a==null?void 0:a.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,a=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new ae().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(a||Or.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,a=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new ee().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(a||Or.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new ee().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new ae().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),a=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new we(new MediaStream(e));let o=[];if(a&&(t!=null&&t.audio)){let n=new oe(i,a,"regular",this.eventBus,t.audio);o.push(n)}if(r&&(t!=null&&t.video)){let n=new U(i,r,"regular",this.eventBus,t.video);n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function Xs(s,e){return function(i){return i in s&&s[i]!==e[i]}}var U=class s extends $e{constructor(t,i,r,a,o=new ee().build()){super(t,i,r);this.eventBus=a;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){d.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:a,maxFramerate:o,maxBitrate:n,deviceId:l,advanced:u,facingMode:p}=S(S({},this.settings),t);return new De(i,r,a,o,l,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Xs(t,this.settings);if(r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("width")||r("height")||r("advanced"))if(this.source==="video"){let a=yield this.replaceTrackWith(t);yield this.replaceSender(a,this.enabled),this.nativeTrack=a,this.videoHandler.updateSinks()}else yield this.nativeTrack.applyConstraints(t.toConstraints())});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(Xs(t,this.settings)("deviceId")&&this.source==="regular"){if(this.enabled){delete t.facingMode;let a=yield this.replaceTrackWith(t);yield this.replaceSender(a,this.enabled),this.nativeTrack=a,this.videoHandler.updateSinks()}i||Q.updateSelection("videoInput",{deviceId:t.deviceId,groupId:this.nativeTrack.getSettings().groupId})}});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});t.tracks.push(this),this.setVideoHandler(new We(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new gt(this,a),this.mediaStreamPluginsManager=new ni,this.setFirstTrackId(this.trackId)}setSimulcastDefinitons(t){this._layerDefinitions=t}getSimulcastDefinitions(){return this._layerDefinitions}setEnabled(t){return c(this,null,function*(){var i;if(t!==this.enabled){if(this.source==="regular"){let r;t?r=yield this.replaceTrackWith(this.settings):r=yield this.replaceTrackWithBlank(),yield this.replaceSender(r,t),(i=this.nativeTrack)==null||i.stop(),this.nativeTrack=r,yield q(s.prototype,this,"setEnabled").call(this,t),t&&(yield this.pluginsManager.waitForRestart(),yield this.processPlugins(),this.settings=this.buildNewSettings({deviceId:r.getSettings().deviceId})),this.videoHandler.updateSinks()}this.eventBus.localVideoEnabled.publish({enabled:t,track:this})}})}processPlugins(){return c(this,null,function*(){try{if(this.pluginsManager.getPlugins().length>0)return;if(this.mediaStreamPluginsManager.getPlugins().length>0){let r=this.mediaStreamPluginsManager.applyPlugins(new MediaStream([this.nativeTrack])).getVideoTracks()[0];yield this.setProcessedTrack(r)}else yield this.setProcessedTrack()}catch(t){console.error("error in processing plugin(s)",t)}})}addStreamPlugins(t){return c(this,null,function*(){if(this.pluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSMediaStreamPlugin and HMSVideoPlugin cannot be used together");this.mediaStreamPluginsManager.addPlugins(t),yield this.processPlugins()})}removeStreamPlugins(t){return c(this,null,function*(){this.mediaStreamPluginsManager.removePlugins(t),yield this.processPlugins()})}isPublishedTrackId(t){return this.publishedTrackId===t}addSink(t){this.addSinkInternal(t,this.processedTrack||this.nativeTrack)}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(yield this.handleDeviceChange(r,i),!this.enabled||de(this.nativeTrack)){this.settings=r;return}yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;q(s.prototype,this,"cleanup").call(this),this.transceiver=void 0,yield this.pluginsManager.cleanup(),(t=this.processedTrack)==null||t.stop(),this.isPublished=!1})}cropTo(t){return c(this,null,function*(){if(t&&this.source==="screen")try{this.nativeTrack.cropTo&&(yield this.nativeTrack.cropTo(t))}catch(i){throw d.e(this.TAG,"failed to crop screenshare capture - ",i),h.TracksErrors.GenericTrack("TRACK","failed to crop screenshare capture")}})}getCaptureHandle(){if(this.nativeTrack.getCaptureHandle)return this.nativeTrack.getCaptureHandle()}setProcessedTrack(t){return c(this,null,function*(){if(!this.nativeTrack.enabled){this.processedTrack=t;return}yield this.removeOrReplaceProcessedTrack(t),this.videoHandler.updateSinks()})}getTrackIDBeingSent(){return this.getTrackBeingSent().id}getTrackBeingSent(){return this.enabled?this.processedTrack||this.nativeTrack:this.nativeTrack}switchCamera(){return c(this,null,function*(){var a;let t=this.getMediaTrackSettings().facingMode;if(!t||this.source!=="regular"){d.d(this.TAG,"facingMode not supported");return}let i=t==="environment"?"user":"environment";(a=this.nativeTrack)==null||a.stop();let r=yield this.replaceTrackWith(this.buildNewSettings({facingMode:i,deviceId:void 0}));yield this.replaceSender(r,this.enabled),this.nativeTrack=r,this.videoHandler.updateSinks(),this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId,facingMode:i}),Q.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();try{let r=yield $s(t);return d.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){throw this.isPublished&&this.eventBus.analytics.publish(M.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Te.getEmptyVideoTrack(t);return t==null||t.stop(),d.d(this.TAG,"replaceTrackWithBlank, Previous track stopped",t,"newTrack",i),i})}replaceSender(t,i){return c(this,null,function*(){i?yield this.replaceSenderTrack(this.processedTrack||t):yield this.replaceSenderTrack(t),this.stream.replaceStreamTrack(this.nativeTrack,t)})}};var Ke="renegotiation-callback-id",li="ion-sfu";var qe="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var Zs="https://event.100ms.live/v2/client/report",ea="https://event-nonprod.100ms.live/v2/client/report";var V={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",STATS_UPDATE:"stats-update",RTC_STATS_UPDATE:"rtc-stats-update",TRACK_DEGRADED:"track-degraded",TRACK_RESTORED:"track-restored",TRACK_AUDIO_LEVEL_UPDATE:"track-audio-level-update",LOCAL_AUDIO_SILENCE:"local-audio-silence",ANALYTICS:"analytics",AUDIO_PLUGIN_FAILED:"audio-plugin-failed",POLICY_CHANGE:"policy-change",LOCAL_ROLE_UPDATE:"local-role-update",AUDIO_TRACK_UPDATE:"audio-track-update",AUDIO_TRACK_ADDED:"audio-track-added",AUDIO_TRACK_REMOVED:"audio-track-removed",AUTOPLAY_ERROR:"autoplay-error",LEAVE:"leave"},ta="2.5",ia="20231201",fe="_handraise",Ur=1e3,Vr=64;var _=class s extends $e{constructor(t,i,r){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new Br;this.preferredLayer="high";this.setVideoHandler(new We(this))}setTrackId(t){this.bizTrackId=t}get trackId(){return this.bizTrackId||super.trackId}get degraded(){return this._degraded}get degradedAt(){return this._degradedAt}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(q(s.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){d.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){d.d(`[Remote Track] ${this.logIdentifier}
38
+ })()`;function X(s){if(s<0)throw Error("`ms` should be a positive integer");return new Promise(e=>{setTimeout(e,s)})}function ue(s){if(s<0)throw Error("`ms` should be a positive integer");if(typeof Worker=="undefined")return X(s);let e=new Worker(URL.createObjectURL(new Blob([Zo],{type:"application/javascript"})));return e.postMessage(["start",s]),new Promise(t=>{e.onmessage=i=>{i.data==="tick"&&(t(),e.terminate())}})}function ii(s,e=300){let t;return function(...i){clearTimeout(t),t=void 0;let r=this;t=setTimeout(()=>{s.apply(r,i)},e)}}var en=35,tn=5,ri=class{constructor(e,t,i){this.track=e;this.audioLevelEvent=t;this.silenceEvent=i;this.TAG="[TrackAudioLevelMonitor]";this.audioLevel=0;this.isMonitored=!1;this.interval=100;this.historyInterval=700;this.history=new Ae(this.historyInterval/this.interval);this.detectSilence=()=>c(this,null,function*(){let i=0;for(;this.isMonitored;){if(this.track.enabled)if(this.isSilentThisInstant()){if(i++,i>50){this.silenceEvent.publish({track:this.track});break}}else break;yield X(20)}});try{let r=new MediaStream([this.track.nativeTrack]);this.analyserNode=this.createAnalyserNodeForStream(r)}catch(r){d.w(this.TAG,"Unable to initialize AudioContext",r)}}start(){this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting track Monitor",`${this.track}`),this.loop().then(()=>d.d(this.TAG,"Stopping track Monitor",`${this.track}`))}stop(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}this.sendAudioLevel(0),this.isMonitored=!1}loop(){return c(this,null,function*(){for(;this.isMonitored;)this.sendAudioLevel(this.getMaxAudioLevelOverPeriod()),yield X(this.interval)})}sendAudioLevel(e=0){if(e=e>en?e:0,Math.abs(this.audioLevel-e)>tn){this.audioLevel=e;let i={track:this.track,audioLevel:this.audioLevel};this.audioLevelEvent.publish(i)}}getMaxAudioLevelOverPeriod(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=this.calculateAudioLevel();return e!==void 0&&this.history.enqueue(e),this.history.aggregate(t=>Math.max(...t))}calculateAudioLevel(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(e);let t=.009,i=t;for(let o of e)i=Math.max(i,(o-128)/128);let r=(Math.log(t)-Math.log(i))/Math.log(t);return Math.ceil(Math.min(Math.max(r*100,0),100))}isSilentThisInstant(){if(!this.analyserNode){d.d(this.TAG,"AudioContext not initialized");return}let e=new Uint8Array(this.analyserNode.fftSize);return this.analyserNode.getByteTimeDomainData(e),!e.some(t=>t!==128&&t!==0)}createAnalyserNodeForStream(e){let t=Pe.getAudioContext(),i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i}};var Dr=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Dr||{});var be={f:"high",h:"medium",q:"low"};var wr=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(wr||{});var ae=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._advanced=[{googEchoCancellation:{exact:!0}},{googExperimentalEchoCancellation:{exact:!0}},{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{googHighpassFilter:{exact:!0}},{googAudioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}build(){return new Le(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced)}},Le=class{constructor(e,t,i,r,a){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=a}toConstraints(){return{deviceId:this.deviceId,advanced:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var ee=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new De(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},De=class{constructor(e,t,i,r,a,o,n,l){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=a,this.advanced=o,this.facingMode=l}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId,facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Yt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var ht=class{constructor(){this._video=new ee().build();this._audio=new ae().build();this._screen=new ee().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw h.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw h.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new Ge(this._video,this._audio,this._simulcast,this._screen||void 0)}},Ge=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=S(S({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=S(S({},this.video.toAnalyticsProperties()),e)),e}};function Js(s,e){return function(i){return i in s&&s[i]!==e[i]}}var oe=class s extends Ee{constructor(t,i,r,a,o=new ae().build()){super(t,i,r);this.eventBus=a;this.TAG="[HMSLocalAudioTrack]";this.isPublished=!1;this.handleVisibilityChange=()=>c(this,null,function*(){document.visibilityState==="visible"&&(yield this.replaceTrackWith(this.settings))});this.replaceSenderTrack=()=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){d.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(this.processedTrack||this.nativeTrack)});this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=Js(t,this.settings);r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("advanced")&&(yield this.replaceTrackWith(t))});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){Js(t,this.settings)("deviceId")&&(this.manuallySelectedDeviceId=i?this.manuallySelectedDeviceId:t.deviceId,yield this.replaceTrackWith(t),i||Q.updateSelection("audioInput",{deviceId:t.deviceId,groupId:this.nativeTrack.getSettings().groupId}))});t.tracks.push(this),this.settings=o,o.deviceId!==i.getSettings().deviceId&&!le(i)&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new pt(this,a),this.setFirstTrackId(i.id),Er()&&N&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}getManuallySelectedDeviceId(){return this.manuallySelectedDeviceId}resetManuallySelectedDeviceId(){this.manuallySelectedDeviceId=void 0}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();let r=!!this.audioLevelMonitor;try{let a=yield Ks(t);a.enabled=this.enabled,d.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",a),yield this.stream.replaceStreamTrack(i,a),this.nativeTrack=a,yield this.replaceSenderTrack(),r&&this.initAudioLevelMonitor()}catch(a){throw this.isPublished&&this.eventBus.analytics.publish(M.publish({error:a})),a}try{yield this.pluginsManager.reprocessPlugins()}catch(a){this.eventBus.audioPluginFailed.publish(a)}})}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(t&&le(this.nativeTrack)&&(yield this.replaceTrackWith(this.settings)),yield q(s.prototype,this,"setEnabled").call(this,t),t&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),this.eventBus.localAudioEnabled.publish({enabled:t,track:this}))})}isPublishedTrackId(t){return this.publishedTrackId===t}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(le(this.nativeTrack)){this.settings=r;return}yield this.handleDeviceChange(r,i),yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.pluginsManager.getPlugins()}addPlugin(t){return c(this,null,function*(){return this.pluginsManager.addPlugin(t)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}setProcessedTrack(t){return c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack()})}initAudioLevelMonitor(){this.audioLevelMonitor&&this.destroyAudioLevelMonitor(),d.d(this.TAG,"Monitor Audio Level for",this,this.getMediaTrackSettings().deviceId),this.audioLevelMonitor=new ri(this,this.eventBus.trackAudioLevelUpdate,this.eventBus.localAudioSilence),this.audioLevelMonitor.start(),this.audioLevelMonitor.detectSilence()}destroyAudioLevelMonitor(){var t;(t=this.audioLevelMonitor)==null||t.stop(),this.audioLevelMonitor=void 0}cleanup(){return c(this,null,function*(){var t;q(s.prototype,this,"cleanup").call(this),yield this.pluginsManager.cleanup(),yield this.pluginsManager.closeContext(),this.transceiver=void 0,(t=this.processedTrack)==null||t.stop(),this.isPublished=!1,this.destroyAudioLevelMonitor(),Er()&&N&&document.removeEventListener("visibilitychange",this.handleVisibilityChange)})}getTrackIDBeingSent(){return this.processedTrack?this.processedTrack.id:this.nativeTrack.id}getTrackBeingSent(){return this.processedTrack||this.nativeTrack}buildNewSettings(t){let{volume:i,codec:r,maxBitrate:a,deviceId:o,advanced:n}=S(S({},this.settings),t);return new Le(i,r,a,o,n)}};var te=class s extends Ee{setEnabled(e){return c(this,null,function*(){e!==this.enabled&&(yield q(s.prototype,this,"setEnabled").call(this,e),yield this.subscribeToAudio(e))})}};var $e=class extends ke{constructor(t,i,r){super(t,i,r);this.type="video";this.sinkCount=0;if(i.kind!=="video")throw new Error("Expected 'track' kind = 'video'")}setVideoHandler(t){this.videoHandler=t}hasSinks(){return this.sinkCount>0}getSinks(){return this.videoHandler.getVideoElements()||[]}attach(t){this.videoHandler.addVideoElement(t)}detach(t){this.videoHandler.removeVideoElement(t)}addSink(t){this.addSinkInternal(t,this.nativeTrack)}removeSink(t){t.srcObject!==null&&(t.srcObject=null,this.reduceSinkCount())}cleanup(){super.cleanup(),this.videoHandler.cleanup()}addSinkInternal(t,i){let r=t.srcObject;if(r!==null&&r instanceof MediaStream){let a=r.getVideoTracks()[0];if((a==null?void 0:a.id)===i.id){if(!a.muted&&a.readyState==="live")return;this.reduceSinkCount()}else this.reduceSinkCount()}t.srcObject=new MediaStream([i]),this.sinkCount++}reduceSinkCount(){this.sinkCount>0&&this.sinkCount--}};var Xs=require("uuid");var St={none:-1,low:0,medium:1,high:2},rn=.5,Qs=(s,e)=>{let t="high",i=e.width>e.height?"width":"height",r=[...s].sort((o,n)=>St[o.layer]-St[n.layer]),a=e[i]*((window==null?void 0:window.devicePixelRatio)||1);for(let o=0;o<r.length;o++){let{resolution:n,layer:l}=r[o],u=n[i];if(a<=u){t=l;break}else{let p=r[o+1],m=p?p.resolution[i]:Number.POSITIVE_INFINITY;if((a-u)/(m-u)<rn){t=l;break}}}return t};var _r=class{constructor(){this.TAG="[HMSIntersectionObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t)=>{var i;this.createObserver(),this.unobserve(e),(i=this.intersectionObserver)==null||i.observe(e),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.intersectionObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.intersectionObserver&&(this.intersectionObserver=new IntersectionObserver(this.handleIntersection))};this.handleIntersection=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=N&&typeof window.IntersectionObserver!="undefined";return e||d.w(this.TAG,"IntersectionObserver is not supported, fallback will be used instead"),e}},zs=new _r;var Nr=class{constructor(){this.TAG="[HMSResizeObserverWrapper]";this.listeners=new WeakMap;this.observe=(e,t,i={box:"border-box"})=>{var r;this.createObserver(),this.unobserve(e),(r=this.resizeObserver)==null||r.observe(e,i),this.listeners.set(e,t)};this.unobserve=e=>{var t;(t=this.resizeObserver)==null||t.unobserve(e),this.listeners.delete(e)};this.createObserver=()=>{this.isSupported()&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(ii(this.handleResize,300)))};this.handleResize=e=>{var t;for(let i of e)(t=this.listeners.get(i.target))==null||t(i)};this.createObserver()}isSupported(){let e=N&&typeof window.ResizeObserver!="undefined";return e||d.w(this.TAG,"Resize Observer is not supported"),e}},Ys=new Nr;var We=class{constructor(e){this.track=e;this.TAG="[VideoElementManager]";this.videoElements=new Set;this.entries=new WeakMap;this.handleIntersection=e=>c(this,null,function*(){let t=getComputedStyle(e.target).visibility==="visible";this.track.enabled&&(e.isIntersecting&&t||!document.contains(e.target))?(d.d(this.TAG,"add sink intersection",`${this.track}`,this.id),this.entries.set(e.target,e.boundingClientRect),yield this.selectMaxLayer(),yield this.track.addSink(e.target)):(d.d(this.TAG,"remove sink intersection",`${this.track}`,this.id),yield this.track.removeSink(e.target))});this.handleResize=e=>c(this,null,function*(){!this.track.enabled||!(this.track instanceof _)||(this.entries.set(e.target,e.contentRect),yield this.selectMaxLayer())});this.cleanup=()=>{this.videoElements.forEach(e=>{var t,i;e.srcObject=null,(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e)}),this.videoElements.clear(),this.resizeObserver=void 0,this.intersectionObserver=void 0};this.init(),this.id=(0,Xs.v4)()}updateSinks(e=!1){for(let t of this.videoElements)this.track.enabled?this.track.addSink(t,e):this.track.removeSink(t,e)}addVideoElement(e){return c(this,null,function*(){var t;this.videoElements.has(e)||(this.init(),d.d(this.TAG,`Adding video element for ${this.track}`,this.id),this.videoElements.add(e),this.videoElements.size>=10&&d.w(this.TAG,`${this.track}`,`the track is added to ${this.videoElements.size} video elements, while this may be intentional, it's likely that there is a bug leading to unnecessary creation of video elements in the UI`),(t=this.intersectionObserver)!=null&&t.isSupported()?this.intersectionObserver.observe(e,this.handleIntersection):N&&(this.isElementInViewport(e)?this.track.addSink(e):this.track.removeSink(e)),this.resizeObserver?this.resizeObserver.observe(e,this.handleResize):this.track instanceof _&&(yield this.track.setPreferredLayer(this.track.getPreferredLayer())))})}removeVideoElement(e){var t,i;this.track.removeSink(e),this.videoElements.delete(e),this.entries.delete(e),(t=this.resizeObserver)==null||t.unobserve(e),(i=this.intersectionObserver)==null||i.unobserve(e),d.d(this.TAG,`Removing video element for ${this.track}`)}getVideoElements(){return Array.from(this.videoElements)}init(){N&&(this.resizeObserver=Ys,this.intersectionObserver=zs)}isElementInViewport(e){let t=e.offsetTop,i=e.offsetLeft,r=e.offsetWidth,a=e.offsetHeight,{hidden:o}=e,{opacity:n,display:l}=getComputedStyle(e);for(;e.offsetParent;)e=e.offsetParent,t+=e.offsetTop,i+=e.offsetLeft;return t<window.pageYOffset+window.innerHeight&&i<window.pageXOffset+window.innerWidth&&t+a>window.pageYOffset&&i+r>window.pageXOffset&&!o&&(n!==""?parseFloat(n)>0:!0)&&l!=="none"}selectMaxLayer(){return c(this,null,function*(){if(!(this.track instanceof _)||this.videoElements.size===0)return;let e;for(let t of this.videoElements){let i=this.entries.get(t);if(!i)continue;let{width:r,height:a}=i;if(r===0||a===0)continue;let o=Qs(this.track.getSimulcastDefinitions(),{width:r,height:a});e?e=St[o]>St[e]?o:e:e=o}e&&(d.d(this.TAG,`selecting max layer ${e} for the track`,`${this.track}`),yield this.track.setPreferredLayer(e))})}};var si=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(si||{}),ai=(t=>(t["2D"]="2d",t.WEBGL="webgl",t.WEBGL2="webgl2",t))(ai||{});var mt=class{constructor(){this.total=0;this.count=0}add(e){this.count++,this.total+=e}getAvg(){return Math.floor(this.total/this.count)}reset(){this.total=0,this.count=0}};var oi=class{constructor(e){this.eventBus=e;this.TAG="[VideoPluginsAnalytics]";this.initTime={},this.preProcessingAvgs=new mt,this.addedTimestamps={},this.processingAvgs={},this.pluginAdded={},this.pluginInputFrameRate={},this.pluginFrameRate={}}added(e,t,i){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.processingAvgs[e]=new mt,this.pluginInputFrameRate[e]=t,this.pluginFrameRate[e]=i||t}removed(e){var t;if(this.pluginAdded[e]){let i={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],avgPreProcessingTime:this.preProcessingAvgs.getAvg(),avgProcessingTime:(t=this.processingAvgs[e])==null?void 0:t.getAvg(),inputFrameRate:this.pluginInputFrameRate[e],pluginFrameRate:this.pluginFrameRate[e]};this.eventBus.analytics.publish(ge.stats(i)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ge.failure(e,t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){d.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),d.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let a=h.MediaPluginErrors.InitFailed("VIDEO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw d.e(this.TAG,a),this.failure(e,a),a}i&&(this.initTime[e]=i)})}preProcessWithTime(e){return c(this,null,function*(){let t=yield this.timeInMs(e);this.preProcessingAvgs.add(t)})}processWithTime(e,t){return c(this,null,function*(){var r;let i;try{i=yield this.timeInMs(t)}catch(a){let o=h.MediaPluginErrors.ProcessingFailed("VIDEO_PLUGINS",`Failed during processing of plugin${a.message||a}`);throw d.e(this.TAG,o),this.failure(e,o),o}i&&((r=this.processingAvgs[e])==null||r.add(i))})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.processingAvgs[e],delete this.pluginAdded[e],delete this.pluginInputFrameRate[e],delete this.pluginFrameRate[e]}};var Zs=24,sn=320,an=240,gt=class{constructor(e,t){this.TAG="[VideoPluginsManager]";this.pluginsLoopRunning=!1;this.pluginsLoopState="paused";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.pluginNumFramesToSkip={},this.pluginNumFramesSkipped={},this.analytics=new oi(t),this.canvases=new Array}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e,t){return c(this,null,function*(){var i;if(this.pluginAddInProgress){let r=(i=e.getName)==null?void 0:i.call(e);if(!r||r===""){d.w("no name provided by the plugin");return}let a=h.MediaPluginErrors.AddAlreadyInProgress("VIDEO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.failure(r,a),d.w("can't add another plugin when previous add is in progress"),a}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e,t)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e,t){return c(this,null,function*(){var o,n;let i=(o=e.getName)==null?void 0:o.call(e);if(!i||i===""){d.w("no name provided by the plugin");return}if(this.pluginsMap.has(i)){d.w(this.TAG,`plugin - ${e.getName()} already added.`);return}let r=this.hmsTrack.getMediaTrackSettings().frameRate||Zs,a=0;t&&t>0?(d.i(this.TAG,`adding plugin ${e.getName()} with framerate ${t}`),t<r&&(a=Math.ceil(r/t)-1),this.analytics.added(i,r,t)):(d.i(this.TAG,`adding plugin ${e.getName()}`),this.analytics.added(i,r)),d.i(this.TAG,"numFrames to skip processing",a),this.pluginNumFramesToSkip[i]=a,this.pluginNumFramesSkipped[i]=a,this.validateAndThrow(i,e);try{if(yield this.analytics.initWithTime(i,()=>c(this,null,function*(){return yield e.init()})),this.pluginsMap.set(i,e),this.pluginsMap.size+1>this.canvases.length)for(let l=this.canvases.length;l<=this.pluginsMap.size;l++)this.canvases[l]=document.createElement("canvas");yield this.startPluginsLoop((n=e.getContextType)==null?void 0:n.call(e))}catch(l){throw d.e(this.TAG,"failed to add plugin",l),yield this.removePlugin(e),l}})}validatePlugin(e){return e.checkSupport()}validateAndThrow(e,t){let i=this.validatePlugin(t);if(i.isSupported)d.i(this.TAG,`plugin is supported,- ${t.getName()}`);else{let r;switch(i.errType){case"PLATFORM_NOT_SUPPORTED":throw r=h.MediaPluginErrors.PlatformNotSupported("VIDEO_PLUGINS","platform not supported, see docs"),this.analytics.failure(e,r),r;case"DEVICE_NOT_SUPPORTED":throw r=h.MediaPluginErrors.DeviceNotSupported("VIDEO_PLUGINS","video device not supported, see docs"),this.analytics.failure(e,r),r}}}removePlugin(e){return c(this,null,function*(){let t=e.getName();if(!this.pluginsMap.get(t)){d.w(this.TAG,`plugin - ${t} not found to remove.`);return}d.i(this.TAG,`removing plugin ${t}`),this.removePluginEntry(t),this.pluginsMap.size===0&&(d.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.stopPluginsLoop()),e.stop(),this.analytics.removed(t)})}removePluginEntry(e){this.pluginsMap.delete(e),this.pluginNumFramesToSkip[e]&&delete this.pluginNumFramesToSkip[e],this.pluginNumFramesSkipped[e]&&delete this.pluginNumFramesSkipped[e]}waitForRestart(){return c(this,null,function*(){if(!(!this.pluginsLoopRunning||this.pluginsLoopState==="running"))for(;this.pluginsLoopState==="paused";)yield ue(100)})}cleanup(){return c(this,null,function*(){var e;for(let t of this.pluginsMap.values())yield this.removePlugin(t);(e=this.outputTrack)==null||e.stop()})}initElementsAndStream(e){this.inputCanvas||(this.inputCanvas=document.createElement("canvas")),this.outputCanvas=document.createElement("canvas"),this.inputVideo||(this.inputVideo=document.createElement("video")),this.inputCanvas.getContext("2d"),this.outputCanvas.getContext(e||"2d");let t=this.outputCanvas.captureStream();this.outputTrack=t.getVideoTracks()[0]}startPluginsLoop(e){return c(this,null,function*(){if(!this.pluginsLoopRunning){this.initElementsAndStream(e),this.pluginsLoopRunning=!0;try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(t){throw this.pluginsLoopRunning=!1,d.e(this.TAG,"error in setting processed track",t),t}this.pluginsLoop().then(()=>{d.d(this.TAG,"processLoop stopped")})}})}stopPluginsLoop(){return c(this,null,function*(){var e;this.pluginsLoopRunning=!1,yield this.hmsTrack.setProcessedTrack(void 0),this.resetCanvases(),(e=this.outputTrack)==null||e.stop(),this.inputVideo&&(this.inputVideo.srcObject=null,this.inputVideo=void 0)})}pluginsLoop(){return c(this,null,function*(){for(;this.pluginsLoopRunning;){let e=this.hmsTrack.getMediaTrackSettings().frameRate||Zs,t=Math.floor(1e3/e);if(!this.hmsTrack.enabled||this.hmsTrack.nativeTrack.readyState==="ended"){this.pluginsLoopState==="running"&&this.resetCanvases(),this.pluginsLoopState="paused",yield ue(t);continue}let i=0;try{yield this.analytics.preProcessWithTime(()=>c(this,null,function*(){return yield this.doPreProcessing()}));let r=Date.now();yield this.processFramesThroughPlugins(),i=Math.floor(Date.now()-r),i>t&&(i=t)}catch(r){d.e(this.TAG,"error in plugins loop",r)}this.pluginsLoopState="running",yield ue(t-i)}})}doPreProcessing(){return c(this,null,function*(){yield this.addTrackToVideo(),yield this.updateInputCanvas()})}processFramesThroughPlugins(){return c(this,null,function*(){this.canvases[0]=this.inputCanvas;let e=0;for(let t of this.pluginsMap.values()){let i=t.getName();if(t){try{let r=this.checkIfSkipRequired(i);if(t.getPluginType()==="TRANSFORM"){let a=(o,n)=>c(this,null,function*(){try{yield t.processVideoFrame(o,n,r)}catch(l){d.e(this.TAG,`error in processing plugin ${i}`,l)}});if(r)e===this.pluginsMap.size-1?yield a(this.canvases[e],this.outputCanvas):yield a(this.canvases[e],this.canvases[e+1]);else{let o=this.canvases[e],n=this.canvases[e+1];e===this.pluginsMap.size-1?yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return a(o,this.outputCanvas)})):yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return a(o,n)}))}}else t.getPluginType()==="ANALYZE"&&!r&&(yield this.analytics.processWithTime(i,()=>c(this,null,function*(){return yield t.processVideoFrame(this.inputCanvas)})))}catch(r){d.e(this.TAG,`error in processing plugin ${i}`,r),yield this.removePlugin(t)}e++}}})}addTrackToVideo(){return c(this,null,function*(){var t;if(!this.inputVideo)return;let e=this.inputVideo.srcObject;e!==null&&e instanceof MediaStream&&((t=e.getVideoTracks()[0])==null?void 0:t.id)===this.hmsTrack.nativeTrack.id||(this.inputVideo.pause(),this.inputVideo.srcObject=new MediaStream([this.hmsTrack.nativeTrack]),this.inputVideo.muted=!0,this.inputVideo.playsInline=!0,yield this.inputVideo.play())})}updateInputCanvas(){return c(this,null,function*(){if(!this.inputCanvas||!this.inputVideo)return;let{width:e=sn,height:t=an}=this.hmsTrack.getMediaTrackSettings();this.inputCanvas.height!==t&&(this.inputCanvas.height=t),this.inputCanvas.width!==e&&(this.inputCanvas.width=e),this.inputCanvas.getContext("2d").drawImage(this.inputVideo,0,0,e,t)})}resetCanvases(){if(!this.outputCanvas||!this.inputCanvas)return;let e=this.inputCanvas.getContext("2d");e&&(e.fillStyle="rgb(0, 0, 0)",e.fillRect(0,0,this.outputCanvas.width,this.outputCanvas.height)),this.canvases=[]}checkIfSkipRequired(e){let t=!1;return this.pluginNumFramesSkipped[e]<this.pluginNumFramesToSkip[e]?(this.pluginNumFramesSkipped[e]++,t=!0):(t=!1,this.pluginNumFramesSkipped[e]=0),t}};var ni=class{constructor(){this.plugins=new Set}addPlugins(e){e.forEach(t=>this.plugins.add(t))}removePlugins(e){e.forEach(t=>{t.stop(),this.plugins.delete(t)})}applyPlugins(e){let t=e;for(let i of this.plugins)try{t=i.apply(t)}catch(r){d.e("Could not apply plugin",r,i)}return t}getPlugins(){return Array.from(this.plugins).map(e=>e.getName())}};var ea=require("uuid");var on=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],ci=class{constructor(){this.eventPerformanceMeasures={}}start(e){performance.mark(e)}end(e){var t;try{this.eventPerformanceMeasures[e]=performance.measure(e,e),d.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration)}catch(i){d.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...on,...e].reduce((t,i)=>y(S({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};var Or={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default"},pe,di,Te=class s{constructor(e,t,i,r,a){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=a;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=Or){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,a=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),l=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let m={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};m.audio&&this.analyticsTimer.start("local_audio_track_time"),m.video&&this.analyticsTimer.start("local_video_track_time");try{d.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:m}),a=yield this.getLocalTracks(m,t,l)}catch(g){a=yield this.retryGetLocalTracks(g,t,m,l)}return m.audio&&this.analyticsTimer.end("local_audio_track_time"),m.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&a.push(o),n&&i&&!p&&a.push(n),a})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(M.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new Ge(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}getLocalScreen(e){return c(this,null,function*(){var m;let t=yield this.getOrDefaultScreenshareConfig(e),i=this.getScreenshareSettings(t.videoOnly),r={video:y(S({},i==null?void 0:i.video.toConstraints(!0)),{displaySurface:t.displaySurface}),preferCurrentTab:t.preferCurrentTab,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio};if(i!=null&&i.audio){let g=(m=i==null?void 0:i.audio)==null?void 0:m.toConstraints();delete g.advanced,r.audio=y(S({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}let a;try{d.d("retrieving screenshare with ",{config:t},{constraints:r}),a=yield navigator.mediaDevices.getDisplayMedia(r)}catch(g){d.w(this.TAG,"error in getting screenshare - ",g);let f=Fe(g,"screen");throw this.eventBus.analytics.publish(M.publish({error:f,devices:this.deviceManager.getDevices(),settings:new Ge(i==null?void 0:i.video,i==null?void 0:i.audio,!1)})),f}let o=[],n=new we(a),l=a.getVideoTracks()[0],u=new U(n,l,"screen",this.eventBus,i==null?void 0:i.video);u.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(u,t.forceCurrentTab);u.isCurrentTab=g,yield u.cropTo(t.cropTarget)}catch(g){throw a.getTracks().forEach(f=>f.stop()),g}o.push(u);let p=a.getAudioTracks()[0];if(p){let g=new oe(n,p,"screen",this.eventBus,i==null?void 0:i.audio);o.push(g)}return d.v(this.TAG,"getLocalScreen",o),o})}setScreenCaptureHandleConfig(e){var t;!((t=navigator.mediaDevices)!=null&&t.setCaptureHandleConfig)||this.isInIframe()||(e=e||{},Object.assign(e,{handle:(0,ea.v4)(),exposeOrigin:!1,permittedOrigins:[window.location.origin]}),d.d("setting capture handle - ",e.handle),navigator.mediaDevices.setCaptureHandleConfig(e),this.captureHandleIdentifier=e.handle)}validateCurrentTabCapture(e,t){let i=e.getCaptureHandle(),r=!!(this.captureHandleIdentifier&&(i==null?void 0:i.handle)===this.captureHandleIdentifier);if(t&&!r)throw d.e(this.TAG,"current tab was not shared with forceCurrentTab as true"),h.TracksErrors.CurrentTabNotShared();return r}requestPermissions(){return c(this,null,function*(){try{(yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})).getTracks().forEach(t=>t.stop())}catch(e){d.e(this.TAG,e)}})}static getEmptyVideoTrack(e){var n,l,u;let t=((n=e==null?void 0:e.getSettings())==null?void 0:n.width)||320,i=((l=e==null?void 0:e.getSettings())==null?void 0:l.height)||240,r=1;pe||(pe=document.createElement("canvas"),pe.width=t,pe.height=i,(u=pe.getContext("2d"))==null||u.fillRect(0,0,t,i)),di||(di=setInterval(()=>{let p=pe==null?void 0:pe.getContext("2d");p&&p.fillRect(0,0,1,1)},1e3/r));let o=pe.captureStream(r).getVideoTracks()[0];return o.enabled=!1,o}static getEmptyAudioTrack(){let e=Pe.getAudioContext(),t=e.createOscillator(),i=e.createMediaStreamDestination();t.connect(i),t.start();let r=i.stream.getAudioTracks()[0];return r.enabled=!1,r}static cleanup(){clearInterval(di),di=void 0,pe=void 0}getAVTracks(e){return c(this,null,function*(){try{let t=yield navigator.mediaDevices.getUserMedia({audio:e.audio?e.audio.toConstraints():!1,video:e.video?e.video.toConstraints():!1});return t.getVideoTracks().concat(t.getAudioTracks())}catch(t){yield this.deviceManager.init();let i=!!(!this.deviceManager.hasWebcamPermission&&e.video),r=!!(!this.deviceManager.hasMicrophonePermission&&e.audio),a=this.getErrorType(i,r);throw Fe(t,a)}})}getAVTrackSettings(e){let t=this.getAudioSettings(e),i=this.getVideoSettings(e);return!t&&!i?null:new ht().video(i).audio(t).build()}isInIframe(){try{return window.self!==window.top}catch(e){return!0}}retryGetLocalTracks(e,t,i,r){return c(this,null,function*(){if(e instanceof T&&e.action==="TRACK"){this.observer.onFailure(e);let a=e.code===v.TracksErrors.OVER_CONSTRAINED,o=e.message.includes("audio"),n=e.message.includes("video");if(a){let l=new ht().video(new De).audio(new Le).build();d.w(this.TAG,"Fetch AV Tracks failed with overconstrained error",{fetchTrackOptions:i},{error:e});try{return yield this.getLocalTracks(i,l,r)}catch(u){let p=u instanceof T?u.nativeError:u,m=u;if((p==null?void 0:p.name)==="OverconstrainedError"){let g=h.TracksErrors.GenericTrack("TRACK","Overconstrained error after dropping all constraints");g.addNativeError(p),m=g}return yield this.retryGetLocalTracks(m,t,i,r)}}i.audio=o?"empty":i.audio,i.video=n?"empty":i.video,d.w(this.TAG,"Fetch AV Tracks failed",{fetchTrackOptions:i},e);try{return yield this.getLocalTracks(i,t,r)}catch(l){return d.w(this.TAG,"Fetch empty tacks failed",l),i.audio=i.audio&&"empty",i.video=i.video&&"empty",this.observer.onFailure(l),yield this.getLocalTracks(i,t,r)}}else return d.w(this.TAG,"Fetch AV Tracks failed - unknown exception",e),this.observer.onFailure(e),[]})}getErrorType(e,t){return e&&t?"audio, video":e?"video":t?"audio":"unknown(video or audio)"}getEmptyTracks(e){let t=[];return e.audio==="empty"&&t.push(s.getEmptyAudioTrack()),e.video==="empty"&&t.push(s.getEmptyVideoTrack()),t}updateCurrentLocalTrackSettings(e){return c(this,null,function*(){let t=this.store.getLocalPeerTracks(),i=t.find(n=>n.type==="video"&&n.source==="regular"),r=t.find(n=>n.type==="audio"&&n.source==="regular"),a=t.find(n=>n.type==="video"&&n.source==="screen");e!=null&&e.video&&(yield i==null?void 0:i.setSettings(e.video)),e!=null&&e.audio&&(yield r==null?void 0:r.setSettings(e.audio));let o=this.getScreenshareSettings(!0);return o!=null&&o.video&&(yield a==null?void 0:a.setSettings(o==null?void 0:o.video)),{videoTrack:i,audioTrack:r}})}getAudioSettings(e){var o;let t=this.store.getPublishParams();if(!t||!((o=t.allowed)!=null&&o.includes("audio")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.audioTrack,a=(r==null?void 0:r.settings.deviceId)||e.audioInputDeviceId;return new ae().codec(t.audio.codec).maxBitrate(t.audio.bitRate).deviceId(a||Or.audioInputDeviceId).build()}getVideoSettings(e){var n;let t=this.store.getPublishParams();if(!t||!((n=t.allowed)!=null&&n.includes("video")))return null;let i=this.store.getLocalPeer(),r=i==null?void 0:i.videoTrack,a=(r==null?void 0:r.settings.deviceId)||e.videoDeviceId,o=t.video;return new ee().codec(o.codec).maxBitrate(o.bitRate).maxFramerate(o.frameRate).setWidth(o.width).setHeight(o.height).deviceId(a||Or.videoDeviceId).build()}getScreenshareSettings(e=!1){var r;let t=this.store.getPublishParams();if(!t||!((r=t.allowed)!=null&&r.includes("screen")))return null;let i=t.screen;return{video:new ee().maxBitrate(i.bitRate,!1).codec(i.codec).maxFramerate(i.frameRate).setWidth(i.width).setHeight(i.height).build(),audio:e?void 0:new ae().build()}}getOrDefaultScreenshareConfig(e){return c(this,null,function*(){var i;let t=Object.assign({videoOnly:!1,audioOnly:!1,forceCurrentTab:!1,preferCurrentTab:!1,selfBrowserSurface:"exclude",surfaceSwitching:"include",systemAudio:"exclude",displaySurface:"monitor"},e||{});return t.forceCurrentTab&&(t.videoOnly=!0,t.preferCurrentTab=!0,t.selfBrowserSurface="include",t.surfaceSwitching="exclude"),t.preferCurrentTab&&(t.selfBrowserSurface="include",t.displaySurface=void 0),t.cropElement&&((i=window.CropTarget)!=null&&i.fromElement)&&(t.cropTarget=yield window.CropTarget.fromElement(t.cropElement)),t})}createHMSLocalTracks(e,t,i){let r=e.find(n=>n.kind==="video"),a=e.find(n=>n.kind==="audio");i?e.forEach(n=>i==null?void 0:i.nativeStream.addTrack(n)):i=new we(new MediaStream(e));let o=[];if(a&&(t!=null&&t.audio)){let n=new oe(i,a,"regular",this.eventBus,t.audio);o.push(n)}if(r&&(t!=null&&t.video)){let n=new U(i,r,"regular",this.eventBus,t.video);n.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"regular")),o.push(n)}return o}};function ta(s,e){return function(i){return i in s&&s[i]!==e[i]}}var U=class s extends $e{constructor(t,i,r,a,o=new ee().build()){super(t,i,r);this.eventBus=a;this._layerDefinitions=[];this.TAG="[HMSLocalVideoTrack]";this.isCurrentTab=!1;this.isPublished=!1;this.replaceSenderTrack=t=>c(this,null,function*(){if(!this.transceiver||this.transceiver.direction!=="sendonly"){d.d(this.TAG,`transceiver for ${this.trackId} not available or not connected yet`);return}yield this.transceiver.sender.replaceTrack(t)});this.buildNewSettings=t=>{let{width:i,height:r,codec:a,maxFramerate:o,maxBitrate:n,deviceId:l,advanced:u,facingMode:p}=S(S({},this.settings),t);return new De(i,r,a,o,l,u,n,p)};this.handleSettingsChange=t=>c(this,null,function*(){let i=this.stream,r=ta(t,this.settings);if(r("maxBitrate")&&t.maxBitrate&&(yield i.setMaxBitrateAndFramerate(this)),r("width")||r("height")||r("advanced"))if(this.source==="video"){let a=yield this.replaceTrackWith(t);yield this.replaceSender(a,this.enabled),this.nativeTrack=a,this.videoHandler.updateSinks()}else yield this.nativeTrack.applyConstraints(t.toConstraints())});this.handleDeviceChange=(t,i=!1)=>c(this,null,function*(){if(ta(t,this.settings)("deviceId")&&this.source==="regular"){if(this.enabled){delete t.facingMode;let a=yield this.replaceTrackWith(t);yield this.replaceSender(a,this.enabled),this.nativeTrack=a,this.videoHandler.updateSinks()}i||Q.updateSelection("videoInput",{deviceId:t.deviceId,groupId:this.nativeTrack.getSettings().groupId})}});this.removeOrReplaceProcessedTrack=t=>c(this,null,function*(){t?t!==this.processedTrack&&(this.processedTrack=t):this.processedTrack=void 0,yield this.replaceSenderTrack(this.processedTrack||this.nativeTrack)});t.tracks.push(this),this.setVideoHandler(new We(this)),this.settings=o,o.deviceId!==i.getSettings().deviceId&&i.enabled&&(this.settings=this.buildNewSettings({deviceId:i.getSettings().deviceId})),this.pluginsManager=new gt(this,a),this.mediaStreamPluginsManager=new ni,this.setFirstTrackId(this.trackId)}setSimulcastDefinitons(t){this._layerDefinitions=t}getSimulcastDefinitions(){return this._layerDefinitions}setEnabled(t){return c(this,null,function*(){var i;if(t!==this.enabled){if(this.source==="regular"){let r;t?r=yield this.replaceTrackWith(this.settings):r=yield this.replaceTrackWithBlank(),yield this.replaceSender(r,t),(i=this.nativeTrack)==null||i.stop(),this.nativeTrack=r,yield q(s.prototype,this,"setEnabled").call(this,t),t&&(yield this.pluginsManager.waitForRestart(),yield this.processPlugins(),this.settings=this.buildNewSettings({deviceId:r.getSettings().deviceId})),this.videoHandler.updateSinks()}this.eventBus.localVideoEnabled.publish({enabled:t,track:this})}})}processPlugins(){return c(this,null,function*(){try{if(this.pluginsManager.getPlugins().length>0)return;if(this.mediaStreamPluginsManager.getPlugins().length>0){let r=this.mediaStreamPluginsManager.applyPlugins(new MediaStream([this.nativeTrack])).getVideoTracks()[0];yield this.setProcessedTrack(r)}else yield this.setProcessedTrack()}catch(t){console.error("error in processing plugin(s)",t)}})}addStreamPlugins(t){return c(this,null,function*(){if(this.pluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSMediaStreamPlugin and HMSVideoPlugin cannot be used together");this.mediaStreamPluginsManager.addPlugins(t),yield this.processPlugins()})}removeStreamPlugins(t){return c(this,null,function*(){this.mediaStreamPluginsManager.removePlugins(t),yield this.processPlugins()})}isPublishedTrackId(t){return this.publishedTrackId===t}addSink(t){this.addSinkInternal(t,this.processedTrack||this.nativeTrack)}setSettings(t,i=!1){return c(this,null,function*(){let r=this.buildNewSettings(t);if(yield this.handleDeviceChange(r,i),!this.enabled||le(this.nativeTrack)){this.settings=r;return}yield this.handleSettingsChange(r),this.settings=r})}getPlugins(){return this.mediaStreamPluginsManager.getPlugins().length>0?this.mediaStreamPluginsManager.getPlugins():this.pluginsManager.getPlugins()}addPlugin(t,i){return c(this,null,function*(){if(this.mediaStreamPluginsManager.getPlugins().length>0)throw Error("Plugins of type HMSVideoPlugin and HMSMediaStreamPlugin cannot be used together");return this.pluginsManager.addPlugin(t,i)})}removePlugin(t){return c(this,null,function*(){return this.pluginsManager.removePlugin(t)})}validatePlugin(t){return this.pluginsManager.validatePlugin(t)}cleanup(){return c(this,null,function*(){var t;q(s.prototype,this,"cleanup").call(this),this.transceiver=void 0,yield this.pluginsManager.cleanup(),(t=this.processedTrack)==null||t.stop(),this.isPublished=!1})}cropTo(t){return c(this,null,function*(){if(t&&this.source==="screen")try{this.nativeTrack.cropTo&&(yield this.nativeTrack.cropTo(t))}catch(i){throw d.e(this.TAG,"failed to crop screenshare capture - ",i),h.TracksErrors.GenericTrack("TRACK","failed to crop screenshare capture")}})}getCaptureHandle(){if(this.nativeTrack.getCaptureHandle)return this.nativeTrack.getCaptureHandle()}setProcessedTrack(t){return c(this,null,function*(){if(!this.nativeTrack.enabled){this.processedTrack=t;return}yield this.removeOrReplaceProcessedTrack(t),this.videoHandler.updateSinks()})}getTrackIDBeingSent(){return this.getTrackBeingSent().id}getTrackBeingSent(){return this.enabled?this.processedTrack||this.nativeTrack:this.nativeTrack}switchCamera(){return c(this,null,function*(){var a;let t=this.getMediaTrackSettings().facingMode;if(!t||this.source!=="regular"){d.d(this.TAG,"facingMode not supported");return}let i=t==="environment"?"user":"environment";(a=this.nativeTrack)==null||a.stop();let r=yield this.replaceTrackWith(this.buildNewSettings({facingMode:i,deviceId:void 0}));yield this.replaceSender(r,this.enabled),this.nativeTrack=r,this.videoHandler.updateSinks(),this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId,facingMode:i}),Q.updateSelection("videoInput",{deviceId:this.settings.deviceId,groupId:this.nativeTrack.getSettings().groupId})})}replaceTrackWith(t){return c(this,null,function*(){let i=this.nativeTrack;i==null||i.stop();try{let r=yield qs(t);return d.d(this.TAG,"replaceTrack, Previous track stopped",i,"newTrack",r),this.settings.deviceId==="default"&&(this.settings=this.buildNewSettings({deviceId:this.nativeTrack.getSettings().deviceId})),r}catch(r){throw this.isPublished&&this.eventBus.analytics.publish(M.publish({error:r})),r}})}replaceTrackWithBlank(){return c(this,null,function*(){let t=this.nativeTrack,i=Te.getEmptyVideoTrack(t);return t==null||t.stop(),d.d(this.TAG,"replaceTrackWithBlank, Previous track stopped",t,"newTrack",i),i})}replaceSender(t,i){return c(this,null,function*(){i?yield this.replaceSenderTrack(this.processedTrack||t):yield this.replaceSenderTrack(t),this.stream.replaceStreamTrack(this.nativeTrack,t)})}};var Ke="renegotiation-callback-id",li="ion-sfu";var qe="SUBSCRIBE_ICE_CONNECTION_CALLBACK_ID";var ia="https://event.100ms.live/v2/client/report",ra="https://event-nonprod.100ms.live/v2/client/report";var V={DEVICE_CHANGE:"device-change",LOCAL_AUDIO_ENABLED:"local-audio-enabled",LOCAL_VIDEO_ENABLED:"local-video-enabled",STATS_UPDATE:"stats-update",RTC_STATS_UPDATE:"rtc-stats-update",TRACK_DEGRADED:"track-degraded",TRACK_RESTORED:"track-restored",TRACK_AUDIO_LEVEL_UPDATE:"track-audio-level-update",LOCAL_AUDIO_SILENCE:"local-audio-silence",ANALYTICS:"analytics",AUDIO_PLUGIN_FAILED:"audio-plugin-failed",POLICY_CHANGE:"policy-change",LOCAL_ROLE_UPDATE:"local-role-update",AUDIO_TRACK_UPDATE:"audio-track-update",AUDIO_TRACK_ADDED:"audio-track-added",AUDIO_TRACK_REMOVED:"audio-track-removed",AUTOPLAY_ERROR:"autoplay-error",LEAVE:"leave"},sa="2.5",aa="20231201",fe="_handraise",Ur=1e3,Vr=64;var _=class s extends $e{constructor(t,i,r){super(t,i,r);this._degraded=!1;this._degradedAt=null;this._layerDefinitions=[];this.history=new Br;this.preferredLayer="high";this.setVideoHandler(new We(this))}setTrackId(t){this.bizTrackId=t}get trackId(){return this.bizTrackId||super.trackId}get degraded(){return this._degraded}get degradedAt(){return this._degradedAt}setEnabled(t){return c(this,null,function*(){t!==this.enabled&&(q(s.prototype,this,"setEnabled").call(this,t),this.videoHandler.updateSinks(!0))})}setPreferredLayer(t){return c(this,null,function*(){if(t==="none"){d.w("layer none will be ignored");return}if(this.preferredLayer=t,!!this.shouldSendVideoLayer(t,"preferLayer")){if(!this.hasSinks()){d.d(`[Remote Track] ${this.logIdentifier}
39
39
  streamId=${this.stream.id}
40
40
  trackId=${this.trackId}
41
41
  saving ${t}, source=${this.source}
42
- Track does not have any sink`);return}yield this.requestLayer(t,"preferLayer"),this.pushInHistory(`uiPreferLayer-${t}`)}})}getSimulcastLayer(){return this.stream.getSimulcastLayer()}getLayer(){return this.stream.getVideoLayer()}getPreferredLayer(){return this.preferredLayer}replaceTrack(t){this.nativeTrack=t.nativeTrack,t.transceiver&&(this.transceiver=t.transceiver,this.stream.updateId(t.stream.id)),this.videoHandler.updateSinks()}addSink(t,i=!0){return c(this,null,function*(){de(this.nativeTrack)?yield this.requestLayer(this.preferredLayer,"addSink"):(q(s.prototype,this,"addSink").call(this,t),i&&(yield this.updateLayer("addSink"))),this.pushInHistory("uiSetLayer-high")})}removeSink(t,i=!0){return c(this,null,function*(){q(s.prototype,this,"removeSink").call(this,t),i&&(yield this.updateLayer("removeSink")),this._degraded=!1,this.pushInHistory("uiSetLayer-none")})}getSimulcastDefinitions(){return[...this._layerDefinitions]}setSimulcastDefinitons(t){this._layerDefinitions=t}setLayerFromServer(t){this._degraded=this.enabled&&(t.publisher_degraded||t.subscriber_degraded)&&t.current_layer==="none",this._degradedAt=this._degraded?new Date:this._degradedAt;let i=t.current_layer;return d.d(`[Remote Track] ${this.logIdentifier}
42
+ Track does not have any sink`);return}yield this.requestLayer(t,"preferLayer"),this.pushInHistory(`uiPreferLayer-${t}`)}})}getSimulcastLayer(){return this.stream.getSimulcastLayer()}getLayer(){return this.stream.getVideoLayer()}getPreferredLayer(){return this.preferredLayer}replaceTrack(t){this.nativeTrack=t.nativeTrack,t.transceiver&&(this.transceiver=t.transceiver,this.stream.updateId(t.stream.id)),this.videoHandler.updateSinks()}addSink(t,i=!0){return c(this,null,function*(){le(this.nativeTrack)?yield this.requestLayer(this.preferredLayer,"addSink"):(q(s.prototype,this,"addSink").call(this,t),i&&(yield this.updateLayer("addSink"))),this.pushInHistory("uiSetLayer-high")})}removeSink(t,i=!0){return c(this,null,function*(){q(s.prototype,this,"removeSink").call(this,t),i&&(yield this.updateLayer("removeSink")),this._degraded=!1,this.pushInHistory("uiSetLayer-none")})}getSimulcastDefinitions(){return[...this._layerDefinitions]}setSimulcastDefinitons(t){this._layerDefinitions=t}setLayerFromServer(t){this._degraded=this.enabled&&(t.publisher_degraded||t.subscriber_degraded)&&t.current_layer==="none",this._degradedAt=this._degraded?new Date:this._degradedAt;let i=t.current_layer;return d.d(`[Remote Track] ${this.logIdentifier}
43
43
  streamId=${this.stream.id}
44
44
  trackId=${this.trackId}
45
45
  layer update from sfu
@@ -63,7 +63,7 @@
63
63
  Setting layer field to=${t}`)}setVideoLayer(t,i,r,a){return d.d(`[Remote stream] ${r}
64
64
  streamId=${this.id}
65
65
  trackId=${i}
66
- source: ${a} request ${t} layer`),this.setVideoLayerLocally(t,r,a),this.connection.sendOverApiDataChannelWithResponse({params:{max_spatial_layer:this.video,track_id:i},method:"prefer-video-track-state"})}getSimulcastLayer(){return this.video}getVideoLayer(){return this.video}isAudioSubscribed(){return this.audio}};var ra=(s,e,t,i)=>c(void 0,null,function*(){var o;let r,a={};if((o=e.transceiver)!=null&&o.sender.track){try{r=yield e.transceiver.sender.getStats();let n={},l={},u={};r==null||r.forEach(p=>{switch(p.type){case"outbound-rtp":l[p.id]=p;break;case"remote-inbound-rtp":u[p.ssrc]=p;break;case"codec":n[p.id]=p.mimeType;break;default:break}}),Object.keys(S({},l)).forEach(p=>{var G,et;let m=(G=l[p])==null?void 0:G.codecId,g=m?n[m]:void 0,f;g&&(f=g.substring(g.indexOf("/")+1));let R=y(S({},l[p]),{rid:(et=l[p])==null?void 0:et.rid}),b=u[R.ssrc];a[p]=y(S({},R),{bitrate:$r("bytesSent",R,i==null?void 0:i[p]),packetsLost:b==null?void 0:b.packetsLost,jitter:b==null?void 0:b.jitter,roundTripTime:b==null?void 0:b.roundTripTime,totalRoundTripTime:b==null?void 0:b.totalRoundTripTime,peerName:t,peerID:e.peerId,enabled:e.enabled,codec:f})})}catch(n){s.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("TRACK",`Error getting local track stats ${e.trackId} - ${n.message}`))),d.w("[HMSWebrtcStats]","Error in getting local track stats",e,n,n.name)}return a}}),sa=(s,e,t,i)=>c(void 0,null,function*(){var l;let r;try{r=yield(l=e.transceiver)==null?void 0:l.receiver.getStats()}catch(u){s.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("TRACK",`Error getting remote track stats ${e.trackId} - ${u.message}`))),d.w("[HMSWebrtcStats]","Error in getting remote track stats",e,u)}let a=sn(r),o=$r("bytesReceived",a,i),n=Fr("packetsLost",a,i);return a!=null&&a.remote&&Object.assign(a.remote,{packetsLostRate:Fr("packetsLost",a.remote,i==null?void 0:i.remote)}),a&&Object.assign(a,{bitrate:o,packetsLostRate:n,peerId:e.peerId,enabled:e.enabled,peerName:t,codec:a.codec})}),sn=s=>{let e,t,i={};s==null||s.forEach(o=>{switch(o.type){case"inbound-rtp":e=o;break;case"outbound-rtp":e=o;break;case"remote-inbound-rtp":t=o;break;case"codec":i[o.id]=o.mimeType;break;default:break}});let r=e!=null&&e.codecId?i[e.codecId]:void 0,a;return r&&(a=r.substring(r.indexOf("/")+1)),e&&Object.assign(e,{remote:t,codec:a})},Gr=(s,e,t)=>{let i=an(e),r=$r(s==="publish"?"bytesSent":"bytesReceived",i,t&&t[s]);return i&&Object.assign(i,{bitrate:r})},an=s=>{let e;return s==null||s.forEach(t=>{t.type==="transport"&&(e=s==null?void 0:s.get(t.selectedCandidatePairId))}),e||s==null||s.forEach(t=>{t.type==="candidate-pair"&&t.selected&&(e=t)}),e},aa=s=>{let e={packetsLost:0,jitter:0};return s==null||s.forEach(t=>{t.packetsLost&&(e.packetsLost+=t.packetsLost),t.jitter>e.jitter&&(e.jitter=t.jitter)}),e},oa=(s,e)=>Array.from(new Set(s.concat(e))),$r=(s,e,t)=>Fr(s,e,t)*8,Fr=(s,e,t)=>{let i=e&&e[s],r=t?t[s]:null;return[e,t,se(i),se(r)].every(o=>!!o)?Wr(i,r,e==null?void 0:e.timestamp,t==null?void 0:t.timestamp)*1e3:0},Wr=(s,e,t,i)=>se(s)&&se(e)&&t&&i?(s-e)/(t-i):0;var ui=class{constructor(e,t,i){this.getStats=e;this.store=t;this.eventBus=i;this.TAG="[HMSWebrtcStats]";this.peerStats={};this.remoteTrackStats={};this.localTrackStats={};this.getLocalPeerStats=()=>this.peerStats[this.localPeerID];this.getRemoteTrackStats=e=>this.remoteTrackStats[e];this.getAllRemoteTracksStats=()=>this.remoteTrackStats;this.getLocalTrackStats=()=>this.localTrackStats;this.updateStats=()=>c(this,null,function*(){yield this.updateLocalPeerStats(),yield this.updateLocalTrackStats(),yield this.updateRemoteTrackStats()});this.updateLocalPeerStats=()=>c(this,null,function*(){var p,m,g,f,R,b;let e=this.getLocalPeerStats(),t;try{t=yield(m=(p=this.getStats).publish)==null?void 0:m.call(p)}catch(G){this.eventBus.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("PUBLISH",G.message))),d.w(this.TAG,"Error in getting publish stats",G)}let i=t&&Gr("publish",t,e),r;try{r=yield(f=(g=this.getStats).subscribe)==null?void 0:f.call(g)}catch(G){this.eventBus.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("SUBSCRIBE",G.message))),d.w(this.TAG,"Error in getting subscribe stats",G)}let a=r&&Gr("subscribe",r,e),{packetsLost:o,jitter:n}=aa(r),l=Wr(o,(R=e==null?void 0:e.subscribe)==null?void 0:R.packetsLost,a==null?void 0:a.timestamp,(b=e==null?void 0:e.subscribe)==null?void 0:b.timestamp),u=a&&Object.assign(a,{packetsLostRate:l,jitter:n,packetsLost:o});this.peerStats[this.localPeerID]={publish:i,subscribe:u}});this.updateRemoteTrackStats=()=>c(this,null,function*(){var i;let e=Array.from(this.store.getTracksMap().values()).filter(r=>r instanceof _||r instanceof te),t=e.map(r=>r.trackId);Object.keys(this.remoteTrackStats).forEach(r=>{t.includes(r)||delete this.remoteTrackStats[r]});for(let r of e){let a=r.peerId&&((i=this.store.getPeerById(r.peerId))==null?void 0:i.name),o=this.getRemoteTrackStats(r.trackId),n=yield sa(this.eventBus,r,a,o);n&&(this.remoteTrackStats[r.trackId]=n)}});this.updateLocalTrackStats=()=>c(this,null,function*(){var i;let e=this.store.getLocalPeerTracks().reduce((r,a)=>(r[a.getTrackIDBeingSent()]=a,r),{}),t=oa(Object.keys(this.localTrackStats),Object.keys(e));for(let r of t){let a=e[r];if(a){let o=(i=this.store.getLocalPeer())==null?void 0:i.name,n=yield ra(this.eventBus,a,o,this.localTrackStats[r]);n&&(this.localTrackStats[r]=n)}else delete this.localTrackStats[r]}});var r;this.localPeerID=(r=this.store.getLocalPeer())==null?void 0:r.peerId}};var pi=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.publishConnection=i;this.subscribeConnection=r;this.TAG="[HMSWebrtcInternals]";this.interval=1e3;this.isMonitored=!1;this.handleStatsUpdate=()=>c(this,null,function*(){var e;yield(e=this.hmsStats)==null?void 0:e.updateStats(),this.eventBus.statsUpdate.publish(this.hmsStats)})}getPublishPeerConnection(){return this.publishConnection}getSubscribePeerConnection(){return this.subscribeConnection}getCurrentStats(){return this.hmsStats}onStatsChange(e){return this.eventBus.statsUpdate.subscribe(e),()=>{this.eventBus.statsUpdate.unsubscribe(e)}}setPeerConnections({publish:e,subscribe:t}){var i,r;this.publishConnection=e,this.subscribeConnection=t,this.hmsStats=new ui({publish:(i=this.publishConnection)==null?void 0:i.getStats.bind(this.publishConnection),subscribe:(r=this.subscribeConnection)==null?void 0:r.getStats.bind(this.subscribeConnection)},this.store,this.eventBus)}start(){return c(this,null,function*(){if(this.isMonitored){d.d(this.TAG,"Already started");return}this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting Webrtc Stats Monitor"),this.startLoop().then(()=>d.d(this.TAG,"Stopping Webrtc Stats Monitor")).catch(e=>{this.eventBus.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("PUBLISH",e.message))),d.e(this.TAG,e.message)})})}stop(){this.isMonitored=!1}startLoop(){return c(this,null,function*(){for(;this.isMonitored;)yield this.handleStatsUpdate(),yield X(this.interval)})}cleanup(){this.stop(),this.eventBus.statsUpdate.removeAllListeners()}};var je=class{constructor({peerId:e,name:t,isLocal:i,customerUserId:r,metadata:a,role:o,joinedAt:n,groups:l,realtime:u}){this.customerUserId="";this.metadata="";this.auxiliaryTracks=[];this.name=t,this.peerId=e,this.isLocal=i,this.customerUserId=r,this.metadata=a,this.joinedAt=n,this.groups=l,this.realtime=u,o&&(this.role=o)}get isHandRaised(){var e;return!!((e=this.groups)!=null&&e.includes(fe))}updateRole(e){this.role=e}updateName(e){this.name=e}updateNetworkQuality(e){this.networkQuality=e}updateMetadata(e){this.metadata=e}updateGroups(e){this.groups=e}toString(){var e,t,i,r;return`{
66
+ source: ${a} request ${t} layer`),this.setVideoLayerLocally(t,r,a),this.connection.sendOverApiDataChannelWithResponse({params:{max_spatial_layer:this.video,track_id:i},method:"prefer-video-track-state"})}getSimulcastLayer(){return this.video}getVideoLayer(){return this.video}isAudioSubscribed(){return this.audio}};var oa=(s,e,t,i)=>c(void 0,null,function*(){var o;let r,a={};if((o=e.transceiver)!=null&&o.sender.track){try{r=yield e.transceiver.sender.getStats();let n={},l={},u={};r==null||r.forEach(p=>{switch(p.type){case"outbound-rtp":l[p.id]=p;break;case"remote-inbound-rtp":u[p.ssrc]=p;break;case"codec":n[p.id]=p.mimeType;break;default:break}}),Object.keys(S({},l)).forEach(p=>{var G,et;let m=(G=l[p])==null?void 0:G.codecId,g=m?n[m]:void 0,f;g&&(f=g.substring(g.indexOf("/")+1));let R=y(S({},l[p]),{rid:(et=l[p])==null?void 0:et.rid}),b=u[R.ssrc];a[p]=y(S({},R),{bitrate:$r("bytesSent",R,i==null?void 0:i[p]),packetsLost:b==null?void 0:b.packetsLost,jitter:b==null?void 0:b.jitter,roundTripTime:b==null?void 0:b.roundTripTime,totalRoundTripTime:b==null?void 0:b.totalRoundTripTime,peerName:t,peerID:e.peerId,enabled:e.enabled,codec:f})})}catch(n){s.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("TRACK",`Error getting local track stats ${e.trackId} - ${n.message}`))),d.w("[HMSWebrtcStats]","Error in getting local track stats",e,n,n.name)}return a}}),na=(s,e,t,i)=>c(void 0,null,function*(){var l;let r;try{r=yield(l=e.transceiver)==null?void 0:l.receiver.getStats()}catch(u){s.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("TRACK",`Error getting remote track stats ${e.trackId} - ${u.message}`))),d.w("[HMSWebrtcStats]","Error in getting remote track stats",e,u)}let a=nn(r),o=$r("bytesReceived",a,i),n=Fr("packetsLost",a,i);return a!=null&&a.remote&&Object.assign(a.remote,{packetsLostRate:Fr("packetsLost",a.remote,i==null?void 0:i.remote)}),a&&Object.assign(a,{bitrate:o,packetsLostRate:n,peerId:e.peerId,enabled:e.enabled,peerName:t,codec:a.codec})}),nn=s=>{let e,t,i={};s==null||s.forEach(o=>{switch(o.type){case"inbound-rtp":e=o;break;case"outbound-rtp":e=o;break;case"remote-inbound-rtp":t=o;break;case"codec":i[o.id]=o.mimeType;break;default:break}});let r=e!=null&&e.codecId?i[e.codecId]:void 0,a;return r&&(a=r.substring(r.indexOf("/")+1)),e&&Object.assign(e,{remote:t,codec:a})},Gr=(s,e,t)=>{let i=cn(e),r=$r(s==="publish"?"bytesSent":"bytesReceived",i,t&&t[s]);return i&&Object.assign(i,{bitrate:r})},cn=s=>{let e;return s==null||s.forEach(t=>{t.type==="transport"&&(e=s==null?void 0:s.get(t.selectedCandidatePairId))}),e||s==null||s.forEach(t=>{t.type==="candidate-pair"&&t.selected&&(e=t)}),e},ca=s=>{let e={packetsLost:0,jitter:0};return s==null||s.forEach(t=>{t.packetsLost&&(e.packetsLost+=t.packetsLost),t.jitter>e.jitter&&(e.jitter=t.jitter)}),e},da=(s,e)=>Array.from(new Set(s.concat(e))),$r=(s,e,t)=>Fr(s,e,t)*8,Fr=(s,e,t)=>{let i=e&&e[s],r=t?t[s]:null;return[e,t,se(i),se(r)].every(o=>!!o)?Wr(i,r,e==null?void 0:e.timestamp,t==null?void 0:t.timestamp)*1e3:0},Wr=(s,e,t,i)=>se(s)&&se(e)&&t&&i?(s-e)/(t-i):0;var ui=class{constructor(e,t,i){this.getStats=e;this.store=t;this.eventBus=i;this.TAG="[HMSWebrtcStats]";this.peerStats={};this.remoteTrackStats={};this.localTrackStats={};this.getLocalPeerStats=()=>this.peerStats[this.localPeerID];this.getRemoteTrackStats=e=>this.remoteTrackStats[e];this.getAllRemoteTracksStats=()=>this.remoteTrackStats;this.getLocalTrackStats=()=>this.localTrackStats;this.updateStats=()=>c(this,null,function*(){yield this.updateLocalPeerStats(),yield this.updateLocalTrackStats(),yield this.updateRemoteTrackStats()});this.updateLocalPeerStats=()=>c(this,null,function*(){var p,m,g,f,R,b;let e=this.getLocalPeerStats(),t;try{t=yield(m=(p=this.getStats).publish)==null?void 0:m.call(p)}catch(G){this.eventBus.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("PUBLISH",G.message))),d.w(this.TAG,"Error in getting publish stats",G)}let i=t&&Gr("publish",t,e),r;try{r=yield(f=(g=this.getStats).subscribe)==null?void 0:f.call(g)}catch(G){this.eventBus.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("SUBSCRIBE",G.message))),d.w(this.TAG,"Error in getting subscribe stats",G)}let a=r&&Gr("subscribe",r,e),{packetsLost:o,jitter:n}=ca(r),l=Wr(o,(R=e==null?void 0:e.subscribe)==null?void 0:R.packetsLost,a==null?void 0:a.timestamp,(b=e==null?void 0:e.subscribe)==null?void 0:b.timestamp),u=a&&Object.assign(a,{packetsLostRate:l,jitter:n,packetsLost:o});this.peerStats[this.localPeerID]={publish:i,subscribe:u}});this.updateRemoteTrackStats=()=>c(this,null,function*(){var i;let e=Array.from(this.store.getTracksMap().values()).filter(r=>r instanceof _||r instanceof te),t=e.map(r=>r.trackId);Object.keys(this.remoteTrackStats).forEach(r=>{t.includes(r)||delete this.remoteTrackStats[r]});for(let r of e){let a=r.peerId&&((i=this.store.getPeerById(r.peerId))==null?void 0:i.name),o=this.getRemoteTrackStats(r.trackId),n=yield na(this.eventBus,r,a,o);n&&(this.remoteTrackStats[r.trackId]=n)}});this.updateLocalTrackStats=()=>c(this,null,function*(){var i;let e=this.store.getLocalPeerTracks().reduce((r,a)=>(r[a.getTrackIDBeingSent()]=a,r),{}),t=da(Object.keys(this.localTrackStats),Object.keys(e));for(let r of t){let a=e[r];if(a){let o=(i=this.store.getLocalPeer())==null?void 0:i.name,n=yield oa(this.eventBus,a,o,this.localTrackStats[r]);n&&(this.localTrackStats[r]=n)}else delete this.localTrackStats[r]}});var r;this.localPeerID=(r=this.store.getLocalPeer())==null?void 0:r.peerId}};var pi=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.publishConnection=i;this.subscribeConnection=r;this.TAG="[HMSWebrtcInternals]";this.interval=1e3;this.isMonitored=!1;this.handleStatsUpdate=()=>c(this,null,function*(){var e;yield(e=this.hmsStats)==null?void 0:e.updateStats(),this.eventBus.statsUpdate.publish(this.hmsStats)})}getPublishPeerConnection(){return this.publishConnection}getSubscribePeerConnection(){return this.subscribeConnection}getCurrentStats(){return this.hmsStats}onStatsChange(e){return this.eventBus.statsUpdate.subscribe(e),()=>{this.eventBus.statsUpdate.unsubscribe(e)}}setPeerConnections({publish:e,subscribe:t}){var i,r;this.publishConnection=e,this.subscribeConnection=t,this.hmsStats=new ui({publish:(i=this.publishConnection)==null?void 0:i.getStats.bind(this.publishConnection),subscribe:(r=this.subscribeConnection)==null?void 0:r.getStats.bind(this.subscribeConnection)},this.store,this.eventBus)}start(){return c(this,null,function*(){if(this.isMonitored){d.d(this.TAG,"Already started");return}this.stop(),this.isMonitored=!0,d.d(this.TAG,"Starting Webrtc Stats Monitor"),this.startLoop().then(()=>d.d(this.TAG,"Stopping Webrtc Stats Monitor")).catch(e=>{this.eventBus.analytics.publish(M.rtcStatsFailed(h.WebrtcErrors.StatsFailed("PUBLISH",e.message))),d.e(this.TAG,e.message)})})}stop(){this.isMonitored=!1}startLoop(){return c(this,null,function*(){for(;this.isMonitored;)yield this.handleStatsUpdate(),yield X(this.interval)})}cleanup(){this.stop(),this.eventBus.statsUpdate.removeAllListeners()}};var je=class{constructor({peerId:e,name:t,isLocal:i,customerUserId:r,metadata:a,role:o,joinedAt:n,groups:l,realtime:u}){this.customerUserId="";this.metadata="";this.auxiliaryTracks=[];this.name=t,this.peerId=e,this.isLocal=i,this.customerUserId=r,this.metadata=a,this.joinedAt=n,this.groups=l,this.realtime=u,o&&(this.role=o)}get isHandRaised(){var e;return!!((e=this.groups)!=null&&e.includes(fe))}updateRole(e){this.role=e}updateName(e){this.name=e}updateNetworkQuality(e){this.networkQuality=e}updateMetadata(e){this.metadata=e}updateGroups(e){this.groups=e}toString(){var e,t,i,r;return`{
67
67
  name: ${this.name};
68
68
  role: ${(e=this.role)==null?void 0:e.name};
69
69
  peerId: ${this.peerId};
@@ -71,7 +71,7 @@
71
71
  ${this.audioTrack?`audioTrack: ${(t=this.audioTrack)==null?void 0:t.trackId};`:""}
72
72
  ${this.videoTrack?`videoTrack: ${(i=this.videoTrack)==null?void 0:i.trackId};`:""}
73
73
  groups: ${(r=this.groups)==null?void 0:r.join()}
74
- }`}};var na=require("uuid"),Je=class{};Je.makePeerId=()=>(0,na.v4)();var Tt=class extends je{constructor(t){super(y(S({},t),{peerId:Je.makePeerId(),isLocal:!0}));this.isLocal=!0;this.auxiliaryTracks=[];this.asRole=t.asRole}isInPreview(){return!!this.asRole}toString(){var t,i,r;return`{
74
+ }`}};var la=require("uuid"),Je=class{};Je.makePeerId=()=>(0,la.v4)();var Tt=class extends je{constructor(t){super(y(S({},t),{peerId:Je.makePeerId(),isLocal:!0}));this.isLocal=!0;this.auxiliaryTracks=[];this.asRole=t.asRole}isInPreview(){return!!this.asRole}toString(){var t,i,r;return`{
75
75
  name: ${this.name};
76
76
  role: ${(t=this.role)==null?void 0:t.name};
77
77
  peerId: ${this.peerId};
@@ -79,5 +79,5 @@
79
79
  ${this.asRole?`asRole: ${this.asRole.name};`:""}
80
80
  ${this.audioTrack?`audioTrack: ${(i=this.audioTrack)==null?void 0:i.trackId};`:""}
81
81
  ${this.videoTrack?`videoTrack: ${(r=this.videoTrack)==null?void 0:r.trackId};`:""}
82
- }`}};var ft=class extends je{constructor(t){super(y(S({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var Re=(s,e)=>new ft({peerId:s.peer_id,name:s.info.name,role:e.getPolicyForRole(s.role),customerUserId:s.info.user_id,metadata:s.info.data,groups:s.groups});var hi=class{constructor(e,t,i){this.transport=e;this.store=t;this.options=i;this.isEnd=!1;this.iterator=null;this.total=0;this.defaultPaginationLimit=10}validateConnection(){if(!this.transport||!this.store)throw Error("Use usePaginatedParticipants or hmsActions.getPeerListIterator after preview or join has happened")}hasNext(){return!this.isEnd}getTotal(){return this.total}findPeers(){return c(this,null,function*(){var t;this.validateConnection();let e=yield this.transport.signal.findPeers(y(S({},this.options||{}),{limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}));return this.updateState(e),this.processPeers(e.peers)})}next(){return c(this,null,function*(){var t;this.validateConnection();let e;return!this.iterator&&!this.isEnd?yield this.findPeers():this.iterator?(e=yield this.transport.signal.peerIterNext({iterator:this.iterator,limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}),this.updateState(e),this.processPeers(e.peers)):[]})}processPeers(e){let t=[];return e.forEach(i=>{let r=Re(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var Qe=class{constructor(e){this.TAG="[AudioContextManager]";this.audioContext=new AudioContext,this.source=this.audioContext.createMediaElementSource(e),this.source.connect(this.audioContext.destination)}resumeContext(){return c(this,null,function*(){this.audioContext.state==="suspended"&&(yield this.audioContext.resume(),d.d(this.TAG,"AudioContext is resumed"))})}getAudioTrack(){return this.destinationNode&&this.source.disconnect(this.destinationNode),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.source.connect(this.destinationNode),this.destinationNode.stream.getAudioTracks()[0]}cleanup(){this.audioContext.state!=="closed"&&this.audioContext.close().catch(e=>{d.d(this.TAG,"AudioContext close error",e.message)})}};var ca=require("eventemitter2"),He=class extends ca.EventEmitter2{on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,t){return super.emit(e,t)}listeners(e){return super.listeners(e)}};var Si=class extends He{constructor(){super(...arguments);this.audioElement=null;this.TAG="[PlaylistAudioManager]";this.seeked=!1}play(t){return c(this,null,function*(){return this.audioElement=this.getAudioElement(),new Promise((i,r)=>{this.audioElement=this.getAudioElement(),this.audioElement.src=t,this.seeked=!1,this.audioElement.onerror=()=>{let a=`Error loading ${t}`;d.e(this.TAG,a),this.stop(),r(a)},this.audioElement.oncanplaythrough=()=>c(this,null,function*(){try{if(!this.audioElement)return;if(this.audioContextManager.resumeContext(),this.track)this.seeked?this.seeked=!1:(yield this.audioElement.play(),i([this.track]));else{yield this.audioElement.play();let a=this.audioContextManager.getAudioTrack();this.track=a,i([a])}}catch(a){d.e(this.TAG,"Error playing audio",t,a.message),r(a)}}),this.audioElement.onseeked=()=>{this.seeked=!0}})})}getTracks(){return this.track?[this.track.id]:[]}getElement(){return this.audioElement||(this.audioElement=this.getAudioElement()),this.audioElement}stop(){var t,i,r;(t=this.audioElement)==null||t.pause(),(i=this.audioElement)==null||i.removeAttribute("src"),this.audioElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.track=void 0}getAudioElement(){if(this.audioElement)return this.audioElement;let t=document.createElement("audio");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Qe(t),t}};var mi=class extends He{constructor(){super(...arguments);this.TAG="[PlaylistVideoManager]";this.videoElement=null;this.canvasContext=null;this.tracks=[];this.DEFAUL_FPS=24;this.seeked=!1;this.drawImage=()=>{var t,i,r;this.videoElement&&!this.videoElement.paused&&!this.videoElement.ended&&((r=this.canvasContext)==null||r.drawImage(this.videoElement,0,0,(t=this.canvas)==null?void 0:t.width,(i=this.canvas)==null?void 0:i.height),this.timer=setTimeout(()=>{this.drawImage()},1e3/this.DEFAUL_FPS))}}play(t){return this.videoElement=this.getVideoElement(),this.createCanvas(),new Promise((i,r)=>{this.videoElement=this.getVideoElement(),this.videoElement.src=t,this.seeked=!1,this.videoElement.onerror=()=>{let a=`Error loading ${t}`;d.e(this.TAG,a),this.stop(),r(a)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var a,o,n;try{if(!this.videoElement)return;if(this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,this.tracks.length===0){this.clearCanvasAndTracks();let l=this.canvas.captureStream();if(!l){d.e(this.TAG,"Browser does not support captureStream");return}this.videoElement.onplay=this.drawImage,yield this.audioContextManager.resumeContext(),yield this.videoElement.play();let u=this.audioContextManager.getAudioTrack();l.addTrack(u),l.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(n=this.canvasContext)==null||n.drawImage(this.videoElement,0,0,(a=this.canvas)==null?void 0:a.width,(o=this.canvas)==null?void 0:o.height)):(yield this.videoElement.play(),i(this.tracks))}catch(l){d.e(this.TAG,"Error playing video",t,l.message),r(l)}}),this.videoElement.onseeked=()=>{this.seeked=!0}})}getTracks(){return this.tracks.map(t=>t.id)}getElement(){return this.videoElement||(this.videoElement=this.getVideoElement()),this.videoElement}stop(){var t,i,r;(t=this.videoElement)==null||t.pause(),(i=this.videoElement)==null||i.removeAttribute("src"),this.videoElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.clearCanvasAndTracks()}clearCanvasAndTracks(){var t;this.tracks=[],(t=this.canvasContext)==null||t.clearRect(0,0,this.canvas.width,this.canvas.height),clearTimeout(this.timer)}getVideoElement(){if(this.videoElement)return this.videoElement;let t=document.createElement("video");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Qe(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var gi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},vt=class extends He{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:S({},gi.audio),video:S({},gi.video)};this.TAG="[PlaylistManager]";this.handlePausePlaylist=r=>c(this,[r],function*({enabled:t,track:i}){var o;if(t)return;let a;i.source==="audioplaylist"&&(a="audio"),i.source==="videoplaylist"&&(a="video"),a&&((o=this.getElement(a))==null||o.pause())});this.addTrack=(t,i)=>c(this,null,function*(){yield this.sdk.addTrack(t,i),d.d(this.TAG,"Playlist track added",Xt(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),d.d(this.TAG,"Playlist track removed",t)});this.audioManager=new Si,this.videoManager=new mi,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){d.w(this.TAG,"Please pass in a list of HMSPlaylistItem's");return}t.forEach(i=>{this.state[i.type].list.find(r=>r.id===i.id)||this.state[i.type].list.push(i)})}clearList(t){return c(this,null,function*(){this.isPlaying(t)&&(yield this.stop(t)),this.state[t].list=[]})}removeItem(t,i){return c(this,null,function*(){let{list:r,currentIndex:a}=this.state[i],o=r.findIndex(n=>t===n.id);return o>-1?(a===o&&this.isPlaying(i)&&(yield this.stop(i)),r.splice(o,1),!0):!1})}seek(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");let a=this.getElement(i);if(a){let o=Math.max(a.currentTime+t,0);a.currentTime=Math.min(o,a.duration)}}seekTo(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");if(t<0)throw Error("value cannot be negative");let a=this.getElement(i);a&&(a.currentTime=Math.min(t,a.duration))}setVolume(t,i="audio"){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");let r=this.getElement(i);r&&(r.volume=t*.01)}getVolume(t="audio"){let i=this.getElement(t);return i?Math.floor(i.volume*100):0}getCurrentTime(t="audio"){let i=this.getElement(t);return(i==null?void 0:i.currentTime)||0}getCurrentIndex(t="audio"){return this.state[t].currentIndex}getCurrentProgress(t="audio"){var n;let{list:i,currentIndex:r}=this.state[t],a=(n=i[r])==null?void 0:n.url,o=this.getElement(t);return!a||!o?0:Math.floor(100*(o.currentTime/o.duration))}getCurrentSelection(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r!==-1)return i[r]}isPlaying(t="audio"){let i=this.getElement(t);return!!i&&!i.paused}setIsAutoplayOn(t="audio",i){this.state[t].isAutoplayOn=i}getPlaybackRate(t="audio"){let i=this.getElement(t);return i?i.playbackRate:1}setPlaybackRate(t="audio",i){if(i<.25||i>2)throw Error("Please pass a value between 0.25 and 2.0");let r=this.getElement(t);r&&(r.playbackRate=i)}setEnabled(a,o){return c(this,arguments,function*(t,{id:i,type:r="audio"}){let l=this.state[r].list.findIndex(p=>p.id===i);if(!i||l===-1){d.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[l].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=l,this.setDuration(r)})}playNext(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r>=i.length-1)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached end of playlist");yield this.play(i[r+1].url,t),this.state[t].currentIndex=r+1,this.setDuration(t)})}playPrevious(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r<=0)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached start of playlist");yield this.play(i[r-1].url,t),this.state[t].currentIndex=r-1,this.setDuration(t)})}stop(){return c(this,arguments,function*(t="audio"){var r;let i=t==="audio"?this.audioManager:this.videoManager;(r=i.getElement())==null||r.pause(),yield this.removeTracks(t),i.stop(),this.state[t].currentIndex=-1})}cleanup(){this.state={audio:S({},gi.audio),video:S({},gi.video)},this.eventBus.localAudioEnabled.unsubscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.unsubscribe(this.handlePausePlaylist),this.audioManager.stop(),this.videoManager.stop()}onProgress(t){this.videoManager.on("progress",()=>{try{t({type:"video",progress:this.getCurrentProgress("video")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}})}onNewTrackStart(t){this.on("newTrackStart",t)}onPlaylistEnded(t){this.on("playlistEnded",t)}onCurrentTrackEnded(t){this.on("currentTrackEnded",t)}getElement(t="audio"){return t==="audio"?this.audioManager.getElement():this.videoManager.getElement()}removeTracks(){return c(this,arguments,function*(t="audio"){let r=(t==="audio"?this.audioManager:this.videoManager).getTracks();for(let a of r)yield this.removeTrack(a)})}play(r){return c(this,arguments,function*(t,i="audio"){let a=i==="audio"?this.audioManager:this.videoManager,o=a.getElement();if(this.isItemCurrentlyPlaying(t,i)){d.w(this.TAG,`The ${i} is currently playing`);return}if(o!=null&&o.src.includes(t))yield o.play();else{o==null||o.pause();let n=yield a.play(t);for(let l of n)yield this.addTrack(l,i==="audio"?"audioplaylist":"videoplaylist")}})}isItemCurrentlyPlaying(t,i){let r=this.getElement(i);return!!(r&&!r.paused&&r.src.includes(t))}setDuration(t="audio"){let i=this.getElement(t),{list:r,currentIndex:a}=this.state[t];r[a]&&(r[a].duration=(i==null?void 0:i.duration)||0),this.emit("newTrackStart",r[a])}pause(r){return c(this,arguments,function*(t,i="audio"){let a=this.getElement(i);a&&!a.paused&&a.src.includes(t)?(a.pause(),d.d(this.TAG,"paused url",t)):d.w(this.TAG,"The passed in url is not currently playing")})}addListeners(){this.audioManager.on("ended",()=>this.handleEnded("audio")),this.videoManager.on("ended",()=>this.handleEnded("video")),this.eventBus.localAudioEnabled.subscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.subscribe(this.handlePausePlaylist)}handleEnded(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r,isAutoplayOn:a}=this.state[t];r===i.length-1?(yield this.stop(t),this.emit("playlistEnded",t)):a?this.playNext(t):yield this.pause(i[r].url,t),this.emit("currentTrackEnded",i[r])})}};var Mt="HMS-Store:",k=class{static v(e,...t){this.log(0,e,...t)}static d(...e){this.log(1,...e)}static i(...e){this.log(2,...e)}static w(...e){this.log(3,...e)}static e(...e){this.log(6,...e)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,...t){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(Mt,...t);break}case 1:{console.debug(Mt,...t);break}case 2:{console.info(Mt,...t);break}case 3:{console.warn(Mt,...t);break}case 6:{console.error(Mt,...t);break}case 4:{performance.mark(t[1]);break}case 5:{let i=t[0],r=t[1];try{let a=performance.measure(r,r);this.log(1,i,r,a==null?void 0:a.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(a){this.log(1,i,r,a)}break}}}};k.level=0;var Kr=(s,e)=>e,yt=(s,e)=>e,da=(s,e)=>e,on=(s,e)=>e,nn=(s,e)=>e,z=(0,H.createSelector)([F,Kr],(s,e)=>e?s[e]:null),qr=(0,H.createSelector)([D,yt],(s,e)=>e?s[e]:null),cn=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="video"?t:null}),dn=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="audio"?t:null}),ln=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="audio"&&(t==null?void 0:t.source)==="screen"?t:null}),un=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="video"&&(t==null?void 0:t.source)==="screen"?t:null}),pn=(0,H.createSelector)([Tr,nn],(s,e)=>e?s[e]:null),W=A(z),hn=A((0,H.createSelector)([Jt,on],(s,e)=>{if(s)return e?s[e]:s}));function Sn(s){return e=>{if(e.sessionStore)return s?e.sessionStore[s]:e.sessionStore}}var mn=(...s)=>(0,H.createSelector)([Jt],e=>{if(e){if(s&&s.length>0){let t=e;for(let i of s){if(!i)return t;t=t==null?void 0:t[i]}return t}return e}}),gn=A((0,H.createSelector)(z,s=>s==null?void 0:s.name)),kt=A(qr),jr=A(cn),Tn=A(dn),fn=A(ln),vn=A(un),la=A((s,e)=>{let t=z(s,e);if(t&&t.videoTrack&&t.videoTrack!=="")return s.tracks[t.videoTrack]}),ua=A((s,e)=>{let t=z(s,e);if(t&&t.audioTrack&&t.audioTrack!=="")return s.tracks[t.audioTrack]}),Mn=la,yn=A((s,e)=>{let t=z(s,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>s.tracks[i]))||[]}),pa=(s,e)=>e?s.speakers[e]:null,kn=A((0,H.createSelector)(pa,s=>(s==null?void 0:s.audioLevel)||0)),En=(s,e)=>{let t=ua(e)(s);return pa(s,t==null?void 0:t.id)},Pn=A((0,H.createSelector)(En,s=>(s==null?void 0:s.audioLevel)||0)),An=A((s,e)=>{if(e)return s.connectionQualities[e]}),bn=A((s,e)=>{let t=z(s,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>at(s.tracks[r]));return i?s.tracks[i]:void 0}}),Rn=A((0,H.createSelector)(D,z,(s,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=s[i];return nt(r)&&ot(r)});return t?s[t]:void 0})),Hn=A((0,H.createSelector)(D,z,(s,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=s[i];return nt(r)&&at(r)});return t?s[t]:void 0})),In=A((0,H.createSelector)(D,z,(s,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=s[i];return jt(r)&&at(r)});return t?s[t]:void 0})),Jr=A((0,H.createSelector)(D,z,(s,e)=>Ie(s,e))),Cn=s=>(0,H.createSelector)(Jr(s),e=>e.video),Qr=s=>(0,H.createSelector)(Jr(s),e=>e.audio),Ln=A((s,e)=>{let t=z(s,e);return xe(s,t==null?void 0:t.audioTrack)}),Dn=A((s,e)=>{let t=z(s,e);return xe(s,t==null?void 0:t.videoTrack)}),zr=A((s,e)=>{if(e&&s.tracks[e])return s.tracks[e].volume===0}),wn=A((s,e)=>{let t=z(s,e);return zr(t==null?void 0:t.audioTrack)(s)}),_n=A((s,e)=>{let t=Qr(e)(s);return zr(t==null?void 0:t.id)(s)}),Yr=A((s,e)=>{let t=qr(s,e);if(t){if(t.type!=="audio"){k.w("Please pass audio track here");return}return t.volume}}),Nn=A((s,e)=>{let t=z(s,e);return Yr(t==null?void 0:t.audioTrack)(s)}),On=A((s,e)=>{let t=Qr(e)(s);return Yr(t==null?void 0:t.id)(s)}),xn=A((s,e)=>{let t=qr(s,e);if(t){if(t.type!=="video"){k.w("Please pass video track here");return}return t.layer}}),ha=(0,H.createSelector)([Ue,ne,Kr],(s,e,t)=>{if(t)return s.filter(i=>{var r;return!i.recipientPeer&&!((r=i.recipientRoles)!=null&&r.length)||i.sender&&![e,t].includes(i.sender)?!1:[e,t].includes(i.recipientPeer)})}),Sa=(0,H.createSelector)([Ue,da],(s,e)=>{if(e)return s.filter(t=>{var i,r;return(i=t.recipientRoles)!=null&&i.length?(r=t.recipientRoles)==null?void 0:r.includes(e):!1})}),ma=(0,H.createSelector)(Ue,s=>s.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),Un=(0,H.createSelector)([Sa,da],s=>s?s.filter(e=>!e.read).length:0),Vn=(0,H.createSelector)([ha,Kr],s=>s?s.filter(e=>!e.read).length:0),Bn=(0,H.createSelector)(ma,s=>s.filter(e=>!e.read).length),Fn=A(ha),Gn=A(Sa),$n=A(Un),Wn=A(Vn),Kn=s=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName===s)),qn=s=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName?s.includes(t.roleName):!1)),jn=s=>(0,H.createSelector)(W(s),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),Jn=s=>(0,H.createSelector)(W(s),e=>!!(e!=null&&e.isHandRaised)),Qn=s=>(0,H.createSelector)(W(s),e=>e==null?void 0:e.name),Xr=A(pn),zn=s=>(0,H.createSelector)(dt,e=>e[s]);var Et=require("reselect");var Yn=(0,Et.createSelector)([F,D],(s,e)=>Object.values(s).map(i=>{var r;return{peer:i,isAudioEnabled:i.audioTrack?(r=e[i.audioTrack])==null?void 0:r.enabled:!1}})),Xn=s=>s.roleChangeRequests[0]||null,Zn=(0,Et.createSelector)([Xn,F,re],(s,e,t)=>s?{requestedBy:s.requestedBy?e[s.requestedBy]:void 0,role:t[s.roleName],token:s.token}:null),ec=(0,Et.createSelector)([lt],s=>ct(s)),tc=(0,Et.createSelector)([mr],s=>ct(s));var pe=require("reselect");var ga=s=>(0,pe.createSelector)([re],e=>e[s]),ic=s=>(0,pe.createSelector)(ga(s),e=>ct(e)),rc=(0,pe.createSelector)([$,D],(s,e)=>{let t=null;return s&&(t=e[s]),(t==null?void 0:t.plugins)||[]}),sc=(0,pe.createSelector)([Y,D],(s,e)=>{let t=null;return s&&(t=e[s]),(t==null?void 0:t.plugins)||[]}),ac=s=>(0,pe.createSelector)([rc],e=>e.includes(s)),oc=s=>(0,pe.createSelector)([sc],e=>e.includes(s)),nc=s=>(0,pe.createSelector)(ie,e=>e.find(s)),cc=s=>(0,pe.createSelector)(ie,e=>e.filter(s)),dc=s=>(0,pe.createSelector)(x,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=s);var xa=require("immer"),Ua=it(require("zustand/shallow")),Va=it(require("zustand/vanilla"));var Ta=require("eventemitter2");var Ti={0:"PEER_JOINED",1:"PEER_LEFT",8:"ROLE_UPDATED",10:"NAME_UPDATED",11:"METADATA_UPDATED",12:"HAND_RAISE_CHANGED"},Pt={0:"TRACK_ADDED",1:"TRACK_REMOVED",2:"TRACK_MUTED",3:"TRACK_UNMUTED",5:"TRACK_DEGRADED",6:"TRACK_RESTORED",4:"TRACK_DESCRIPTION_CHANGED"},fi={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",3:"POLL_VOTES_UPDATED"};var Zr="hmsNotification",vi=class{constructor(e){this.id=0;this.onNotification=(e,t)=>{let i=r=>{if(t){let a;if(Array.isArray(t)?a=t.includes(r.type):a=t===r.type,!a)return}e(r)};return this.eventEmitter.addListener(Zr,i),()=>{this.eventEmitter.removeListener(Zr,i)}};this.store=e,this.eventEmitter=new Ta.EventEmitter2({maxListeners:Object.keys(qt).length})}sendPlaylistTrackEnded(e){let t=this.createNotification("PLAYLIST_TRACK_ENDED",e,"info");this.emitEvent(t)}sendDeviceChange(e){var i;let t=this.createNotification("DEVICE_CHANGE_UPDATE",e,e.error?"error":"info",`Selected ${e.type} device - ${(i=e.selection)==null?void 0:i.label}`);this.emitEvent(t)}sendLeaveRoom(e){var r;let t=(r=e.requestedBy)==null?void 0:r.name,i=this.createNotification(e.roomEnded||!t?"ROOM_ENDED":"REMOVED_FROM_ROOM",e,"info",`${e.roomEnded?"Room ended":"Removed from room"} ${t?`by ${t}`:""}`);this.emitEvent(i)}sendPeerList(e){if(e.length===0)return;let t=this.createNotification("PEER_LIST",e,"info");this.emitEvent(t)}sendPeerUpdate(e,t){let i=this.store.getState(W(t==null?void 0:t.id))||t,r=Ti[e];if(r&&i){let a=this.createNotification(r,i,"info");this.emitEvent(a)}}sendTrackUpdate(e,t){let i=this.store.getState(kt(t)),r=Pt[e];if(r){let a=this.createNotification(r,i,"info");this.emitEvent(a)}}sendMessageReceived(e){let t=this.createNotification("NEW_MESSAGE",e,"info");this.emitEvent(t)}sendError(e){let t=this.createNotification("ERROR",e,"error");this.emitEvent(t)}sendReconnecting(e){let t=this.createNotification("RECONNECTING",e,"error");this.emitEvent(t)}sendReconnected(){let e=this.createNotification("RECONNECTED",null,"info");this.emitEvent(e)}sendChangeTrackStateRequest(e){let t=this.createNotification("CHANGE_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendChangeMultiTrackStateRequest(e){let t=this.createNotification("CHANGE_MULTI_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendPollUpdate(e,t){let i=fi[e],r=this.store.getState(Xr(t));if(i){let a=this.createNotification(i,r,"info");this.emitEvent(a)}}emitEvent(e){this.eventEmitter.emit(Zr,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var Mi=class{constructor(e){this.queuedUpdates={};this.timers={};this.DEFAULT_INTERVAL_MS=50;this.store=e}setState(e,t,i=this.DEFAULT_INTERVAL_MS){this.queuedUpdates[t]=this.queuedUpdates[t]||[],this.queuedUpdates[t].push(e),!this.timers[t]&&(window?this.timers[t]=window.setTimeout(()=>this.setStateBatched(t),i):this.setStateBatched(t))}setStateBatched(e){var t;if(((t=this.queuedUpdates[e])==null?void 0:t.length)>0){let i=r=>{this.queuedUpdates[e].forEach(a=>{try{a(r)}catch(o){k.w("failed to update store",o)}})};console.time(`timed-${e}`),this.store.namedSetState(i,e),console.timeEnd(`timed-${e}`)}delete this.queuedUpdates[e],window&&this.timers[e]&&(window.clearTimeout(this.timers[e]),delete this.timers[e])}};function fa(s){return s instanceof te||s instanceof _}var va=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?(Z(r.auxiliaryTracks,a.auxiliaryTracks)&&(a.auxiliaryTracks=r.auxiliaryTracks),r.groups&&Z(r.groups,a.groups)&&(a.groups=r.groups),Object.assign(r,a)):is(r,a)?delete s[i]:yi(r,a)&&(s[i]=a)}},Ma=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?(ts(r,a),Object.assign(r,a)):is(r,a)?delete s[i]:yi(r,a)&&(s[i]=a)}},ya=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?(r.questions&&Z(r.questions,a.questions)&&(a.questions=r.questions),Object.assign(r,a)):yi(r,a)&&(s[i]=a)}},es=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?Object.assign(r,a):is(r,a)?delete s[i]:yi(r,a)&&(s[i]=a)}},ka=(s,e,t)=>{let i=t.reduce((a,o)=>(a[o.firstTrackId]=Object.values(e[o.getTrackIDBeingSent()]||{}).sort((n,l)=>!n.rid||!l.rid?0:n.rid<l.rid?-1:1),a),{}),r=At(Object.keys(s),Object.keys(i));for(let a of r){if(!i[a]){delete s[a];continue}s[a]=i[a]}},ts=(s,e)=>{s.plugins&&Z(s.plugins,e.plugins)&&(e.plugins=s.plugins),s.type==="video"&&s.layerDefinitions&&Z(s.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=s.layerDefinitions)},_e=(s,e)=>s&&e,is=(s,e)=>s&&!e,yi=(s,e)=>!s&&e,Z=(s,e)=>{if(s===e||s.length===0&&(e==null?void 0:e.length)===0)return!0;if(!s||!e||s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]!==e[t])return!1;return!0},At=(s,e)=>{let t=new Set;for(let i of s)t.add(i);for(let i of e)t.add(i);return Array.from(t)};var w=class s{static convertPeer(e){var t,i,r;return{id:e.peerId,name:e.name,roleName:(t=e.role)==null?void 0:t.name,isLocal:e.isLocal,videoTrack:(i=e.videoTrack)==null?void 0:i.trackId,audioTrack:(r=e.audioTrack)==null?void 0:r.trackId,auxiliaryTracks:e.auxiliaryTracks.map(a=>a.trackId),customerUserId:e.customerUserId,metadata:e.metadata,joinedAt:e.joinedAt,groups:e.groups,isHandRaised:e.isHandRaised}}static convertTrack(e,t){let i={id:e.trackId,source:e.source,type:e.type,enabled:e.enabled,displayEnabled:e.enabled,peerId:e.peerId||t};return this.enrichTrack(i,e),i}static enrichTrack(e,t){let i=t.getMediaTrackSettings();t instanceof te&&(e.volume=t.getVolume()||0),s.updateDeviceID(e,t),s.enrichLocalTrack(e,t),e.type==="video"&&(e.source==="screen"?(e.displaySurface=i.displaySurface,s.enrichScreenTrack(e,t)):e.source==="regular"&&(e.facingMode=i.facingMode),e.height=i.height,e.width=i.width,s.enrichVideoTrack(e,t)),s.enrichPluginsDetails(e,t)}static enrichLocalTrack(e,t){(t instanceof U||t instanceof oe)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof U||t instanceof oe?e.deviceID=t.settings.deviceId:e.deviceID=(i=t.getMediaTrackSettings())==null?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof _&&(e.layer=t.getLayer(),e.preferredLayer=t.getPreferredLayer(),e.degraded=t.degraded),(t instanceof _||t instanceof U)&&(Z(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof U){let a=(i=t.getCaptureHandle)==null?void 0:i.call(t);(a==null?void 0:a.handle)!==((r=e.captureHandle)==null?void 0:r.handle)&&(e.captureHandle=a),t.isCurrentTab&&(e.displaySurface="selfBrowser")}}static enrichPluginsDetails(e,t){(t instanceof U||t instanceof oe)&&(Z(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:a}=s.convertRecordingStreamingState(e==null?void 0:e.recording,e==null?void 0:e.rtmp,e==null?void 0:e.hls);return{id:e.id,name:e.name,localPeer:t,recording:i,rtmp:r,hls:a,sessionId:e.sessionId,startedAt:e.startedAt,joinedAt:e.joinedAt,peerCount:e.peerCount,isLargeRoom:e.large_room_optimization,isEffectsEnabled:e.isEffectsEnabled,effectsKey:e.effectsKey}}static convertMessage(e,t){var i,r,a,o;return{sender:(i=e.peer)==null?void 0:i.peer_id,senderName:(r=e.peer)==null?void 0:r.info.name,senderRole:(a=e.peer)==null?void 0:a.role,senderUserId:(o=e.peer)==null?void 0:o.info.user_id,recipientPeer:e.private?t:void 0,recipientRoles:e.roles,time:new Date(e.timestamp),type:e.info.type,message:e.info.message,id:e.message_id}}static convertRoles(e){let t={};return e&&e.forEach(i=>{t[i.name]=i}),t}static convertRoleChangeRequest(e){var t;return{requestedBy:(t=e.requestedBy)==null?void 0:t.peerId,roleName:e.role.name,token:e.token}}static convertException(e){return{code:e.code,action:e.action,name:e.name,message:e.message,description:e.description,isTerminal:e.isTerminal,nativeError:e.nativeError,timestamp:new Date}}static convertDeviceChangeUpdate(e){let t={devices:e.devices,selection:e.selection,type:e.type};return e.error&&(t.error=this.convertException(e.error)),t}static convertPlaylist(e){let t=this.getConvertedPlaylistType(e,"audio"),i=this.getConvertedPlaylistType(e,"video");return{audio:t,video:i}}static convertPlaylistItem(e,t){let i=t.type,r=e.getCurrentSelection(i),a=e.isPlaying(i),o=t.url===(r==null?void 0:r.url);return y(S({},t),{type:t.type,selected:o,playing:o&&a})}static getConvertedPlaylistType(e,t){let i={},r=e.getCurrentSelection(t),a=e.getCurrentProgress(t),o=e.getVolume(t),n=e.getList(t),l=e.getCurrentIndex(t);return e.getList(t).forEach(u=>{i[u.id]=s.convertPlaylistItem(e,u)}),{list:i,selection:{id:r==null?void 0:r.id,hasPrevious:l>0,hasNext:l<n.length-1},progress:a,volume:o,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i){var r;return{recording:{browser:S({running:!1},e==null?void 0:e.browser),server:S({running:!1},e==null?void 0:e.server),hls:S({running:!1},e==null?void 0:e.hls)},rtmp:S({running:!1},t),hls:{variants:((r=i==null?void 0:i.variants)==null?void 0:r.map(a=>a))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error}}}};var bt=class{constructor(e,t,i,r){this.playlistManager=e;this.syncPlaylistState=i;this.store=r;this.type=t}play(e){return c(this,null,function*(){if(!e){k.w("Please pass id to play");return}yield this.playlistManager.setEnabled(!0,{id:e,type:this.type})})}pause(){return c(this,null,function*(){let e=this.type==="audio"?Mr:yr,t=this.store.getState(e.selection);if(!t.id){k.w("No item is currently playing to pause");return}yield this.playlistManager.setEnabled(!1,{id:t.id,type:this.type})})}playNext(){return c(this,null,function*(){yield this.playlistManager.playNext(this.type)})}playPrevious(){return c(this,null,function*(){yield this.playlistManager.playPrevious(this.type)})}seek(e){this.playlistManager.seek(e,this.type),this.syncPlaylistState(`seekOn${this.type}Playlist`)}seekTo(e){this.playlistManager.seekTo(e,this.type),this.syncPlaylistState(`seekToOn${this.type}Playlist`)}setVolume(e){this.playlistManager.setVolume(e,this.type),this.syncPlaylistState(`setVolumeOn${this.type}Playlist`)}setList(e){this.playlistManager.setList(e),this.syncPlaylistState(`setListOn${this.type}Playlist`)}stop(){return c(this,null,function*(){yield this.playlistManager.stop(this.type),this.syncPlaylistState(`stop${this.type}Playlist`)})}setIsAutoplayOn(e){this.playlistManager.setIsAutoplayOn(this.type,e)}setPlaybackRate(e){this.playlistManager.setPlaybackRate(this.type,e),this.syncPlaylistState(`set${this.type}PlaybackRate`)}removeItem(e){return c(this,null,function*(){let t=yield this.playlistManager.removeItem(e,this.type);return t&&this.syncPlaylistState(`remove${this.type}PlaylistItem`),t})}clearList(){return c(this,null,function*(){yield this.playlistManager.clearList(this.type),this.syncPlaylistState(`clear${this.type}Playlist`)})}};var ki=class{constructor(e,t){this.sdk=e;this.setLocally=t}get sdkSessionStore(){return this.sdk.getSessionStore()}set(e,t){return c(this,null,function*(){let{value:i}=yield this.sdkSessionStore.set(String(e),t);this.setLocally({key:e,value:i})})}observe(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.observe(t)})}unobserve(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.unobserve(t)})}};var Ei=class{constructor(e,t){this.intervalMs=100,this.shouldMonitor=!1,this.hasStarted=!1,this.unsubs=[],this.analysers={},this.store=e,this.actions=t}start(){return c(this,null,function*(){if(this.hasStarted)return;this.hasStarted=!0,k.d("starting audio level monitor for remote peers",this.store);let e=this.store.getState(he);k.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),he);this.unsubs.push(t)})}stop(){return c(this,null,function*(){this.hasStarted&&(this.hasStarted=!1,this.shouldMonitor=!1,this.unsubs.forEach(e=>e()),k.d("stopped audio level monitor for remote peers"))})}monitorAudioLevels(){return c(this,null,function*(){if(!this.store.getState(he)){this.shouldMonitor&&(k.i("room no longer connected, stopping audio level monitoring for remote"),this.shouldMonitor=!1);return}if(this.shouldMonitor)return;k.i("monitoring audio levels"),this.shouldMonitor=!0;let t=()=>{this.shouldMonitor?(this.logAllPeersAudioLevels(),setTimeout(t,this.intervalMs)):k.i("stopped monitoring audio levels")};setTimeout(t,1e3)})}logAllPeersAudioLevels(){return c(this,null,function*(){var r;if(!window.__triggerBeamEvent__)return;let t=this.store.getState(ie).filter(a=>!!a.audioTrack),i=[];for(let a of t){let o=this.actions.hmsSDKTracks[a.audioTrack],n=(r=o==null?void 0:o.stream)==null?void 0:r.nativeStream;if(a.joinedAt&&n){let l=yield this.getAudioLevel(a,n);l.level>0&&i.push(l)}}if(i.length>0){let a={event:"app-audio-level",data:i};window.__triggerBeamEvent__(JSON.stringify(a))}})}getAudioLevel(e,t){return c(this,null,function*(){this.analysers[t.id]||(this.analysers[t.id]=this.createAnalyserNode(t));let i=this.analysers[t.id],r=this.calculateAudioLevel(i);return{peerId:e.id,peerName:e.name,level:r}})}createAnalyserNode(e){this.audioContext||(this.audioContext=new AudioContext);let t=this.audioContext.createAnalyser();return this.audioContext.createMediaStreamSource(e).connect(t),t}calculateAudioLevel(e){let t=new Uint8Array(e.fftSize);e.getByteTimeDomainData(t);let i=.009,r=i;for(let n of t)r=Math.max(r,(n-128)/128);let a=(Math.log(i)-Math.log(r))/Math.log(i);return Math.ceil(Math.min(Math.max(a*100,0),100))}};var Pi=class{constructor(e,t,i){this.isRoomJoinCalled=!1;this.ignoredMessageTypes=[];this.setProgress=({type:e,progress:t})=>{this.setState(i=>{i.playlist[e].progress=t,i.playlist[e].currentTime=this.sdk.getPlaylistManager().getCurrentTime(e)},"playlistProgress")};this.syncPlaylistState=e=>{this.setState(t=>{Object.assign(t.playlist,w.convertPlaylist(this.sdk.getPlaylistManager()))},e)};this.sendPeerUpdateNotification=(e,t)=>{let i=this.store.getState(W(t.peerId)),r=Ti[e]||"peerUpdate";if(e===8)this.syncRoomState(r),this.updateMidCallPreviewRoomState(e,t);else if([0,1].includes(e))this.syncRoomState(r),i||(i=this.store.getState(W(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState(W(t.peerId)));else{let a=w.convertPeer(t);this.setState(o=>{let n=o.peers[a.id];_e(n,a)&&(Z(n.auxiliaryTracks,a.auxiliaryTracks)&&(n.auxiliaryTracks=a.auxiliaryTracks),Object.assign(n,a)),i=a},r)}this.hmsNotifications.sendPeerUpdate(e,i)};this.getSDKHMSPeer=e=>this.sdk.getPeerMap()[e];this.setState=(e,t)=>this.store.namedSetState(e,t);this.store=e,this.sdk=t,this.hmsNotifications=i,this.sessionStore=new ki(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new Mi(e)}getLocalTrack(e){return this.sdk.store.getLocalPeerTracks().find(t=>t.trackId===e)}get interactivityCenter(){return this.sdk.getInteractivityCenter()}setPlaylistSettings(e){this.sdk.updatePlaylistSettings(e)}refreshDevices(){return c(this,null,function*(){yield this.sdk.refreshDevices()})}unblockAudio(){return c(this,null,function*(){yield this.sdk.getAudioOutput().unblockAutoplay()})}setVolume(e,t){return c(this,null,function*(){t?yield this.setTrackVolume(e,t):(yield this.sdk.getAudioOutput().setVolume(e),this.syncRoomState("setOutputVolume"))})}setAudioOutputDevice(e){return c(this,null,function*(){(yield this.sdk.getAudioOutput().setDevice(e))&&this.setState(i=>{i.settings.audioOutputDeviceId=e},"setAudioOutputDevice")})}setPreferredLayer(e,t){return c(this,null,function*(){var r;let i=this.sdk.store.getTrackById(e);if(i)if(i instanceof _){if(t==="none"){k.d("layer none will be ignored");return}if(((r=this.store.getState(jr(e)))==null?void 0:r.preferredLayer)===t){k.d(`preferred layer is already ${t}`);return}this.setState(o=>{let n=o.tracks[e];n&&(n.preferredLayer=t)},"setPreferredLayer"),yield i.setPreferredLayer(t)}else k.d(`track ${e} is not a remote video track`);else this.logPossibleInconsistency(`track ${e} not present, unable to set preffer layer`)})}getAuthTokenByRoomCode(e,t){return this.sdk.getAuthTokenByRoomCode(e,t)}preview(e){return c(this,null,function*(){let t=this.store.getState(J);if(t==="Preview"||t==="Connecting"){this.logPossibleInconsistency("attempting to call preview while room is in preview/connecting");return}try{t!=="Connected"&&this.setState(i=>{i.room.roomState="Connecting"},"connecting"),yield this.sdkPreviewWithListeners(e)}catch(i){throw k.e("Cannot show preview. Failed to connect to room - ",i),i}})}cancelMidCallPreview(){return c(this,null,function*(){return this.sdk.cancelMidCallPreview()})}join(e){return c(this,null,function*(){if(this.isRoomJoinCalled){this.logPossibleInconsistency("room join is called again");return}try{this.isRoomJoinCalled=!0,this.setState(t=>{t.room.roomState="Connecting"},"join"),yield this.sdkJoinWithListeners(e)}catch(t){throw this.isRoomJoinCalled=!1,k.e("Failed to connect to room - ",t),t}})}leave(){return c(this,null,function*(){let e=this.store.getState(he),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(J);return this.setState(r=>{r.room.roomState="Disconnecting"},"leaving"),this.sdk.leave(t).then(()=>{this.resetState("leave"),this.beamSpeakerLabelsLogger&&this.beamSpeakerLabelsLogger.stop().catch(k.e),k.i("left room")}).catch(r=>{k.e("error in leaving room - ",r),this.setState(a=>{a.room.roomState=i},"revertLeave")})})}setScreenShareEnabled(e,t){return c(this,null,function*(){typeof t=="boolean"&&(t={audioOnly:t});try{e?yield this.startScreenShare(t):yield this.stopScreenShare()}catch(i){throw this.hmsNotifications.sendError(w.convertException(i)),i}})}addTrack(e,t="regular"){return c(this,null,function*(){yield this.sdk.addTrack(e,t),this.syncRoomState("addTrack")})}removeTrack(e){return c(this,null,function*(){yield this.sdk.removeTrack(e),this.syncRoomState("removeTrack")})}setLocalAudioEnabled(e){return c(this,null,function*(){let t=this.store.getState(Y);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState($);t&&(yield this.setEnabledTrack(t,e))})}setEnabledTrack(e,t){return c(this,null,function*(){var a;if(((a=this.store.getState().tracks[e])==null?void 0:a.enabled)===t){this.logPossibleInconsistency(`local track[${e}] enabled state - ${t}`);return}this.setState(o=>{o.tracks[e]?o.tracks[e].displayEnabled=t:this.logPossibleInconsistency("track id not found for setEnabled")},"displayEnabled");try{yield this.setEnabledSDKTrack(e,t),this.syncRoomState("setEnabled")}catch(o){throw this.setState(n=>{n.tracks[e].displayEnabled=!t},"rollbackDisplayEnabled"),this.hmsNotifications.sendError(w.convertException(o)),o}let r=t?3:2;this.hmsNotifications.sendTrackUpdate(r,e)})}setAudioSettings(e){return c(this,null,function*(){let t=this.store.getState(Y);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState($);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState($);if(e){let t=this.sdk.store.getLocalPeerTracks().find(i=>i.trackId===e);t&&(yield t.switchCamera(),this.syncRoomState("switchCamera"))}})}sendMessage(e){this.sendBroadcastMessage(e)}sendBroadcastMessage(e,t){return c(this,null,function*(){let{message_id:i,timestamp:r}=yield this.sdk.sendBroadcastMessage(e,t);this.updateMessageInStore({message:e,type:t,id:i,time:r})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getState(re),a=t.map(l=>r[l]),{message_id:o,timestamp:n}=yield this.sdk.sendGroupMessage(e,a,i);this.updateMessageInStore({message:e,recipientRoles:t,type:i,id:o,time:n})})}sendDirectMessage(e,t,i){return c(this,null,function*(){let{message_id:r,timestamp:a}=yield this.sdk.sendDirectMessage(e,t,i);this.updateMessageInStore({message:e,recipientPeer:t,type:i,id:r,time:a})})}updateMessageInStore(e){var r;if(!e.message)throw k.w("sendMessage","Failed to send message",e),Error(`sendMessage Failed - ${JSON.stringify(e)}`);let t=this.sdk.getLocalPeer(),i={read:!0,id:e.id,time:new Date(e.time),message:e.message,type:e.type||"chat",recipientPeer:e.recipientPeer,recipientRoles:e.recipientRoles,senderName:t==null?void 0:t.name,sender:t==null?void 0:t.peerId,senderRole:(r=t==null?void 0:t.role)==null?void 0:r.name,ignored:!!e.type&&this.ignoredMessageTypes.includes(e.type)};this.putMessageInStore(i)}setMessageRead(e,t){this.setState(i=>{t?i.messages.byID[t]?i.messages.byID[t].read=e:this.logPossibleInconsistency("no message with id is found"):i.messages.allIDs.forEach(r=>{i.messages.byID[r].read=e})},"setMessageRead")}attachVideo(e,t){return c(this,null,function*(){if(this.localAndVideoUnmuting(e))return new Promise(i=>{let r=this.store.subscribe(a=>c(this,null,function*(){a&&(yield this.attachVideoInternal(e,t),r(),i())}),Qt)});yield this.attachVideoInternal(e,t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.sdk.store.getTrackById(e);(i==null?void 0:i.type)==="video"?yield this.sdk.detachVideo(i,t):(t&&(t.srcObject=null),k.d("possible inconsistency detected - no video track found to remove sink"))})}addPluginToVideoTrack(e,t){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"add",t)})}addPluginsToVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"add")})}removePluginsFromVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"remove")})}addPluginToAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"add")})}validateVideoPluginSupport(e){let t={};if(t.isSupported=!1,!e)return k.w("no plugin passed in for checking support"),t.errMsg="no plugin passed in for checking support",t;let i=this.store.getState($);if(!i)return k.w("video Track not added to local peer yet"),t.errMsg="call this function only after local peer has video track",t;let r=this.sdk.store.getTrackById(i);return r?t=r.validatePlugin(e):(k.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}validateAudioPluginSupport(e){let t={};if(t.isSupported=!1,!e)return k.w('no plugin passed in for checking support"'),t.errMsg='no plugin passed in for checking support"',t;let i=this.store.getState(Y);if(!i)return k.w("audio track not added to local peer yet"),t.errMsg="call this function only after local peer has audio track",t;let r=this.sdk.store.getTrackById(i);return r?t=r.validatePlugin(e):(k.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}removePluginFromVideoTrack(e){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"remove")})}removePluginFromAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"remove")})}changeRole(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){let i=this.sdk.getRoles().filter(r=>e.includes(r.name));yield this.sdk.changeRoleOfPeersWithRoles(i,t)})}acceptChangeRole(e){return c(this,null,function*(){let t=e.requestedBy?this.getSDKHMSPeer(e.requestedBy.id):void 0;t||k.w(`peer for which role change is requested no longer available - ${e.requestedBy}`);let i={requestedBy:t,role:e.role,token:e.token};yield this.sdk.acceptChangeRole(i),this.removeRoleChangeRequest(e)})}raiseLocalPeerHand(){return c(this,null,function*(){yield this.sdk.raiseLocalPeerHand()})}lowerLocalPeerHand(){return c(this,null,function*(){yield this.sdk.lowerLocalPeerHand()})}raiseRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.raiseRemotePeerHand(e)})}lowerRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.lowerRemotePeerHand(e)})}getPeerListIterator(e){let t=this.sdk.getPeerListIterator(e);return{hasNext:()=>t.hasNext(),next:()=>c(this,null,function*(){return(yield t.next()).map(r=>w.convertPeer(r))}),findPeers:()=>c(this,null,function*(){return(yield t.findPeers()).map(r=>w.convertPeer(r))}),getTotal:()=>t.getTotal()}}initAppData(e){this.setState(t=>{t.appData=e},"initAppData")}setAppData(e,t,i){let r=(t==null?void 0:t.constructor.name)==="Object";this.setState(a=>{if(a.appData)i&&r?Object.assign(a.appData[e],t):a.appData[e]=t;else{let o={[e]:t};a.appData=o}},`setAppData-${e}`)}rejectChangeRole(e){this.removeRoleChangeRequest(e)}endRoom(e,t){return c(this,null,function*(){let i=this.store.getState(gr);if(!(i!=null&&i.endRoom)){k.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(J);this.setState(a=>{a.room.roomState="Disconnecting"},"endingRoom");try{yield this.sdk.endRoom(e,t),this.resetState("endRoom")}catch(a){k.e("error in ending room - ",a),this.setState(o=>{o.room.roomState=r},"revertEndRoom")}})}removePeer(e,t){return c(this,null,function*(){var r;let i=(r=this.sdk.getLocalPeer())==null?void 0:r.peerId;e!==i&&(yield this.sdk.removePeer(e,t))})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.sdk.startRTMPOrRecording(e)})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.sdk.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){yield this.sdk.startHLSStreaming(e)})}stopHLSStreaming(e){return c(this,null,function*(){yield this.sdk.stopHLSStreaming(e)})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.sdk.sendHLSTimedMetadata(e)})}changeName(e){return c(this,null,function*(){yield this.sdk.changeName(e)})}changeMetadata(e){return c(this,null,function*(){typeof e!="string"&&(e=JSON.stringify(e)),yield this.sdk.changeMetadata(e)})}setSessionMetadata(e){return c(this,null,function*(){yield this.sdk.setSessionMetadata(e),this.setState(t=>{t.sessionMetadata=e},"setSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"setSessionMetadata")})}populateSessionMetadata(){return c(this,null,function*(){let e=yield this.sdk.getSessionMetadata();this.setState(t=>{t.sessionMetadata=e},"populateSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"populateSessionmetadata")})}setRemoteTrackEnabled(e,t){return c(this,null,function*(){if(typeof e=="string"){let i=this.sdk.store.getTrackById(e);i&&fa(i)?yield this.sdk.changeTrackState(i,t):this.logPossibleInconsistency(`No remote track with ID ${e} found for change track state`)}else Array.isArray(e)&&e.forEach(i=>this.setRemoteTrackEnabled(i,t))})}setRemoteTracksEnabled(e){return c(this,null,function*(){let t={enabled:e.enabled,type:e.type,source:e.source};if(e.roles){let i=this.store.getState(re);t.roles=e.roles.map(r=>i[r])}yield this.sdk.changeMultiTrackState(t)})}setLogLevel(e){k.level=e,this.sdk.setLogLevel(e)}setFrameworkInfo(e){this.sdk.setFrameworkInfo(e)}ignoreMessageTypes(e,t=!1){if(t)this.ignoredMessageTypes=e;else for(let i of e)this.ignoredMessageTypes.includes(i)||this.ignoredMessageTypes.push(i)}enableBeamSpeakerLabelsLogging(){return c(this,null,function*(){this.beamSpeakerLabelsLogger||(k.i("enabling beam speaker labels logging"),this.beamSpeakerLabelsLogger=new Ei(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}resetState(e="resetState"){this.isRoomJoinCalled=!1,k.cleanup(),this.setState(t=>{Object.assign(t,rt())},e)}sdkJoinWithListeners(e){return c(this,null,function*(){yield this.sdk.join(e,{onJoin:this.onJoin.bind(this),onPreview:this.onPreview.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this),onMessageReceived:this.onMessageReceived.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onRoleChangeRequest:this.onRoleChangeRequest.bind(this),onRoleUpdate:this.onRoleUpdate.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onChangeTrackStateRequest:this.onChangeTrackStateRequest.bind(this),onChangeMultiTrackStateRequest:this.onChangeMultiTrackStateRequest.bind(this),onRemovedFromRoom:this.onRemovedFromRoom.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onSessionStoreUpdate:this.onSessionStoreUpdate.bind(this),onPollsUpdate:this.onPollsUpdate.bind(this),onWhiteboardUpdate:this.onWhiteboardUpdate.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)})})}onRemovedFromRoom(e){var r;let t=this.store.getState(W((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(y(S({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";k.i(`resetting state after peer removed ${i}`,e),this.resetState(i)}onDeviceChange(e){let t=e.devices;if(!t)return;let i=this.store.getState(j);if(this.setState(r=>{Z(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),Z(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),Z(r.devices.audioOutput,t.audioOutput)||(r.devices.audioOutput=t.audioOutput);let a=this.sdk.getLocalPeer();i!=null&&i.id&&a&&Object.assign(r.settings,this.getMediaSettings(a))},"deviceChange"),e.selection){let r=w.convertDeviceChangeUpdate(e);this.hmsNotifications.sendDeviceChange(r)}}sdkPreviewWithListeners(e){return c(this,null,function*(){yield this.sdk.preview(e,{onPreview:this.onPreview.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)})})}onNetworkQuality(e){this.setState(t=>{var r;let i=t.room.localPeer||((r=this.sdk.getLocalPeer())==null?void 0:r.peerId);i&&(t.connectionQualities[i]={peerID:i,downlinkQuality:e})},"ConnectionQuality")}onSessionStoreUpdate(e){this.setSessionStoreValueLocally(e,"sessionStoreUpdate")}onPollsUpdate(e,t){let i=fi[e];this.setState(r=>{let a=t.reduce((o,n)=>{var l;return o[n.id]=y(S({},n),{questions:(l=n.questions)==null?void 0:l.map(u=>{var p,m;return y(S({},u),{answer:u.answer?S({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(g=>S({},g)),responses:(m=u.responses)==null?void 0:m.map(g=>S({},g))})})}),o},{});ya(r.polls,a)},i),t.forEach(r=>this.hmsNotifications.sendPollUpdate(e,r.id))}onWhiteboardUpdate(e){this.setState(t=>{t.whiteboards[e.id]=e},"whiteboardUpdate")}startScreenShare(e){return c(this,null,function*(){this.store.getState(zt)?this.logPossibleInconsistency("start screenshare is called while it's on"):(yield this.sdk.startScreenShare(()=>this.syncRoomState("screenshareStopped"),e),this.syncRoomState("startScreenShare"))})}stopScreenShare(){return c(this,null,function*(){this.store.getState(zt)?(yield this.sdk.stopScreenShare(),this.syncRoomState("stopScreenShare")):this.logPossibleInconsistency("stop screenshare is called while it's not on")})}attachVideoInternal(e,t){return c(this,null,function*(){let i=this.sdk.store.getTrackById(e);i||(i=this.getLocalTrack(e)),i&&i.type==="video"?yield this.sdk.attachVideo(i,t):this.logPossibleInconsistency("no video track found to add sink")})}syncRoomState(e){e=`${e}_fullSync`,k.time(`store-sync-${e}`);let t={},i=[],r={},a={},o={},n,l=this.sdk.getPeers();for(let g of l){let f=w.convertPeer(g);t[f.id]=f,i.push(f.id),o[f.id]={peerID:f.id,downlinkQuality:g.networkQuality||-1};let R=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let b of R){if(!b)continue;let G=w.convertTrack(b);r[G.id]=G}if(g.isLocal){let b=g;n=this.getPreviewFields(b),Object.assign(a,this.getMediaSettings(b))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),m=this.sdk.getHLSState();this.setState(g=>{var b;g.room.peers=i;let f=g.peers,R=g.tracks;va(f,t),Ma(R,r),Object.assign(g.settings,a),Object.assign(g.connectionQualities,o),(b=g.preview)!=null&&b.localPeer&&(n!=null&&n.localPeer)?Object.assign(g.preview,n):g.preview=n,Object.assign(g.roles,w.convertRoles(this.sdk.getRoles())),Object.assign(g.playlist,w.convertPlaylist(this.sdk.getPlaylistManager())),Object.assign(g.room,w.convertRecordingStreamingState(u,p,m)),Object.assign(g.templateAppData,this.sdk.getTemplateAppData())},e),k.timeEnd(`store-sync-${e}`)}onPreview(e){this.setState(t=>{var i;Object.assign(t.room,w.convertRoom(e,(i=this.sdk.getLocalPeer())==null?void 0:i.peerId)),t.room.roomState="Preview"},"previewStart"),this.syncRoomState("previewSync")}onJoin(e){let t=this.sdk.getPlaylistManager();this.audioPlaylist=new bt(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new bt(t,"video",this.syncRoomState.bind(this),this.store),this.syncRoomState("joinSync"),this.setState(i=>{var r;Object.assign(i.room,w.convertRoom(e,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId)),i.room.isConnected=!0,i.room.roomState="Connected"},"joined"),t.onProgress(this.setProgress),t.onNewTrackStart(i=>{this.syncPlaylistState(`${i.type}PlaylistUpdate`)}),t.onPlaylistEnded(i=>{this.syncPlaylistState(`${i}PlaylistEnded`)}),t.onCurrentTrackEnded(i=>{this.hmsNotifications.sendPlaylistTrackEnded(w.convertPlaylistItem(t,i)),this.syncPlaylistState(`${i.type}PlaylistItemEnded`)})}onRoomUpdate(e,t){this.setState(i=>{var r;Object.assign(i.room,w.convertRoom(t,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId))},e)}onPeerUpdate(e,t){if(![4,5].includes(e)){if(Array.isArray(t)){let i=this.store.getState(F),r=t.filter(o=>!i[o.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(he)){let o=[];for(let n of t){let l=this.store.getState(W(n.peerId));l&&o.push(l)}this.hmsNotifications.sendPeerList(o)}else r.forEach(o=>{let n=this.store.getState(W(o.peerId));n&&this.hmsNotifications.sendPeerUpdate(0,n)});return}this.sendPeerUpdateNotification(e,t)}}onTrackUpdate(e,t,i){if(e===1)this.hmsNotifications.sendTrackUpdate(e,t.trackId),this.handleTrackRemove(t,i);else if([0,1].includes(e)){let r=Pt[e];this.syncRoomState(r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}else{let r=Pt[e]||"trackUpdate",a=w.convertTrack(t);this.setState(o=>{let n=o.tracks[a.id];_e(n,a)&&(ts(n,a),Object.assign(n,a))},r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=w.convertMessage(e,this.store.getState(ne));t.read=!1,t.ignored=this.ignoredMessageTypes.includes(t.type),this.putMessageInStore(t),this.hmsNotifications.sendMessageReceived(t)}putMessageInStore(e){e.ignored||this.actionBatcher.setState(t=>{t.messages.byID[e.id]=e,t.messages.allIDs.push(e.id)},"newMessage",150)}onAudioLevelUpdate(e){this.setState(t=>{let i={};e.forEach(a=>{if(!a.track||!a.peer)return;let o=a.track.trackId;i[o]=a.audioLevel,t.speakers[o]||(t.speakers[o]={audioLevel:a.audioLevel,peerID:a.peer.peerId,trackID:o})});let r=Object.entries(t.speakers);for(let[a,o]of r)o.audioLevel=i[a]||0,o.audioLevel===0&&delete t.speakers[a]},"audioLevel")}onConnectionQualityUpdate(e){this.setState(t=>{e.forEach(i=>{let r=i.peerID;r&&(t.connectionQualities[r]?Object.assign(t.connectionQualities[r],i):t.connectionQualities[r]=i)})},"connectionQuality")}onChangeTrackStateRequest(e){var a;let t=this.store.getState(W((a=e.requestedBy)==null?void 0:a.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState(kt(i));if(!r)return this.logPossibleInconsistency(`Not found track for which track state change was requested, ${e.track}`);e.enabled||this.syncRoomState("changeTrackStateRequest"),this.hmsNotifications.sendChangeTrackStateRequest({requestedBy:t||void 0,track:r,enabled:e.enabled})}onChangeMultiTrackStateRequest(e){var a;let t=this.store.getState(W((a=e.requestedBy)==null?void 0:a.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(D);for(let o of e.tracks){let n=this.getStoreLocalTrackIDfromSDKTrack(o);n&&r[n]&&i.push(r[n])}this.hmsNotifications.sendChangeMultiTrackStateRequest({requestedBy:t||void 0,tracks:i,enabled:e.enabled,type:e.type,source:e.source})}onReconnected(){this.syncRoomState("reconnectedSync"),this.hmsNotifications.sendReconnected(),this.setState(e=>{e.room.roomState=e.room.isConnected?"Connected":"Preview"},"reconnected")}onReconnecting(e){let t=w.convertException(e);k.e("Reconnection: received error from sdk",t),this.hmsNotifications.sendReconnecting(t),this.setState(i=>{i.room.roomState="Reconnecting",i.errors.push(t)},"reconnecting")}onError(e){let t=w.convertException(e);t.isTerminal?(this.leave().then(()=>k.e("error from SDK, left room.")),this.setState(i=>{i.room.roomState="Failed",i.errors.push(t)},"errorTerminal")):this.store.getState().errors.length<50&&this.setState(r=>{r.errors.push(t)},"error"),this.syncRoomState("errorSync"),this.hmsNotifications.sendError(t),k.e("received error from sdk",t instanceof T?`${t}`:t)}handleTrackRemove(e,t){this.setState(i=>{let r=i.peers[t.peerId],a=i.tracks,o=e.trackId;if(this.isSameStoreSDKTrack(o,r==null?void 0:r.audioTrack))r==null||delete r.audioTrack;else if(this.isSameStoreSDKTrack(o,r==null?void 0:r.videoTrack))r==null||delete r.videoTrack;else{let n=r==null?void 0:r.auxiliaryTracks.indexOf(o);n>-1&&this.isSameStoreSDKTrack(o,r==null?void 0:r.auxiliaryTracks[n])&&(r==null||r.auxiliaryTracks.splice(n,1))}delete a[o]},"trackRemoved")}setEnabledSDKTrack(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setEnabled(t):this.logPossibleInconsistency(`track ${e} not present, unable to enabled/disable`)})}setSDKLocalVideoTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}setSDKLocalAudioTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}getMediaSettings(e){var a;let t=this.store.getState(ur),i=e.audioTrack,r=e.videoTrack;return{audioInputDeviceId:(i==null?void 0:i.settings.deviceId)||t.audioInputDeviceId,videoInputDeviceId:(r==null?void 0:r.settings.deviceId)||t.videoInputDeviceId,audioOutputDeviceId:(a=this.sdk.getAudioOutput().getDevice())==null?void 0:a.deviceId}}getPreviewFields(e){var i,r;if(!e.isInPreview())return;let t=w.convertPeer(e);return{localPeer:t.id,audioTrack:t.audioTrack,videoTrack:t.videoTrack,asRole:((i=e.asRole)==null?void 0:i.name)||((r=e.role)==null?void 0:r.name)}}setTrackVolume(e,t){return c(this,null,function*(){let i=this.sdk.store.getTrackById(t);i?i instanceof Ee?(yield i.setVolume(e),this.setState(r=>{let a=r.tracks[t];a&&a.type==="audio"&&(a.volume=e)},"trackVolume")):k.w(`track ${t} is not an audio track`):this.logPossibleInconsistency(`track ${t} not present, unable to set volume`)})}localAndVideoUnmuting(e){let t=this.store.getState(j);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(hr),r=this.store.getState(Qt);return i&&!r}logPossibleInconsistency(e){k.w("possible inconsistency detected - ",e)}addRemoveVideoPlugin(e,t,i){return c(this,null,function*(){if(!e){k.w("Invalid plugin received in store");return}let r=this.store.getState($);if(r){let a=this.getLocalTrack(r);a?(t==="add"?yield a.addPlugin(e,i):t==="remove"&&(yield a.removePlugin(e)),this.syncRoomState(`${t}VideoPlugin`)):this.logPossibleInconsistency(`track ${r} not present, unable to ${t} plugin`)}})}addRemoveMediaStreamVideoPlugins(e,t){return c(this,null,function*(){if(e.length===0){k.w("Invalid plugin received in store");return}let i=this.store.getState($);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addStreamPlugins(e):t==="remove"&&(yield r.removeStreamPlugins(e)),this.syncRoomState(`${t}MediaStreamPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}})}addRemoveAudioPlugin(e,t){return c(this,null,function*(){if(!e){k.w("Invalid plugin received in store");return}let i=this.store.getState(Y);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addPlugin(e):t==="remove"&&(yield r.removePlugin(e)),this.syncRoomState(`${t}AudioPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}})}isSameStoreSDKTrack(e,t){var i;return t?((i=this.sdk.store.getTrackById(t))==null?void 0:i.trackId)===e:!1}onRoleChangeRequest(e){this.setState(t=>{t.roleChangeRequests.length===0&&t.roleChangeRequests.push(w.convertRoleChangeRequest(e))},"roleChangeRequest")}removeRoleChangeRequest(e){this.setState(t=>{let i=t.roleChangeRequests.findIndex(r=>r.token===e.token);i!==-1&&t.roleChangeRequests.splice(i,1)},"removeRoleChangeRequest")}onRoleUpdate(){this.syncRoomState("roleUpdate")}getStoreLocalTrackIDfromSDKTrack(e){return this.store.getState(pr).find(i=>{var r;return((r=this.sdk.store.getTrackById(i))==null?void 0:r.trackId)===e.trackId})}updateMidCallPreviewRoomState(e,t){t.isLocal&&e===8&&this.store.getState(Sr)&&this.setState(i=>{i.room.roomState="Connected"},"midCallPreviewCompleted")}setSessionStoreValueLocally(e,t="setSessionStore"){let i=Array.isArray(e)?e:[e];this.setState(r=>{i.forEach(a=>{r.sessionStore[a.key]=a.value})},t)}};var Ai=s=>N?`${s} ${document.title}`:s;var Rt=class{constructor(e){this.recording={server:{running:!1},browser:{running:!1},hls:{running:!1}};this.rtmp={running:!1};this.hls={running:!1,variants:[]};this.id=e}};var bi=class{constructor(e,t){this.eventBus=e;this.listener=t;this.TAG="[NetworkTestManager]";this.controller=new AbortController;this.start=e=>c(this,null,function*(){var u;if(!e)return;let{url:t,timeout:i,scoreMap:r}=e,a=this.controller.signal,o=Date.now(),n=0,l=X(i).then(()=>{this.controller.abort()});try{let m=(u=(yield fetch(`${t}?${Date.now()}`,{signal:a})).body)==null?void 0:u.getReader();if(!m)throw Error("unable to process request");let g=()=>c(this,null,function*(){if(m)try{let f=!1;for(;!f;){let{value:R,done:b}=yield m.read();f=b,R&&(n+=R.byteLength,this.sendScore({scoreMap:r,downloadedSize:n,startTime:o}))}}catch(f){f.name!=="AbortError"&&d.d(this.TAG,f)}});return Promise.race([g(),l]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:n,startTime:o,finished:!0})}).catch(f=>{d.d(this.TAG,f),this.updateScoreToListener(0),this.eventBus.analytics.publish(M.previewNetworkQuality({error:f.message}))})}catch(p){p.name!=="AbortError"?(d.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(M.previewNetworkQuality({error:p.message}))):d.d(this.TAG,p)}});this.stop=()=>{this.controller.signal.aborted||this.controller.abort()};this.sendScore=({scoreMap:e,downloadedSize:t,startTime:i,finished:r=!1})=>{let a=(Date.now()-i)/1e3,n=t/1024/a*8,l=-1;for(let u in e){let p=e[u];n>=p.low&&(!p.high||n<=p.high)&&(l=Number(u))}this.updateScoreToListener(l),r&&this.eventBus.analytics.publish(M.previewNetworkQuality({score:l,downLink:n.toFixed(2)}))}}updateScoreToListener(e){var t,i;e!==this.score&&(this.score=e,(i=(t=this.listener)==null?void 0:t.onNetworkQuality)==null||i.call(t,e))}};var Ht=class{constructor(e,t,i,r,a,o){this.store=e;this.transport=t;this.deviceManager=i;this.publish=r;this.removeAuxiliaryTrack=a;this.listener=o;this.handleLocalPeerRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var a;let r=this.store.getLocalPeer();r&&(yield this.diffRolesAndPublishTracks({oldRole:e,newRole:t}),(a=this.listener)==null||a.onPeerUpdate(8,r))});this.diffRolesAndPublishTracks=i=>c(this,[i],function*({oldRole:e,newRole:t}){var f,R,b,G,et,us;let r=new Set(e.publishParams.allowed),a=new Set(t.publishParams.allowed),o=this.removeTrack(r,a,"video"),n=this.removeTrack(r,a,"audio"),l=this.removeTrack(r,a,"screen"),u=this.hasSimulcastDifference((f=e.publishParams.simulcast)==null?void 0:f.video,(R=t.publishParams.simulcast)==null?void 0:R.video),p=this.hasSimulcastDifference((b=e.publishParams.simulcast)==null?void 0:b.screen,(G=t.publishParams.simulcast)==null?void 0:G.screen),m=(us=(et=this.store.getLocalPeer())==null?void 0:et.videoTrack)==null?void 0:us.enabled;yield this.removeAudioTrack(n),yield this.removeVideoTracks(o||u),yield this.removeScreenTracks(l||p);let g=this.getSettings();u&&(g.isVideoMuted=!m),yield this.publish(g),yield this.syncDevices(g,t)})}syncDevices(e,t){return c(this,null,function*(){(!e.isAudioMuted||!e.isVideoMuted)&&t.publishParams.allowed.length>0&&(yield this.deviceManager.init(!0))})}removeVideoTracks(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.videoTrack&&(t.videoTrack.isPublished?yield this.transport.unpublish([t.videoTrack]):yield t.videoTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.videoTrack,t),t.videoTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="video")})}removeAudioTrack(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.audioTrack&&(t.audioTrack.isPublished?yield this.transport.unpublish([t.audioTrack]):yield t.audioTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t),t.audioTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="audio")})}removeScreenTracks(e){return c(this,null,function*(){e&&(yield this.removeAuxTracks(t=>t.source==="screen"))})}removeAuxTracks(e){return c(this,null,function*(){let t=this.store.getLocalPeer();if(t!=null&&t.auxiliaryTracks){let i=[...t.auxiliaryTracks];for(let r of i)e(r)&&(yield this.removeAuxiliaryTrack(r.trackId))}})}removeTrack(e,t,i){return e.has(i)&&!t.has(i)}hasSimulcastDifference(e,t){var i,r,a;return!e&&!t?!1:((i=e==null?void 0:e.layers)==null?void 0:i.length)!==((r=t==null?void 0:t.layers)==null?void 0:r.length)?!0:!!((a=e==null?void 0:e.layers)!=null&&a.some(o=>{var l;let n=(l=t==null?void 0:t.layers)==null?void 0:l.find(u=>u.rid===o.rid);return(n==null?void 0:n.maxBitrate)!==o.maxBitrate||(n==null?void 0:n.maxFramerate)!==o.maxFramerate}))}getSettings(){var t,i,r;let e=(t=this.store.getConfig())==null?void 0:t.settings;return{isAudioMuted:(i=e==null?void 0:e.isAudioMuted)!=null?i:!0,isVideoMuted:(r=e==null?void 0:e.isVideoMuted)!=null?r:!0,audioInputDeviceId:(e==null?void 0:e.audioInputDeviceId)||"default",audioOutputDeviceId:(e==null?void 0:e.audioOutputDeviceId)||"default",videoDeviceId:(e==null?void 0:e.videoDeviceId)||"default"}}};var rs=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new ce("client-events");this.isConnected=!0;this.env=null;this.websocketURL=""}setEnv(e){this.env=e,this.flushFailedEvents()}setWebsocketEndpoint(e){this.websocketURL=e}sendEvent(e){if(!this.env){this.addEventToStorage(e);return}let t={event:e.name,payload:e.properties,event_id:String(e.timestamp),peer:e.metadata.peer,timestamp:e.timestamp,device_id:e.device_id,cluster:{websocket_url:this.websocketURL}},i=this.env==="prod"?Zs:ea;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.metadata.token}`,user_agent_v2:e.metadata.userAgent},body:JSON.stringify(t)}).then(r=>{if(r.status===401){this.removeFromStorage(e);return}if(r.status!==200)throw Error(r.statusText);this.removeFromStorage(e)}).catch(r=>{d.v(this.TAG,"Failed to send event",r,e),this.addEventToStorage(e)})}flushFailedEvents(){let e=this.failedEvents.get();e==null||e.forEach(t=>this.sendEvent(t))}addEventToStorage(e){let t=this.failedEvents.get()||[];t.find(i=>i.timestamp===e.timestamp)||(t.length===100&&t.shift(),t.push(e),this.failedEvents.set(t))}removeFromStorage(e){let t=this.failedEvents.get()||[],i=t.findIndex(r=>r.timestamp===e.timestamp);i>-1&&(t.splice(i,1),this.failedEvents.set(t))}},ve=new rs;var It=class{constructor(){this.knownRoles={};this.peers={};this.tracks=new Map;this.peerTrackStates={};this.speakers=[];this.roleDetailsArrived=!1;this.env="prod";this.simulcastEnabled=!1;this.userAgent=ut(this.env);this.polls=new Map;this.whiteboards=new Map}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}getEnv(){return this.env}getPublishParams(){let e=this.getLocalPeer(),t=(e==null?void 0:e.asRole)||(e==null?void 0:e.role);return t==null?void 0:t.publishParams}getRoom(){return this.room}getPolicyForRole(e){return this.knownRoles[e]}getKnownRoles(){return this.knownRoles}getTemplateAppData(){return this.templateAppData}getLocalPeer(){if(this.localPeerId&&this.peers[this.localPeerId])return this.peers[this.localPeerId]}getRemotePeers(){return Object.values(this.peers).filter(e=>!e.isLocal)}getPeers(){return Object.values(this.peers)}getPeerMap(){return this.peers}getPeerById(e){if(this.peers[e])return this.peers[e]}getTracksMap(){return this.tracks}getTracks(){return Array.from(this.tracks.values())}getVideoTracks(){return this.getTracks().filter(e=>e.type==="video")}getRemoteVideoTracks(){return this.getTracks().filter(e=>e instanceof _)}getAudioTracks(){return this.getTracks().filter(e=>e.type==="audio")}getPeerTracks(e){let t=e?this.peers[e]:void 0,i=[];return t!=null&&t.videoTrack&&i.push(t.videoTrack),t!=null&&t.audioTrack&&i.push(t.audioTrack),i.concat((t==null?void 0:t.auxiliaryTracks)||[])}getLocalPeerTracks(){return this.getPeerTracks(this.localPeerId)}hasTrack(e){return this.tracks.has(e)}getTrackById(e){var r,a;let t=Array.from(this.tracks.values()).find(o=>o.trackId===e);if(t)return t;let i=this.getLocalPeer();if(i){if((r=i.audioTrack)!=null&&r.isPublishedTrackId(e))return i.audioTrack;if((a=i.videoTrack)!=null&&a.isPublishedTrackId(e))return i.videoTrack}}getPeerByTrackId(e){let t=Array.from(this.tracks.values()).find(i=>i.trackId===e);return t!=null&&t.peerId?this.peers[t.peerId]:void 0}getSpeakers(){return this.speakers}getSpeakerPeers(){return this.speakers.map(e=>e.peer)}getUserAgent(){return this.userAgent}createAndSetUserAgent(e){this.userAgent=ut(this.env,e)}setRoom(e){this.room=e}setKnownRoles(e){var i,r;if(this.knownRoles=e.known_roles,this.addPluginsToRoles(e.plugins),this.roleDetailsArrived=!0,this.templateAppData=e.app_data,!this.simulcastEnabled)return;let t=(i=this.knownRoles[e.name])==null?void 0:i.publishParams;this.videoLayers=this.convertSimulcastLayers((r=t.simulcast)==null?void 0:r.video),this.updatePeersPolicy()}hasRoleDetailsArrived(){return this.roleDetailsArrived}setConfig(e){var t,i,r;if(Q.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let a=Q.getSelection();a&&(e.settings||(e.settings={}),(t=a.audioInput)!=null&&t.deviceId&&(e.settings.audioInputDeviceId=e.settings.audioInputDeviceId||a.audioInput.deviceId),(i=a.audioOutput)!=null&&i.deviceId&&(e.settings.audioOutputDeviceId=e.settings.audioOutputDeviceId||a.audioOutput.deviceId),(r=a.videoInput)!=null&&r.deviceId&&(e.settings.videoDeviceId=e.settings.videoDeviceId||a.videoInput.deviceId))}e.autoManageVideo=e.autoManageVideo!==!1,e.autoManageWakeLock=e.autoManageWakeLock!==!1,this.config=e,this.setEnv()}addPeer(e){this.peers[e.peerId]=e,e.isLocal&&(this.localPeerId=e.peerId)}addTrack(e){this.tracks.set(e,e)}getTrackState(e){return this.peerTrackStates[e]}setTrackState(e){this.peerTrackStates[e.trackInfo.track_id]=e}removePeer(e){this.localPeerId===e&&(this.localPeerId=void 0),delete this.peers[e]}removeTrack(e){this.tracks.delete(e)}updateSpeakers(e){this.speakers=e}updateAudioOutputVolume(e){return c(this,null,function*(){for(let t of this.getAudioTracks())yield t.setVolume(e)})}updateAudioOutputDevice(e){return c(this,null,function*(){let t=[];this.getAudioTracks().forEach(i=>{i instanceof te&&t.push(i.setOutputDevice(e))}),yield Promise.all(t)})}getSimulcastLayers(e){var t;return!this.simulcastEnabled||!["screen","regular"].includes(e)?[]:e==="screen"?[]:((t=this.videoLayers)==null?void 0:t.layers)||[]}convertSimulcastLayers(e){if(e)return y(S({},e),{layers:(e.layers||[]).map(t=>y(S({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var n,l,u;if([!e||!e.role,t==="screen",!this.simulcastEnabled].some(p=>!!p))return[];let i=this.getPolicyForRole(e.role.name).publishParams,r,a,o;return t==="regular"?(r=(n=i.simulcast)==null?void 0:n.video,a=i.video.width,o=i.video.height):t==="screen"&&(r=(l=i.simulcast)==null?void 0:l.screen,a=i.screen.width,o=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let m=be[p.rid],g={width:Math.floor(a/p.scaleResolutionDownBy),height:Math.floor(o/p.scaleResolutionDownBy)};return{layer:m,resolution:g}}))||[]}setPoll(e){this.polls.set(e.id,e)}getPoll(e){return this.polls.get(e)}setWhiteboard(e){this.whiteboards.set(e.id,e)}getWhiteboard(e){return e?this.whiteboards.get(e):this.whiteboards.values().next().value}getErrorListener(){return this.errorListener}cleanup(){let e=this.getTracks();for(let t of e)t.cleanup();this.room=void 0,this.config=void 0,this.localPeerId=void 0,this.roleDetailsArrived=!1}setErrorListener(e){this.errorListener=e}updatePeersPolicy(){this.getPeers().forEach(e=>{var t;if(!e.role){(t=this.errorListener)==null||t.onError(h.GenericErrors.InvalidRole("VALIDATION",""));return}e.role=this.getPolicyForRole(e.role.name)})}addPluginsToRoles(e){if(!e)return;let t=(i,r,a)=>{var n;let o=this.knownRoles[i].permissions;o[r]||(o[r]=[]),(n=o[r])==null||n.push(a)};Object.keys(e).forEach(i=>{var o,n,l;let r=i;if(!e[r])return;let a=e[r].permissions;(o=a==null?void 0:a.admin)==null||o.forEach(u=>t(u,r,"admin")),(n=a==null?void 0:a.reader)==null||n.forEach(u=>t(u,r,"read")),(l=a==null?void 0:a.writer)==null||l.forEach(u=>t(u,r,"write"))})}setEnv(){var r;let t=((r=this.config)==null?void 0:r.initEndpoint).split("https://")[1],i="prod";t.startsWith("prod")?i="prod":t.startsWith("qa")?i="qa":t.startsWith("dev")&&(i="dev"),this.env=i,ve.setEnv(i)}};var Ri=class{constructor(){this.TAG="[WakeLockManager]";this.wakeLock=null;this.acquireLock=()=>c(this,null,function*(){yield this.requestWakeLock(),document==null||document.addEventListener("visibilitychange",this.visibilityHandler)});this.cleanup=()=>c(this,null,function*(){if(this.wakeLock&&!this.wakeLock.released)try{yield this.wakeLock.release(),d.d(this.TAG,"Wake lock released")}catch(e){let t=e;d.w(this.TAG,"Error while releasing wake lock",`name=${t.name}, message=${t.message}`)}this.wakeLock=null});this.visibilityHandler=()=>c(this,null,function*(){(document==null?void 0:document.visibilityState)==="visible"&&(!this.wakeLock||this.wakeLock.released)&&(d.d(this.TAG,"Re-acquiring wake lock due to visibility change"),yield this.requestWakeLock())});this.requestWakeLock=()=>c(this,null,function*(){try{if(!("wakeLock"in navigator)){d.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),d.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;d.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var Hi=class{constructor(e){this.store=e;this.bufferSize=100;this.TAG="[AnalyticsEventsService]";this.transport=null;this.pendingEvents=[];this.level=1}setTransport(e){this.transport=e}reset(){this.transport=null,this.pendingEvents=[]}queue(e){if(e.level>=this.level&&(this.pendingEvents.push(e),this.pendingEvents.length>this.bufferSize)){let t=this.pendingEvents.shift();d.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){ve.flushFailedEvents()}flush(){var e;try{for(;this.pendingEvents.length>0;){let t=this.pendingEvents.shift();t&&(t.metadata.peer.peer_id=(e=this.store.getLocalPeer())==null?void 0:e.peerId,t.metadata.userAgent=this.store.getUserAgent(),this.transport&&this.transport.transportProvider.isConnected?this.transport.sendEvent(t):this.sendClientEventOnHTTP(t))}}catch(t){d.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,a,o,n;let t=this.store.getRoom(),i=this.store.getLocalPeer();e.metadata.token=(r=this.store.getConfig())==null?void 0:r.authToken,e.metadata.peer={session_id:t==null?void 0:t.sessionId,room_id:t==null?void 0:t.id,room_name:t==null?void 0:t.name,template_id:t==null?void 0:t.templateId,joined_at:(a=t==null?void 0:t.joinedAt)==null?void 0:a.getTime(),session_started_at:(o=t==null?void 0:t.startedAt)==null?void 0:o.getTime(),role:(n=i==null?void 0:i.role)==null?void 0:n.name,user_name:i==null?void 0:i.name,user_data:i==null?void 0:i.metadata,peer_id:i==null?void 0:i.peerId},ve.sendEvent(e)}};var Pa=require("uuid");var Ea={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},Ct=class{constructor(e,t,i){this.store=e;this.deviceManager=t;this.eventBus=i;this.autoPausedTracks=new Set;this.TAG="[AudioSinkManager]:";this.volume=100;this.state=S({},Ea);this.handleAudioPaused=e=>c(this,null,function*(){var a;let i=(a=e.target.srcObject)==null?void 0:a.getAudioTracks()[0];if(!(i!=null&&i.enabled))return;d.d(this.TAG,"Audio Paused",e.target.id);let r=this.store.getTrackById(e.target.id);r&&(Yt()?(yield X(500),this.playAudioFor(r)):this.autoPausedTracks.add(r))});this.handleTrackUpdate=({track:e})=>{d.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,n;let a=document.createElement("audio");a.style.display="none",a.id=e.trackId,a.addEventListener("pause",this.handleAudioPaused),a.onerror=()=>c(this,null,function*(){var u,p;d.e(this.TAG,"error on audio element",a.error);let l=h.TracksErrors.AudioPlaybackError(`Audio playback error for track - ${e.trackId} code - ${(u=a==null?void 0:a.error)==null?void 0:u.code}`);this.eventBus.analytics.publish(M.audioPlaybackError(l)),((p=a==null?void 0:a.error)==null?void 0:p.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(a,e),yield X(500),yield this.handleTrackAdd({track:e,peer:t,callListener:!1}))}),e.setAudioElement(a),e.setVolume(this.volume),d.d(this.TAG,"Audio track added",`${e}`),this.init(),yield this.autoSelectAudioOutput(),(o=this.audioSink)==null||o.append(a),this.outputDevice&&(yield e.setOutputDevice(this.outputDevice)),a.srcObject=new MediaStream([e.nativeTrack]),i&&((n=this.listener)==null||n.onTrackUpdate(0,e,t)),yield this.handleAutoplayError(e)});this.handleAutoplayError=e=>c(this,null,function*(){if(this.state.autoplayFailed===void 0&&(this.state.autoplayCheckPromise||(this.state.autoplayCheckPromise=new Promise(t=>{this.playAudioFor(e).then(t)})),yield this.state.autoplayCheckPromise),this.state.autoplayFailed){this.autoPausedTracks.add(e);return}yield this.playAudioFor(e)});this.handleAudioDeviceChange=e=>{e.error||!e.selection||e.type==="video"||this.unpauseAudioTracks()};this.handleTrackRemove=e=>{this.autoPausedTracks.delete(e);let t=document.getElementById(e.trackId);t&&this.removeAudioElement(t,e),this.audioSink&&this.audioSink.childElementCount===0&&(this.state.autoplayCheckPromise=void 0,this.state.autoplayFailed=void 0),d.d(this.TAG,"Audio track removed",`${e}`)};this.unpauseAudioTracks=()=>c(this,null,function*(){let e=[];this.autoPausedTracks.forEach(t=>{e.push(this.playAudioFor(t))}),yield Promise.all(e)});this.removeAudioElement=(e,t)=>{e&&(d.d(this.TAG,"removing audio element",`${t}`),e.removeEventListener("pause",this.handleAudioPaused),e.srcObject=null,e.remove(),t.setAudioElement(null))};this.autoSelectAudioOutput=()=>c(this,null,function*(){var e,t,i;if(((e=this.audioSink)==null?void 0:e.children.length)===0){let r=(t=this.deviceManager.audioInput)==null?void 0:t.find(o=>o.label.includes("earpiece")),a=(i=this.store.getLocalPeer())==null?void 0:i.audioTrack;a&&r&&(yield a.setSettings({deviceId:r==null?void 0:r.deviceId}),yield a.setSettings({deviceId:"default"}))}});this.eventBus.audioTrackAdded.subscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.subscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.subscribe(this.handleTrackUpdate),this.eventBus.deviceChange.subscribe(this.handleAudioDeviceChange)}setListener(e){this.listener=e}get outputDevice(){return this.deviceManager.outputDevice}getVolume(){return this.volume}setVolume(e){return c(this,null,function*(){yield this.store.updateAudioOutputVolume(e),this.volume=e})}unblockAutoplay(){return c(this,null,function*(){this.autoPausedTracks.size>0&&this.unpauseAudioTracks()})}init(e){if(this.state.initialized||this.audioSink)return;this.state.initialized=!0;let t=document.createElement("div");t.id=`HMS-SDK-audio-sink-${(0,Pa.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,d.d(this.TAG,"audio sink created",this.audioSink)}cleanup(){var e;(e=this.audioSink)==null||e.remove(),this.audioSink=void 0,this.eventBus.audioTrackAdded.unsubscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.unsubscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.unsubscribe(this.handleTrackUpdate),this.eventBus.deviceChange.unsubscribe(this.handleAudioDeviceChange),this.autoPausedTracks=new Set,this.state=S({},Ea)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){d.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),d.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),d.w(this.TAG,"Failed to play track",`${e}`,i);let r=i;if(!this.state.autoplayFailed&&r.name==="NotAllowedError"){this.state.autoplayFailed=!0;let a=h.TracksErrors.AutoplayBlocked("AUTOPLAY","");a.addNativeError(r),this.eventBus.analytics.publish(M.autoplayError()),this.eventBus.autoplayError.publish(a)}}})}};var Lt=class{constructor(e,t){this.store=e;this.eventBus=t;this.audioInput=[];this.audioOutput=[];this.videoInput=[];this.hasWebcamPermission=!1;this.hasMicrophonePermission=!1;this.TAG="[Device Manager]:";this.initialized=!1;this.videoInputChanged=!1;this.audioInputChanged=!1;this.updateOutputDevice=e=>c(this,null,function*(){let t=this.audioOutput.find(i=>i.deviceId===e);return t&&(this.outputDevice=t,yield this.store.updateAudioOutputDevice(t),Q.updateSelection("audioOutput",{deviceId:t.deviceId,groupId:t.groupId})),t});this.getCurrentSelection=()=>{var o,n;let e=this.store.getLocalPeer(),t=this.createIdentifier((o=e==null?void 0:e.audioTrack)==null?void 0:o.getMediaTrackSettings()),i=this.createIdentifier((n=e==null?void 0:e.videoTrack)==null?void 0:n.getMediaTrackSettings()),r=this.audioInput.find(l=>this.createIdentifier(l)===t),a=this.videoInput.find(l=>this.createIdentifier(l)===i);return{audioInput:r,videoInput:a,audioOutput:this.outputDevice}};this.computeChange=(e,t)=>e.length!==t.length?!0:t.some(i=>!e.includes(this.createIdentifier(i)));this.enumerateDevices=()=>c(this,null,function*(){try{let e=yield navigator.mediaDevices.enumerateDevices(),t=this.videoInput.map(this.createIdentifier),i=this.audioInput.map(this.createIdentifier);this.audioInput=[],this.audioOutput=[],this.videoInput=[],e.forEach(r=>{r.kind==="audioinput"&&r.label?(this.hasMicrophonePermission=!0,this.audioInput.push(r)):r.kind==="audiooutput"?this.audioOutput.push(r):r.kind==="videoinput"&&r.label&&(this.hasWebcamPermission=!0,this.videoInput.push(r))}),this.videoInputChanged=this.computeChange(t,this.videoInput),this.audioInputChanged=this.computeChange(i,this.audioInput),Q.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){d.e(this.TAG,"Failed enumerating devices",e)}});this.handleDeviceChange=ii(()=>c(this,null,function*(){yield this.enumerateDevices(),this.logDevices("After Device Change");let e=this.store.getLocalPeer(),t=e==null?void 0:e.audioTrack;yield this.setOutputDevice(!0),t&&(yield this.handleAudioInputDeviceChange(e==null?void 0:e.audioTrack)),yield this.handleVideoInputDeviceChange(e==null?void 0:e.videoTrack),this.eventBus.analytics.publish(M.deviceChange({selection:this.getCurrentSelection(),type:"change",devices:this.getDevices()}))}),500).bind(this);this.handleAudioInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No Audio track on local peer");return}if(!this.audioInputChanged){d.d(this.TAG,"No Change in AudioInput Device");return}let t=this.getNewAudioInputDevice();if(!t||!t.deviceId){this.eventBus.analytics.publish(M.deviceChange({selection:{audioInput:t},error:h.TracksErrors.SelectedDeviceMissing("audio"),devices:this.getDevices(),type:"audioInput"})),d.e(this.TAG,"Audio device not found");return}let{settings:i}=e,r=new ae().codec(i.codec).maxBitrate(i.maxBitrate).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"audioInput"}),this.logDevices("Audio Device Change Success")}catch(a){d.e(this.TAG,"[Audio Device Change]",a),this.eventBus.analytics.publish(M.deviceChange({selection:{audioInput:t},devices:this.getDevices(),type:"audioInput",error:a})),this.eventBus.deviceChange.publish({error:a,selection:t,type:"audioInput",devices:this.getDevices()})}});this.handleVideoInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No video track on local peer");return}if(!this.videoInputChanged){d.d(this.TAG,"No Change in VideoInput Device");return}let t=this.videoInput[0];if(!t||!t.deviceId){this.eventBus.analytics.publish(M.deviceChange({selection:{videoInput:t},error:h.TracksErrors.SelectedDeviceMissing("video"),devices:this.getDevices(),type:"video"})),d.e(this.TAG,"Video device not found");return}let{settings:i}=e,r=new ee().codec(i.codec).maxBitrate(i.maxBitrate).maxFramerate(i.maxFramerate).setWidth(i.width).setHeight(i.height).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"video"}),this.logDevices("Video Device Change Success")}catch(a){d.e(this.TAG,"[Video Device Change]",a),this.eventBus.analytics.publish(M.deviceChange({selection:{videoInput:t},devices:this.getDevices(),type:"video",error:a})),this.eventBus.deviceChange.publish({error:a,type:"video",selection:t,devices:this.getDevices()})}});let i=({enabled:r,track:a})=>r&&a.source==="regular";this.eventBus.localVideoEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.videoInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})})),this.eventBus.localAudioEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.audioInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})}))}init(e=!1){return c(this,null,function*(){this.initialized&&!e||(!this.initialized&&navigator.mediaDevices.addEventListener("devicechange",this.handleDeviceChange),this.initialized=!0,yield this.enumerateDevices(),this.logDevices("Init"),yield this.setOutputDevice(),this.eventBus.deviceChange.publish({devices:this.getDevices()}),this.eventBus.analytics.publish(M.deviceChange({selection:this.getCurrentSelection(),type:"list",devices:this.getDevices()})))})}getDevices(){return{audioInput:this.audioInput,audioOutput:this.audioOutput,videoInput:this.videoInput}}cleanup(){this.initialized=!1,this.audioInput=[],this.audioOutput=[],this.videoInput=[],this.outputDevice=void 0,navigator.mediaDevices.removeEventListener("devicechange",this.handleDeviceChange)}createIdentifier(e){return e?`${e.deviceId}${e.groupId}`:""}getNewAudioInputDevice(){let e=this.store.getLocalPeer(),t=e==null?void 0:e.audioTrack,i=this.audioInput.find(a=>a.deviceId===(t==null?void 0:t.getManuallySelectedDeviceId()));if(i)return i;t==null||t.resetManuallySelectedDeviceId();let r=this.audioInput.find(a=>a.deviceId==="default");return r?this.audioInput.find(o=>o.deviceId!=="default"&&r.label.includes(o.label)):this.audioInput[0]}setOutputDevice(e=!1){return c(this,null,function*(){let t=this.getNewAudioInputDevice(),i=this.createIdentifier(this.outputDevice);this.outputDevice=this.getAudioOutputDeviceMatchingInput(t),this.outputDevice||(this.outputDevice=this.audioOutput.find(r=>this.createIdentifier(r)===i),this.outputDevice||(this.outputDevice=this.audioOutput.find(r=>r.deviceId==="default")||this.audioOutput[0])),yield this.store.updateAudioOutputDevice(this.outputDevice),e&&i!==this.createIdentifier(this.outputDevice)&&(this.eventBus.analytics.publish(M.deviceChange({selection:{audioOutput:this.outputDevice},devices:this.getDevices(),type:"audioOutput"})),this.eventBus.deviceChange.publish({selection:this.outputDevice,type:"audioOutput",devices:this.getDevices()}))})}getAudioOutputDeviceMatchingInput(e){var o,n;let t=((n=(o=this.store.getConfig())==null?void 0:o.settings)==null?void 0:n.speakerAutoSelectionBlacklist)||[];if(t==="all"||!e)return;let i=e.label.toLowerCase()||"";if(t.some(l=>i.includes(l.toLowerCase())))return;let r=this.audioOutput.find(l=>e.deviceId!=="default"&&l.label===e.label);if(r)return r;let a=this.audioOutput.find(l=>l.groupId===e.groupId);if(a&&this.audioOutput[0].deviceId==="default"&&a.groupId===this.audioOutput[0].groupId)return a}logDevices(e=""){d.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}};var Ii=class{constructor(e,t){this.deviceManager=e;this.audioSinkManager=t}getVolume(){return this.audioSinkManager.getVolume()}setVolume(e){if(e<0||e>100)throw Error("Please pass a valid number between 0-100");this.audioSinkManager.setVolume(e)}getDevice(){return this.deviceManager.outputDevice}setDevice(e){return this.deviceManager.updateOutputDevice(e)}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield Pe.resumeContext()})}};var Aa=require("eventemitter2");var O=class{constructor(e,t){this.eventName=e;this.eventEmitter=t;this.publish=e=>{this.eventEmitter.emit(this.eventName,e)};this.subscribe=e=>{this.eventEmitter.on(this.eventName,e)};this.subscribeOnce=e=>{this.eventEmitter.once(this.eventName,e)};this.unsubscribe=e=>{this.eventEmitter.off(this.eventName,e)};this.waitFor=e=>this.eventEmitter.waitFor(this.eventName,{filter:e});this.removeAllListeners=()=>{this.eventEmitter.removeAllListeners(this.eventName)}}};var Ci=class{constructor(){this.eventEmitter=new Aa.EventEmitter2;this.deviceChange=new O(V.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new O(V.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new O(V.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.statsUpdate=new O(V.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new O(V.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new O(V.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new O(V.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new O(V.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new O(V.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.analytics=new O(V.ANALYTICS,this.eventEmitter);this.policyChange=new O(V.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new O(V.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new O(V.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new O(V.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new O(V.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new O(V.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new O(V.LEAVE,this.eventEmitter)}};var Dt=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof ke?(this.mute=!e.enabled,this.track_id=e.publishedTrackId,this.stream_id=e.stream.id):(this.mute=e.mute,this.track_id=e.track_id,this.stream_id=e.stream_id)}};var Li=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var a,o,n;let t=e["speaker-list"],i=t.map(l=>({audioLevel:l.level,peer:this.store.getPeerById(l.peer_id),track:this.store.getTrackById(l.track_id)}));(a=this.audioListener)==null||a.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(o=this.listener)==null||o.onPeerUpdate(4,l)}else(n=this.listener)==null||n.onPeerUpdate(5,null)}};var Di=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;d.d(this.TAG,`Received Message from sender=${(t=e==null?void 0:e.peer)==null?void 0:t.peer_id}: ${e}`),(i=this.listener)==null||i.onMessageReceived(e)}};var wi=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(a=>{let o=this.store.getPeerById(a.peer_id);return o&&o.updateNetworkQuality(a.downlink_score),{peerID:a.peer_id,downlinkQuality:a.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var ze=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{d.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{d.d(this.TAG,"ONTRACKREMOVE",e),Object.keys(e.tracks).forEach(i=>{var n;let r=this.store.getTrackState(i);if(!r)return;let a=this.store.getTrackById(i);if(!a){d.d(this.TAG,"Track not found in store");return}a.type==="audio"&&this.eventBus.audioTrackRemoved.publish(a),this.store.removeTrack(a);let o=this.store.getPeerById(r.peerId);o&&(this.removePeerTracks(o,a),(n=this.listener)==null||n.onTrackUpdate(1,a,o))})};this.handleTrackLayerUpdate=e=>{for(let t in e.tracks){let i=e.tracks[t],r=this.store.getTrackById(t);!r||!this.store.getPeerByTrackId(t)||r instanceof _&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var a,o;let i=this.store.getPeerById(e.peer.peer_id),r=e.peer;if(!i&&!r){d.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=Re(r,this.store),this.store.addPeer(i));for(let n in e.tracks){let l=Object.assign({},(a=this.store.getTrackState(n))==null?void 0:a.trackInfo),u=e.tracks[n],p=this.store.getTrackById(n);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:S(S({},l),u)}),!p||this.tracksToProcess.has(n))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{p.setEnabled(!u.mute);let m=this.processTrackUpdate(p,l,u);m&&((o=this.listener)==null||o.onTrackUpdate(m,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var a;let i=this.store.getTrackState(t.trackId);if(!i){d.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){d.d(this.TAG,"Peer not added to store, peerId",i.peerId);return}t.source=i.trackInfo.source,t.peerId=r.peerId,t.logIdentifier=r.name,t.setEnabled(!i.trackInfo.mute),this.addAudioTrack(r,t),this.addVideoTrack(r,t),t.type==="audio"?this.eventBus.audioTrackAdded.publish({track:t,peer:r}):(a=this.listener)==null||a.onTrackUpdate(0,t,r),this.tracksToProcess.delete(t.trackId)})}}handleTrackMetadataAdd(e){d.d(this.TAG,"TRACK_METADATA_ADD",JSON.stringify(e,null,2));for(let t in e.tracks){let i=e.tracks[t];this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:i})}this.processPendingTracks()}handleTrackRemove(e,t=!0){var a;d.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){d.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let o=this.store.getPeerById(i.peerId);if(!o)return;this.removePeerTracks(o,e),(a=this.listener)==null||a.onTrackUpdate(1,e,o),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var a,o;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(a=this.listener)==null||a.onTrackUpdate(5,e,i):(o=this.listener)==null||o.onTrackUpdate(6,e,i)}removePeerTracks(e,t){let i=e.auxiliaryTracks.indexOf(t);i>-1?(e.auxiliaryTracks.splice(i,1),d.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,d.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,d.d(this.TAG,"video track removed",`${t}`))}addAudioTrack(e,t){var i;t.type==="audio"&&(t.source==="regular"&&(!e.audioTrack||((i=e.audioTrack)==null?void 0:i.trackId)===t.trackId)?e.audioTrack=t:e.auxiliaryTracks.push(t),this.store.addTrack(t),d.d(this.TAG,"audio track added",`${t}`))}addVideoTrack(e,t){if(t.type!=="video")return;let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);if(i.setSimulcastDefinitons(r),this.addAsPrimaryVideoTrack(e,i))e.videoTrack?e.videoTrack.replaceTrack(i):e.videoTrack=i,this.store.addTrack(e.videoTrack);else{let a=e.auxiliaryTracks.findIndex(o=>o.trackId===i.trackId);a===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[a].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[a]))}d.d(this.TAG,"video track added",`${t}`)}addAsPrimaryVideoTrack(e,t){var i;return t.source==="regular"&&(!e.videoTrack||((i=e.videoTrack)==null?void 0:i.trackId)===t.trackId)}processTrackUpdate(e,t,i){let r;return t.mute!==i.mute?(r=i.mute?2:3,e.type==="audio"&&this.eventBus.audioTrackUpdate.publish({track:e,enabled:!i.mute})):t.description!==i.description&&(r=4),r}};var _i=class extends ze{constructor(t,i,r,a){super(t,i,a);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u;if(t.type!=="video")return;let a=this.store.getPeerById(i);if(!a||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let o=new me(new MediaStream,this.transport.getSubscribeConnection()),n=Te.getEmptyVideoTrack();n.enabled=!t.mute;let l=new _(o,n,t.source);l.setTrackId(t.track_id),l.peerId=a.peerId,l.logIdentifier=a.name,this.addVideoTrack(a,l),r&&((u=this.listener)==null||u.onTrackUpdate(0,a.videoTrack,a))}}handleTrackMetadataAdd(t){super.handleTrackMetadataAdd(t);for(let i in t.tracks)t.tracks[i].type==="video"&&this.processTrackInfo(t.tracks[i],t.peer.peer_id)}handleTrackRemove(t){let i=t.type==="video"&&t.source==="regular";super.handleTrackRemove(t,!i),i&&this.processTrackInfo({track_id:t.trackId,mute:!t.enabled,type:t.type,source:t.source,stream_id:t.stream.id},t.peerId,!1)}addAsPrimaryVideoTrack(t,i){return i.source!=="regular"?!1:!t.videoTrack||t.videoTrack.trackId===i.trackId?!0:t.videoTrack.enabled&&de(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var a,o,n,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(o=(a=i==null?void 0:i.role)==null?void 0:a.subscribeParams)==null?void 0:o.subscribeToRoles)==null?void 0:l.includes((n=r.role)==null?void 0:n.name))}};var Ni=class{constructor(e,t,i,r){this.store=e;this.peerManager=t;this.trackManager=i;this.listener=r;this.TAG="[PeerListManager]";this.handleInitialPeerList=e=>{let t=Object.values(e.peers);this.peerManager.handlePeerList(t)};this.handleReconnectPeerList=e=>{this.handleRepeatedPeerList(e.peers)};this.handlePreviewRoomState=e=>{if(!this.store.hasRoleDetailsArrived())return;let t=e.peers;if(t==null){e.peer_count===0&&this.handleRepeatedPeerList({});return}Object.keys(t).forEach(i=>{t[i].tracks={},t[i].is_from_room_state=!0}),this.handleRepeatedPeerList(t)};this.handleRepeatedPeerList=e=>{let t=this.store.getRemotePeers(),i=Object.values(e),r=t.filter(o=>!e[o.peerId]);r.length>0&&d.d(this.TAG,`${r}`),r.forEach(o=>{var l;let n={peer_id:o.peerId,role:((l=o.role)==null?void 0:l.name)||"",info:{name:o.name,data:o.metadata||"",user_id:o.customerUserId||""},tracks:{},groups:[],realtime:o.realtime};this.peerManager.handlePeerLeave(n)});let a=[];i.forEach(o=>{let n=this.store.getPeerById(o.peer_id),l=Object.values(o.tracks);n&&(this.store.getPeerTracks(n.peerId).forEach(p=>{var m;o.tracks[p.trackId]||(this.removePeerTrack(n,p.trackId),(m=this.listener)==null||m.onTrackUpdate(1,p,n))}),l.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:n.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:o,tracks:o.tracks},!1),this.peerManager.handlePeerUpdate(o)),a.push(o)}),a.length>0&&this.peerManager.handlePeerList(a)}}handleNotification(e,t,i){if(e==="peer-list"){let r=t;i?(d.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(d.d(this.TAG,"PEER_LIST event",JSON.stringify(r,null,2)),this.handleInitialPeerList(r))}else if(e==="room-state"){let r=t;this.handlePreviewRoomState(r)}}removePeerTrack(e,t){var i,r;if(d.d(this.TAG,`removing track - ${t} from ${e}`),((i=e.audioTrack)==null?void 0:i.trackId)===t)e.audioTrack=void 0;else if(((r=e.videoTrack)==null?void 0:r.trackId)===t)e.videoTrack=void 0;else{let a=e.auxiliaryTracks.findIndex(o=>o.trackId===t);a>=0&&e.auxiliaryTracks.splice(a,1)}}};var L=s=>s?new Date(s):void 0;var Oi=class{constructor(e,t,i){this.store=e;this.trackManager=t;this.listener=i;this.TAG="[PeerManager]";this.handlePeerList=e=>{var r,a;if(e.length===0){(r=this.listener)==null||r.onPeerUpdate(9,[]);return}let t=[],i=new Set(e.map(o=>o.peer_id));this.store.getRemotePeers().forEach(({peerId:o,fromRoomState:n})=>{!i.has(o)&&n&&this.store.removePeer(o)});for(let o of e)t.push(this.makePeer(o));(a=this.listener)==null||a.onPeerUpdate(9,t),this.trackManager.processPendingTracks()};this.handlePeerJoin=e=>{var i;let t=this.makePeer(e);(i=this.listener)==null||i.onPeerUpdate(0,t),this.trackManager.processPendingTracks()};this.handlePeerLeave=e=>{var i,r,a,o;let t=this.store.getPeerById(e.peer_id);this.store.removePeer(e.peer_id),d.d(this.TAG,"PEER_LEAVE",e.peer_id,`remainingPeers=${this.store.getPeers().length}`),t&&(t.audioTrack&&((i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t)),t.videoTrack&&((r=this.listener)==null||r.onTrackUpdate(1,t.videoTrack,t)),(a=t.auxiliaryTracks)==null||a.forEach(n=>{var l;(l=this.listener)==null||l.onTrackUpdate(1,n,t)}),(o=this.listener)==null||o.onPeerUpdate(1,t))}}handleNotification(e,t){switch(e){case"on-peer-join":{let i=t;this.handlePeerJoin(i);break}case"on-peer-leave":{let i=t;this.handlePeerLeave(i);break}case"on-peer-update":this.handlePeerUpdate(t);break;default:break}}handlePeerUpdate(e){var a,o,n,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(a=this.listener)==null||a.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(o=this.listener)==null||o.onPeerUpdate(13,t);return}if(!t){d.d(this.TAG,`peer ${e.peer_id} not found`);return}if(t.role&&t.role.name!==e.role){let p=this.store.getPolicyForRole(e.role);t.updateRole(p),this.updateSimulcastLayersForPeer(t),(n=this.listener)==null||n.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(fe);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(S({peer:t},e.info))}handlePeerInfoUpdate({peer:e,name:t,data:i}){var r,a;e&&(t&&e.name!==t&&(e.updateName(t),(r=this.listener)==null||r.onPeerUpdate(10,e)),i&&e.metadata!==i&&(e.updateMetadata(i),(a=this.listener)==null||a.onPeerUpdate(11,e)))}makePeer(e){let t=this.store.getPeerById(e.peer_id);t||(t=Re(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),d.d(this.TAG,"adding to the peerList",`${t}`));for(let i in e.tracks){let r=e.tracks[i];this.store.setTrackState({peerId:e.peer_id,trackInfo:r}),r.type==="video"&&this.trackManager.processTrackInfo(r,e.peer_id,!1)}return t}updateSimulcastLayersForPeer(e){this.store.getPeerTracks(e.peerId).forEach(t=>{if(t.type==="video"&&["regular","screen"].includes(t.source)){let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);i.setSimulcastDefinitons(r)}})}};var xi=class{constructor(e,t){this.store=e;this.eventBus=t}handlePolicyChange(e){let t=this.store.getLocalPeer();if(t&&!t.role){let r=e.known_roles[e.name];t.updateRole(r)}this.store.setKnownRoles(e);let i=this.store.getRoom();i?i.templateId=e.template_id:d.w("[PolicyChangeManager]","on policy change - room not present"),this.updateLocalPeerRole(e),this.eventBus.policyChange.publish(e)}updateLocalPeerRole(e){var i;let t=this.store.getLocalPeer();if(t!=null&&t.role&&t.role.name!==e.name){let r=this.store.getPolicyForRole(e.name),a=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:a,newRole:r})}}};var Ui=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.TAG="[HMSWhiteboardInteractivityCenter]"}get isEnabled(){return this.transport.isFlagEnabled("whiteboardEnabled")}open(e){return c(this,null,function*(){var o;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e==null?void 0:e.id),i=t==null?void 0:t.id;if(t||(i=(yield this.transport.signal.createWhiteboard(this.getCreateOptionsWithDefaults(e))).id),!i)throw new Error(`Whiteboard ID: ${i} not found`);let r=yield this.transport.signal.getWhiteboard({id:i}),a=y(S({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,token:r.token,addr:r.addr,owner:r.owner,permissions:r.permissions||[],open:!0});this.store.setWhiteboard(a),(o=this.listener)==null||o.onWhiteboardUpdate(a)})}close(e){return c(this,null,function*(){var r;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e);if(!t)throw new Error(`Whiteboard ID: ${e} not found`);let i={id:t.id,title:t.title,open:!1};this.store.setWhiteboard(i),(r=this.listener)==null||r.onWhiteboardUpdate(i)})}setListener(e){this.listener=e}getCreateOptionsWithDefaults(e){var o;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],a=[];return t.forEach(n=>{var l,u,p;(l=n.permissions.whiteboard)!=null&&l.includes("read")&&i.push(n.name),(u=n.permissions.whiteboard)!=null&&u.includes("write")&&r.push(n.name),(p=n.permissions.whiteboard)!=null&&p.includes("admin")&&a.push(n.name)}),{title:(e==null?void 0:e.title)||`${(o=this.store.getRoom())==null?void 0:o.id} Whiteboard`,reader:(e==null?void 0:e.reader)||i,writer:(e==null?void 0:e.writer)||r,admin:(e==null?void 0:e.admin)||a}}};var wt=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Ui(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var o,n;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(y(S({},e),{mode:e.mode?t[e.mode]:void 0,poll_id:e.id,vote:e.rolesThatCanVote,responses:e.rolesThatCanViewResponses}));e.id||(e.id=i),Array.isArray(e.questions)&&(yield this.addQuestionsToPoll(e.id,e.questions));let r=yield this.transport.signal.getPollQuestions({poll_id:e.id,index:0,count:50}),a=Vi(y(S({},e),{poll_id:e.id,state:"created",created_by:(o=this.store.getLocalPeer())==null?void 0:o.peerId}));a.questions=r.questions.map(({question:l,options:u,answer:p})=>y(S({},l),{options:u,answer:p})),(n=this.listener)==null||n.onPollsUpdate(0,[a])})}startPoll(e){return c(this,null,function*(){typeof e=="string"?yield this.transport.signal.startPoll({poll_id:e}):(yield this.createPoll(e),yield this.transport.signal.startPoll({poll_id:e.id}))})}addQuestionsToPoll(e,t){return c(this,null,function*(){t.length>0&&(yield this.transport.signal.setPollQuestions({poll_id:e,questions:t.map((i,r)=>this.createQuestionSetParams(i,r))}))})}stopPoll(e){return c(this,null,function*(){yield this.transport.signal.stopPoll({poll_id:e})})}addResponsesToPoll(e,t){return c(this,null,function*(){let i=this.store.getPoll(e);if(!i)throw new Error("Invalid poll ID - Poll not found");let r=t.map(a=>{var n,l;let o=this.getQuestionInPoll(i,a.questionIndex);return o.type==="single-choice"?(a.option=a.option||((n=a.options)==null?void 0:n[0])||-1,delete a.text,delete a.options):o.type==="multiple-choice"?((l=a.options)==null||l.sort(),delete a.text,delete a.option):(delete a.option,delete a.options),a.skipped&&(delete a.option,delete a.options,delete a.text),S({duration:0,type:o.type,question:a.questionIndex},a)});yield this.transport.signal.setPollResponses({poll_id:e,responses:r})})}fetchLeaderboard(e,t,i){return c(this,null,function*(){var u,p;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let a=((p=(u=this.store.getLocalPeer())==null?void 0:u.role)==null?void 0:p.permissions.pollRead)||!1;if(r.anonymous||r.state!=="stopped"||!a)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),n={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctAnswers:o.correct_users};return{entries:o.questions.map(m=>({position:m.position,totalResponses:m.total_responses,correctResponses:m.correct_responses,duration:m.duration,peer:m.peer,score:m.score})),hasNext:!o.last,summary:n}})}getPolls(){return c(this,null,function*(){let e=yield this.transport.signal.getPollsList({count:50}),t=[];for(let i of e.polls){let r=yield this.transport.signal.getPollQuestions({poll_id:i.poll_id,index:0,count:50}),a=Vi(i);a.questions=r.questions.map(({question:o,options:n,answer:l})=>y(S({},o),{options:n,answer:l})),t.push(a),this.store.setPoll(a)}return t})}createQuestionSetParams(e,t){var o;let i=y(S({},e),{index:t+1}),r,a=e.answer||{hidden:!1};return Array.isArray(e.options)&&["single-choice","multiple-choice"].includes(e.type)?(r=(o=e.options)==null?void 0:o.map((n,l)=>({index:l+1,text:n.text,weight:n.weight})),a==null||delete a.text,e.type==="single-choice"?a.option=e.options.findIndex(n=>n.isCorrectAnswer)+1||void 0:a.options=e.options.map((n,l)=>n.isCorrectAnswer?l+1:void 0).filter(n=>!!n)):(a==null||delete a.options,a==null||delete a.option),{question:i,options:r,answer:a}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(a=>a.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},Vi=s=>{let e={userid:"customerID",peerid:"peerID",username:"userName"};return{id:s.poll_id,title:s.title,startedBy:s.started_by,createdBy:s.created_by,anonymous:s.anonymous,type:s.type,duration:s.duration,locked:s.locked,mode:s.mode?e[s.mode]:void 0,visibility:s.visibility,rolesThatCanVote:s.vote||[],rolesThatCanViewResponses:s.responses||[],state:s.state,stoppedBy:s.stopped_by,startedAt:L(s.started_at),stoppedAt:L(s.stopped_at),createdAt:L(s.created_at)}};var Bi=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-poll-start":{this.handlePollStart(t);break}case"on-poll-stop":{this.handlePollStop(t);break}case"on-poll-stats":this.handlePollStats(t);break;default:break}}handlePollStart(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){if(this.store.getPoll(r.poll_id))return;let a=yield this.transport.signal.getPollQuestions({poll_id:r.poll_id,index:0,count:50}),o=Vi(r);o.questions=a.questions.map(({question:n,options:l,answer:u})=>y(S({},n),{options:l,answer:u})),yield this.updatePollResponses(o,!0),t.push(o),this.store.setPoll(o)}(i=this.listener)==null||i.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let a=this.store.getPoll(r.poll_id);if(a){a.state="stopped",a.stoppedAt=L(r.stopped_at),a.stoppedBy=r.stopped_by;let o=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(a,o),t.push(a)}}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(2,t))})}handlePollStats(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let a=this.store.getPoll(r.poll_id);if(!a)return;this.updatePollResult(a,r),yield this.updatePollResponses(a,!1),t.push(a)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(3,t))})}updatePollResult(e,t){var i;e.result=S({},e.result),e.result.totalUsers=t.user_count,e.result.maxUsers=t.max_user,e.result.totalResponses=t.total_response,(i=t.questions)==null||i.forEach(r=>{var o,n;let a=(o=e.questions)==null?void 0:o.find(l=>l.index===r.question);a&&(a.result=S({},a.result),a.result.correctResponses=r.correct,a.result.skippedCount=r.skipped,a.result.totalResponses=r.total,(n=r.options)==null||n.forEach((l,u)=>{var m;let p=(m=a.options)==null?void 0:m[u];p&&p.voteCount!==l&&(p.voteCount=l)}))})}updatePollResponses(e,t){return c(this,null,function*(){var r;(r=(yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t})).responses)==null||r.forEach(({response:a,peer:o,final:n})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(m=>m.index===a.question);if(!l)return;let u={id:a.response_id,questionIndex:a.question,option:a.option,options:a.options,text:a.text,responseFinal:n,peer:{peerid:o.peerid,userHash:o.hash,userid:o.userid,username:o.username},skipped:a.skipped,type:a.type,update:a.update};Array.isArray(l.responses)&&l.responses.length>0?l.responses.find(({id:m})=>m===u.id)||l.responses.push(u):l.responses=[u]})})}};var Fi=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){switch(e){case"on-role-change-request":this.handleRoleChangeRequest(t);break;case"on-track-update-request":this.handleTrackUpdateRequest(t);break;case"on-change-track-mute-state-request":this.handleChangeTrackStateRequest(t);break;default:return}}handleRoleChangeRequest(e){var i;let t={requestedBy:e.requested_by?this.store.getPeerById(e.requested_by):void 0,role:this.store.getPolicyForRole(e.role),token:e.token};(i=this.listener)==null||i.onRoleChangeRequest(t)}handleTrackUpdateRequest(e){let{requested_by:t,track_id:i,mute:r}=e,a=t?this.store.getPeerById(t):void 0,o=this.store.getLocalPeerTracks().find(l=>l.publishedTrackId===i);if(!o)return;let n=()=>{var l;(l=this.listener)==null||l.onChangeTrackStateRequest({requestedBy:a,track:o,enabled:!r})};if(r){if(o.enabled===!r)return;o.setEnabled(!r).then(n)}else n()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:a}=e,o=a?this.store.getPeerById(a):void 0,n=!r,l=this.getTracksToBeUpdated({type:t,source:i,enabled:n});if(l.length!==0)if(n)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let m of l)p.push(m.setEnabled(!1));Promise.all(p).then(()=>{var m;(m=this.listener)==null||m.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let a=this.store.getLocalPeerTracks();return e&&(a=a.filter(o=>o.type===e)),t&&(a=a.filter(o=>o.source===t)),a.filter(o=>o.enabled!==i)}};var Gi=class{constructor(e,t){this.store=e;this.listener=t;this.TAG="[RoomUpdateManager]"}handleNotification(e,t){switch(e){case"peer-list":this.onRoomState(t.room);break;case"on-rtmp-update":this.updateRTMPStatus(t);break;case"on-record-update":this.updateRecordingStatus(t);break;case"room-state":this.handlePreviewRoomState(t);break;case"room-info":this.handleRoomInfo(t);break;case"session-info":this.handleSessionInfo(t);break;case"on-hls-update":this.updateHLSStatus(t);break;default:break}}handleRoomInfo(e){let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.description=e.description,t.large_room_optimization=e.large_room_optimization,t.max_size=e.max_size,t.name=e.name}handleSessionInfo(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.sessionId=e.session_id,t.peerCount!==e.peer_count&&(t.peerCount=e.peer_count,(i=this.listener)==null||i.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",t))}handlePreviewRoomState(e){let{room:t}=e;this.onRoomState(t)}onRoomState(e){var l,u,p,m;let{recording:t,streaming:i,session_id:r,started_at:a,name:o}=e,n=this.store.getRoom();if(!n){d.w(this.TAG,"on room state - room not present");return}n.name=o,n.rtmp.running=this.isStreamingRunning((l=i==null?void 0:i.rtmp)==null?void 0:l.state),n.rtmp.startedAt=L((u=i==null?void 0:i.rtmp)==null?void 0:u.started_at),n.rtmp.state=(p=i==null?void 0:i.rtmp)==null?void 0:p.state,n.recording.server=this.getPeerListSFURecording(t),n.recording.browser=this.getPeerListBrowserRecording(t),n.recording.hls=this.getPeerListHLSRecording(t),n.hls=this.convertHls(i==null?void 0:i.hls),n.sessionId=r,n.startedAt=L(a),(m=this.listener)==null||m.onRoomUpdate("RECORDING_STATE_UPDATED",n)}isRecordingRunning(e){return e?!["none","paused","stopped","failed"].includes(e):!1}isStreamingRunning(e){return e?!["none","stopped","failed"].includes(e):!1}initHLS(e){let t=this.store.getRoom(),i={running:!0,variants:[]};return t?(e!=null&&e.variants&&e.variants.forEach((r,a)=>{var o;i.variants.push({initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[a].initialised_at),url:""})}),i):(d.w(this.TAG,"on hls - room not present"),i)}updateHLSStatus(e){var r;let t=this.store.getRoom(),i=e.variants&&e.variants.length>0?this.isStreamingRunning(e.variants[0].state):!1;if(!t){d.w(this.TAG,"on hls - room not present");return}e.enabled=i,t.hls=this.convertHls(e),(r=this.listener)==null||r.onRoomUpdate("HLS_STREAMING_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants[0].state==="initialised":!1)return this.initHLS(e);let i={running:!!(e!=null&&e.enabled),variants:[],error:this.toSdkError(e==null?void 0:e.error)};return(r=e==null?void 0:e.variants)==null||r.forEach(a=>{i.variants.push({meetingURL:a==null?void 0:a.meeting_url,url:a==null?void 0:a.url,metadata:a==null?void 0:a.metadata,startedAt:L(a==null?void 0:a.started_at),initialisedAt:L(a==null?void 0:a.initialised_at),state:a.state})}),i}getHLSRecording(e){var r,a;let t={running:!1},i=this.isRecordingRunning(e==null?void 0:e.state);return(i||(e==null?void 0:e.state)==="paused")&&(t={running:i,singleFilePerLayer:!!((r=e==null?void 0:e.hls_recording)!=null&&r.single_file_per_layer),hlsVod:!!((a=e==null?void 0:e.hls_recording)!=null&&a.hls_vod),startedAt:L(e==null?void 0:e.started_at),initialisedAt:L(e==null?void 0:e.initialised_at),state:e==null?void 0:e.state,error:this.toSdkError(e==null?void 0:e.error)}),t}getPeerListHLSRecording(e){var r,a;let t=e==null?void 0:e.hls;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),initialisedAt:L(t==null?void 0:t.initialised_at),state:t==null?void 0:t.state,singleFilePerLayer:(r=t==null?void 0:t.config)==null?void 0:r.single_file_per_layer,hlsVod:(a=t==null?void 0:t.config)==null?void 0:a.hls_vod}}getPeerListBrowserRecording(e){let t=e==null?void 0:e.browser;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}getPeerListSFURecording(e){let t=e==null?void 0:e.sfu;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}updateRecordingStatus(e){var a;let t=this.store.getRoom(),i=this.isRecordingRunning(e.state);if(!t){d.w(this.TAG,`set recording status running=${i} - room not present`);return}let r;e.type==="sfu"?(t.recording.server={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e.state},r="SERVER_RECORDING_STATE_UPDATED"):e.type==="HLS"?(t.recording.hls=this.getHLSRecording(e),r="RECORDING_STATE_UPDATED"):(t.recording.browser={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e==null?void 0:e.state},r="BROWSER_RECORDING_STATE_UPDATED"),(a=this.listener)==null||a.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,a;let t=this.store.getRoom(),i=this.isStreamingRunning(e.state);if(!t){d.w(this.TAG,"on policy change - room not present");return}if(!i){t.rtmp={running:i,state:e.state,error:this.toSdkError(e.error)},(r=this.listener)==null||r.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t);return}t.rtmp={running:i,startedAt:i?L(e.started_at):void 0,state:e.state,error:this.toSdkError(e.error)},(a=this.listener)==null||a.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new T(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var $i=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){e==="on-metadata-change"&&this.handleMetadataChange(t)}handleMetadataChange(e){var i;let t=e.values.map(r=>({key:r.key,value:r.data,updatedAt:L(r.updated_at),updatedBy:r.updated_by?this.store.getPeerById(r.updated_by):void 0}));(i=this.listener)==null||i.onSessionStoreUpdate(t)}};var Wi=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-whiteboard-update":{this.handleWhiteboardUpdate(t);break}default:break}}handleWhiteboardUpdate(e){return c(this,null,function*(){var n;let t=this.store.getLocalPeer(),i=this.store.getWhiteboard(e.id),r=e.owner===(t==null?void 0:t.peerId)||e.owner===(t==null?void 0:t.customerUserId),a=e.state==="open",o={id:e.id,title:e.title,attributes:e.attributes};if(o.open=r?i==null?void 0:i.open:a,o.owner=o.open?e.owner:void 0,!r&&o.open){let l=yield this.transport.signal.getWhiteboard({id:e.id});o.token=l.token,o.addr=l.addr,o.permissions=l.permissions}this.store.setWhiteboard(o),(n=this.listener)==null||n.onWhiteboardUpdate(o)})}};var Ki=class{constructor(e,t,i,r,a,o){this.store=e;this.transport=i;this.listener=r;this.audioListener=a;this.connectionQualityListener=o;this.TAG="[HMSNotificationManager]";this.hasConsistentRoomStateArrived=!1;this.ignoreNotification=e=>{if(e==="peer-list")this.hasConsistentRoomStateArrived=!0;else if(e==="room-state")return this.hasConsistentRoomStateArrived;return!1};this.handleTrackAdd=e=>{this.trackManager.handleTrackAdd(e)};this.handleTrackRemove=e=>{this.trackManager.handleTrackRemove(e)};this.updateLocalPeer=({name:e,metadata:t})=>{let i=this.store.getLocalPeer();this.peerManager.handlePeerInfoUpdate({peer:i,name:e,data:t})};let n=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=n?new _i(this.store,t,this.transport,this.listener):new ze(this.store,t,this.listener),this.peerManager=new Oi(this.store,this.trackManager,this.listener),this.peerListManager=new Ni(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new Di(this.listener),this.policyChangeManager=new xi(this.store,t),this.requestManager=new Fi(this.store,this.listener),this.activeSpeakerManager=new Li(this.store,this.listener,this.audioListener),this.connectionQualityManager=new wi(this.store,this.connectionQualityListener),this.roomUpdateManager=new Gi(this.store,this.listener),this.sessionMetadataManager=new $i(this.store,this.listener),this.pollsManager=new Bi(this.store,this.transport,this.listener),this.whiteboardManager=new Wi(this.store,this.transport,this.listener)}setListener(e){this.listener=e,this.trackManager.listener=e,this.peerManager.listener=e,this.peerListManager.listener=e,this.broadcastManager.listener=e,this.requestManager.listener=e,this.activeSpeakerManager.listener=e,this.roomUpdateManager.listener=e,this.sessionMetadataManager.listener=e,this.pollsManager.listener=e,this.whiteboardManager.listener=e}setAudioListener(e){this.audioListener=e,this.activeSpeakerManager.audioListener=e}setConnectionQualityListener(e){this.connectionQualityListener=e,this.connectionQualityManager.listener=e}handleNotification(e,t=!1){var a,o;let i=e.method,r=e.params;["active-speakers","sfu-stats","on-connection-quality-update",void 0].includes(i)||d.d(this.TAG,`Received notification - ${i}`,{notification:r}),i==="sfu-stats"&&(a=window.HMS)!=null&&a.ON_SFU_STATS&&typeof((o=window.HMS)==null?void 0:o.ON_SFU_STATS)=="function"&&window.HMS.ON_SFU_STATS(e.params),!this.ignoreNotification(i)&&(this.roomUpdateManager.handleNotification(i,r),this.peerManager.handleNotification(i,r),this.requestManager.handleNotification(i,r),this.peerListManager.handleNotification(i,r,t),this.broadcastManager.handleNotification(i,r),this.sessionMetadataManager.handleNotification(i,r),this.pollsManager.handleNotification(i,r),this.whiteboardManager.handleNotification(i,r),this.handleIsolatedMethods(i,r))}handleIsolatedMethods(e,t){switch(e){case"on-track-add":{this.trackManager.handleTrackMetadataAdd(t);break}case"on-track-update":{this.trackManager.handleTrackUpdate(t);break}case"on-track-remove":{if(!t.peer){d.d(this.TAG,`Ignoring sfu notification - ${e}`,{notification:t});return}this.trackManager.handleTrackRemovedPermanently(t);break}case"on-track-layer-update":{this.trackManager.handleTrackLayerUpdate(t);break}case"active-speakers":this.activeSpeakerManager.handleActiveSpeakers(t);break;case"on-connection-quality-update":this.connectionQualityManager.handleQualityUpdate(t);break;case"on-policy-change":this.policyChangeManager.handlePolicyChange(t);break;default:break}}};var qi=class{constructor(e){this.transport=e;this.observedKeys=new Set}get(e){return c(this,null,function*(){let{data:t,updated_at:i}=yield this.transport.signal.getSessionMetadata(e);return{value:t,updatedAt:L(i)}})}set(e,t){return c(this,null,function*(){let{data:i,updated_at:r}=yield this.transport.signal.setSessionMetadata({key:e,data:t}),a=L(r);return{value:i,updatedAt:a}})}observe(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(e.forEach(i=>this.observedKeys.add(i)),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}unobserve(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(this.observedKeys=new Set([...this.observedKeys].filter(i=>!e.includes(i))),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}};var ji=class{constructor(e,t,i="",r="",a="https://prod-init.100ms.live/init",o=!1){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=a;this.autoSubscribeVideo=o}};var K=(a=>(a[a.ConnectFailed=0]="ConnectFailed",a[a.SignalDisconnect=1]="SignalDisconnect",a[a.JoinWSMessageFailed=2]="JoinWSMessageFailed",a[a.PublishIceConnectionFailed=3]="PublishIceConnectionFailed",a[a.SubscribeIceConnectionFailed=4]="SubscribeIceConnectionFailed",a))(K||{}),ba={0:[],1:[],2:[1],3:[1],4:[1]};var Ji=(n=>(n.Disconnected="Disconnected",n.Connecting="Connecting",n.Joined="Joined",n.Preview="Preview",n.Failed="Failed",n.Reconnecting="Reconnecting",n.Leaving="Leaving",n))(Ji||{});var Qi=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var zi=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(n){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxFailedRetries:a=5,changeState:o=!0}){yield this.scheduleTask({category:e,error:t,changeState:o,task:i,originalState:r,maxFailedRetries:a})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(l){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:a,maxFailedRetries:o=5,failedRetryCount:n=0}){if(d.d(this.TAG,"schedule: ",{category:K[e],error:t}),n===0){let f=this.inProgress.get(e);if(f){d.d(this.TAG,`schedule: Already a task for ${K[e]} scheduled, waiting for its completion`),yield f.promise;return}let R=new Qi((b,G)=>{});this.inProgress.set(e,R),this.sendEvent(t,e)}let u=!1,p=ba[e];for(let f in p){let R=p[parseInt(f)];try{let b=this.inProgress.get(R);b&&(d.d(this.TAG,`schedule: Suspending retry task of ${K[e]}, waiting for ${K[R]} to recover`),yield b.promise,d.d(this.TAG,`schedule: Resuming retry task ${K[e]} as it's dependency ${K[R]} is recovered`))}catch(b){d.d(this.TAG,`schedule: Stopping retry task of ${K[e]} as it's dependency ${K[R]} failed to recover`),u=!0;break}}if(n>=o||u){if(t.description+=`. [${K[e]}] Could not recover after ${n} tries`,u&&(t.description+=` Could not recover all of it's required dependencies - [${p.map(f=>K[f]).toString()}]`),t.isTerminal=!0,this.inProgress.delete(e),this.sendEvent(t,e),this.reset(),i)this.onStateChange("Failed",t);else throw t;return}i&&this.onStateChange("Reconnecting",t);let m=this.getDelayForRetryCount(e,n);d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Scheduling retry task in ${m}ms`);let g;try{g=yield this.setTimeoutPromise(r,m)}catch(f){g=!1,d.w(this.TAG,`[${K[e]}] Un-caught exception ${f.name} in retry-task, initiating retry`,f)}if(g){let f=this.inProgress.get(e);this.inProgress.delete(e),f==null||f.resolve(n),i&&this.inProgress.size===0&&this.onStateChange(a),d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Recovered \u267B\uFE0F`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:a,maxFailedRetries:o,failedRetryCount:n+1})})}getBaseDelayForTask(e,t){return e===2?2:Math.pow(2,t)}getDelayForRetryCount(e,t){let i=this.getBaseDelayForTask(e,t),r=e===2?Math.random()*2:Math.random();return Math.round(Math.min(i+r,60)*1e3)}setTimeoutPromise(e,t){return c(this,null,function*(){return new Promise((i,r)=>{let a=window.setTimeout(()=>c(this,null,function*(){try{let o=yield e();o&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(a),1),i(o)}catch(o){r(o)}}),t);this.retryTaskIds.push(a)})})}};var Yi=class extends Ae{constructor(){super(100);this.localStorage=new ce("hms-analytics");this.localStorage.clear(),this.initLocalStorageQueue()}enqueue(t){super.enqueue(t),this.localStorage.set(this.storage)}dequeue(){let t=super.dequeue();return this.localStorage.set(this.storage),t}initLocalStorageQueue(){var t;(t=this.localStorage.get())==null||t.forEach(i=>{let r=new I(i);super.enqueue(r)})}};var Xi=class{constructor(){this.TAG="[AnalyticsTransport]"}sendEvent(e){try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){d.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(d.d(this.TAG,"Flushing failed events",this.failedEvents);this.failedEvents.size()>0;){let i=this.failedEvents.dequeue();i&&(((t=i.metadata)==null?void 0:t.peer.peer_id)===e||!i.metadata.peer.peer_id?this.sendSingleEvent(i):ve.sendEvent(i))}}catch(i){d.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),d.d(this.TAG,"Sent event",e.name,e)}catch(t){throw d.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var Zi=class extends Xi{constructor(t){super();this.transportProvider=t;this.failedEvents=new Yi}};var Ye=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.sampleWindowSize=i;this.pushInterval=r;this.shouldSendEvent=!1;this.sequenceNum=1;this.stop=()=>{this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1};this.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>d.e("[StatsAnanlytics]",e.message)))}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield X(this.pushInterval*1e3),this.sendEvent()})}},Xe=class{constructor({track:e,ssrc:t,rid:i,kind:r,sampleWindowSize:a}){this.samples=[];this.tempStats=[];this.track=e,this.ssrc=t,this.rid=i,this.kind=r,this.track_id=this.track.trackId,this.source=this.track.source,this.sampleWindowSize=a}push(e){this.tempStats.push(e),this.shouldCreateSample()&&(this.samples.push(this.createSample()),this.tempStats.length=0)}getLatestStat(){return this.tempStats[this.tempStats.length-1]}getFirstStat(){return this.tempStats[0]}calculateSum(e){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((i,r)=>i+(r[e]||0),0)}calculateAverage(e,t=!0){let i=this.calculateSum(e),r=i!==void 0?i/this.tempStats.length:void 0;return r?t?Math.round(r):r:void 0}calculateDifferenceForSample(e){let t=Number(this.tempStats[0][e])||0;return(Number(this.getLatestStat()[e])||0)-t}calculateInstancesOfHigh(e,t){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((r,a)=>r+((a[e]||0)>t?1:0),0)}},er=(s,e)=>s&&e&&(s.frameWidth!==e.frameWidth||s.frameHeight!==e.frameHeight),tr=(s,e)=>s&&e&&s.enabled!==e.enabled,_t=s=>Object.entries(s).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var Nt=class extends Ye{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,a;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.toAnalytics())}),{audio:t,video:i,joined_at:(a=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:a.getTime(),sequence_num:this.sequenceNum++,max_window_sec:30}}sendEvent(){this.eventBus.analytics.publish(M.publishStats(this.toAnalytics()))}handleStatsUpdate(t){let i=t.getLocalTrackStats();Object.keys(i).forEach(r=>{let a=i[r],o=this.store.getLocalPeerTracks().find(n=>n.getTrackIDBeingSent()===r);Object.keys(a).forEach(n=>{var p,m,g,f,R;let l=a[n],u=o&&this.getTrackIdentifier(o==null?void 0:o.trackId,l);if(u&&this.trackAnalytics.has(u))(g=this.trackAnalytics.get(u))==null||g.push(y(S({},l),{availableOutgoingBitrate:(m=(p=t.getLocalPeerStats())==null?void 0:p.publish)==null?void 0:m.availableOutgoingBitrate}));else if(o){let b=new as({track:o,sampleWindowSize:this.sampleWindowSize,rid:l.rid,ssrc:l.ssrc.toString(),kind:l.kind});b.push(y(S({},l),{availableOutgoingBitrate:(R=(f=t.getLocalPeerStats())==null?void 0:f.publish)==null?void 0:R.availableOutgoingBitrate})),this.trackAnalytics.set(this.getTrackIdentifier(o==null?void 0:o.trackId,l),b)}})})}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},as=class extends Xe{constructor(){super(...arguments);this.samples=[];this.createSample=()=>{let t=this.getLatestStat(),i=t.qualityLimitationDurations,r=i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other},a=t.frameHeight?{height_px:this.getLatestStat().frameHeight,width_px:this.getLatestStat().frameWidth}:void 0,o=this.calculateAverage("jitter",!1),n=o?Math.round(o*1e3):void 0,l=this.calculateAverage("roundTripTime",!1),u=l?Math.round(l*1e3):void 0;return _t({timestamp:Date.now(),avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:this.calculateDifferenceForSample("packetsLost"),total_packets_sent:this.calculateDifferenceForSample("packetsSent"),total_packet_sent_delay_sec:parseFloat(this.calculateDifferenceForSample("totalPacketSendDelay").toFixed(4)),total_fir_count:this.calculateDifferenceForSample("firCount"),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_ms:n,avg_round_trip_time_ms:u,total_quality_limitation:r,resolution:a})};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||tr(i,r)||i.kind==="video"&&er(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var Ot=class extends Ye{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,a;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.toAnalytics())}),{audio:t,video:i,joined_at:(a=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:a.getTime(),sequence_num:this.sequenceNum++,max_window_sec:10}}sendEvent(){this.eventBus.analytics.publish(M.subscribeStats(this.toAnalytics()))}handleStatsUpdate(t){let i=t.getAllRemoteTracksStats();Object.keys(i).forEach(r=>{var n;let a=i[r],o=this.store.getTrackById(r);if(this.trackAnalytics.has(r))(n=this.trackAnalytics.get(r))==null||n.push(S({},a));else if(o){let l=new ns({track:o,sampleWindowSize:this.sampleWindowSize,ssrc:a.ssrc.toString(),kind:a.kind});l.push(S({},a)),this.trackAnalytics.set(r,l)}})}},ns=class extends Xe{constructor(){super(...arguments);this.samples=[];this.createSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),fec_packets_discarded:this.calculateDifferenceForSample("fecPacketsDiscarded"),fec_packets_received:this.calculateDifferenceForSample("fecPacketsReceived"),total_samples_duration:this.calculateDifferenceForSample("totalSamplesDuration"),total_packets_received:this.calculateDifferenceForSample("packetsReceived"),total_packets_lost:this.calculateDifferenceForSample("packetsLost"),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount")};if(t.kind==="video")return _t(r);{let a=(t.concealedSamples||0)-(t.silentConcealedSamples||0)-((i.concealedSamples||0)-(i.silentConcealedSamples||0));return _t(Object.assign(r,{audio_concealed_samples:a,audio_level:this.calculateInstancesOfHigh("audioLevel",.05),audio_total_samples_received:this.calculateDifferenceForSample("totalSamplesReceived"),audio_concealment_events:this.calculateDifferenceForSample("concealmentEvents")}))}};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===10||tr(i,r)||i.kind==="video"&&er(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var ir=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(ir||{});var xt=it(require("sdp-transform"));function Ra(s,e){var r;let t=xt.parse(s.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return s;let i=e?Array.from(e.values()):[];return t.media.forEach(a=>{var l,u,p;let o=(l=a.msid)==null?void 0:l.split(" ")[0],n=(u=i.find(m=>m.type===a.type&&m.stream_id===o))==null?void 0:u.track_id;n&&(a.msid=(p=a.msid)==null?void 0:p.replace(/\s(.+)/,` ${n}`))}),{type:s.type,sdp:xt.write(t)}}function Ha(s,e){var a;if(!(s!=null&&s.sdp)||!e)return;let i=xt.parse(s.sdp).media.find(o=>se(o.mid)&&parseInt(o.mid)===parseInt(e));return(a=i==null?void 0:i.msid)==null?void 0:a.split(" ")[1]}function Ia(s){return s.sdp.includes("usedtx=1")?s:{type:s.type,sdp:s.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var Me="[HMSConnection]",Ne=class{constructor(e,t){this.candidates=new Array;this.role=e,this.signal=t}get iceConnectionState(){return this.nativeConnection.iceConnectionState}get connectionState(){return this.nativeConnection.connectionState}get action(){return this.role===0?"PUBLISH":"SUBSCRIBE"}addTransceiver(e,t){return this.nativeConnection.addTransceiver(e,t)}createOffer(e,t){return c(this,null,function*(){try{let i=yield this.nativeConnection.createOffer(t);return d.d(Me,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Ia(Ra(i,e))}catch(i){throw h.WebrtcErrors.CreateOfferFailed(this.action,i.message)}})}createAnswer(e=void 0){return c(this,null,function*(){try{let t=yield this.nativeConnection.createAnswer(e);return d.d(Me,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw h.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}setLocalDescription(e){return c(this,null,function*(){try{d.d(Me,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(t){throw h.WebrtcErrors.SetLocalDescriptionFailed(this.action,t.message)}})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(Me,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw h.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(Me,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(Me,`[role=${this.role}] addIceCandidate candidate=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.addIceCandidate(e)})}get remoteDescription(){return this.nativeConnection.remoteDescription}getSenders(){return this.nativeConnection.getSenders()}logSelectedIceCandidatePairs(){try{(this.role===0?this.getSenders():this.getReceivers()).forEach(t=>{var r;let i=(r=t.track)==null?void 0:r.kind;if(t.transport){let a=t.transport.iceTransport,o=()=>{typeof a.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=a.getSelectedCandidatePair(),d.d(Me,`${ir[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2)))};typeof a.onselectedcandidatepairchange=="function"&&(a.onselectedcandidatepairchange=o),o()}})}catch(e){d.w(Me,`Error in logging selected ice candidate pair for ${ir[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e){return c(this,null,function*(){let t=e.settings.maxBitrate,i=e instanceof U&&e.settings.maxFramerate,r=this.getSenders().find(a=>{var o;return((o=a==null?void 0:a.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(r){let a=r.getParameters();a.encodings.length===1&&(t&&(a.encodings[0].maxBitrate=t*1e3),i&&(a.encodings[0].maxFramerate=i)),yield r.setParameters(a)}else d.w(Me,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){return c(this,null,function*(){this.nativeConnection.close()})}getReceivers(){return this.nativeConnection.getReceivers()}};var Ut=class extends Ne{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(li,{protocol:"SCTP"}),this.channel.onerror=a=>d.e(this.TAG,`publish data channel onerror ${a}`,a),this.nativeConnection.onicecandidate=({candidate:a})=>{a&&t.trickle(this.role,a)},this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState),this.nativeConnection.sctp&&(this.nativeConnection.sctp.transport.onstatechange=()=>{var a;this.observer.onDTLSTransportStateChange((a=this.nativeConnection.sctp)==null?void 0:a.transport.state)},this.nativeConnection.sctp.transport.onerror=a=>{var o;this.observer.onDTLSTransportError(new Error((o=a==null?void 0:a.error)==null?void 0:o.errorDetail)||"DTLS Transport failed")})}}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var Ca=it(require("eventemitter2")),La=require("uuid");var Vt=class{constructor(e,t,i=""){this.TAG="[HMSDataChannel]";this.nativeChannel=e,this.observer=t,this.metadata=i,e.onmessage=r=>{this.observer.onMessage(r.data)}}get id(){return this.nativeChannel.id}get label(){return this.nativeChannel.label}get readyState(){return this.nativeChannel.readyState}send(e){d.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var Bt=class s extends Ne{constructor(t,i,r,a){super(1,t);this.isFlagEnabled=r;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.pendingMessageQueue=[];this.eventEmitter=new Ca.default({maxListeners:60});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(d.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i)=>c(this,null,function*(){var a;((a=this.apiChannel)==null?void 0:a.readyState)!=="open"&&(yield this.eventEmitter.waitFor("open"));let r;for(let o=0;o<this.MAX_RETRIES;o++){this.apiChannel.send(t),r=yield this.waitForResponse(i);let n=r.error;if(n){if(n.code===404){d.d(this.TAG,`Track not found ${i}`,{request:t,try:o+1,error:n});break}if(d.d(this.TAG,`Failed sending ${i}`,{request:t,try:o+1,error:n}),!(n.code/100===5||n.code===429))throw Error(`code=${n.code}, message=${n.message}`);let u=(2+Math.random()*2)*1e3;yield le(u)}else break}return r});this.waitForResponse=t=>c(this,null,function*(){let i=yield this.eventEmitter.waitFor("message",function(a){return a.includes(t)}),r=JSON.parse(i[0]);return d.d(this.TAG,`response for ${t} -`,JSON.stringify(r,null,2)),r});this.observer=a,this.nativeConnection=new RTCPeerConnection(i),this.initNativeConnectionCallbacks()}initNativeConnectionCallbacks(){this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState)},this.nativeConnection.ondatachannel=t=>{t.channel.label===li&&(this.apiChannel=new Vt(t.channel,{onMessage:i=>{this.eventEmitter.emit("message",i),this.observer.onApiChannelMessage(i)}},`role=${this.role}`),t.channel.onopen=this.handlePendingApiMessages)},this.nativeConnection.onicecandidate=t=>{t.candidate!==null&&this.signal.trickle(this.role,t.candidate)},this.nativeConnection.ontrack=t=>{var u;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let p=new me(i,this);this.remoteStreams.set(r,p)}i.addEventListener("removetrack",p=>{if(p.track.id!==t.track.id)return;let m=a.tracks.findIndex(g=>{var f;return g.nativeTrack.id===p.track.id&&t.transceiver.mid===((f=g.transceiver)==null?void 0:f.mid)});if(m>=0){let g=a.tracks[m];this.observer.onTrackRemove(g),a.tracks.splice(m,1),a.tracks.length===0&&this.remoteStreams.delete(r)}});let a=this.remoteStreams.get(r),o=t.track.kind==="audio"?te:_,n=new o(a,t.track);t.track.kind==="video"&&a.setVideoLayerLocally("none","addTrack","subscribeConnection"),n.transceiver=t.transceiver;let l=Ha(this.remoteDescription,(u=t.transceiver)==null?void 0:u.mid);l&&n.setSdpTrackId(l),a.tracks.push(n),this.observer.onTrackAdd(n)}}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(d.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t,i){return c(this,null,function*(){let r=(0,La.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return d.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:r};let a=JSON.stringify(S({id:i||r,jsonrpc:"2.0"},t));return this.sendMessage(a,r)})}close(){return c(this,null,function*(){var t;yield q(s.prototype,this,"close").call(this),(t=this.apiChannel)==null||t.close()})}};var rr="[InitService]",Ft=class{static handleError(e,t){switch(e.status){case 404:throw h.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw h.APIErrors.ServerErrors(t.code||e.status,"INIT",t.message||(e==null?void 0:e.statusText))}}static fetchInitConfig(o){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:a=""}){d.d(rr,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${a} `);let n=pc(r,t,i,a);try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`}});try{let u=yield l.clone().json();return this.handleError(l,u),d.d(rr,`config is ${JSON.stringify(u,null,2)}`),hc(u)}catch(u){let p=yield l.text();throw d.e(rr,"json error",u.message,p),h.APIErrors.ServerErrors(l.status,"INIT",p)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?h.APIErrors.EndpointUnreachable("INIT",u.message):u}})}};function pc(s,e,t,i){try{let r=new URL("/init",s);return i&&i.trim().length>0&&r.searchParams.set("region",i.trim()),r.searchParams.set("peer_id",e),r.searchParams.set("user_agent_v2",t),r.toString()}catch(r){let a=r;throw d.e(rr,a.name,a.message),a}}function hc(s){var e;return y(S({},s),{rtcConfiguration:y(S({},s.rtcConfiguration),{iceServers:(e=s.rtcConfiguration)==null?void 0:e.ice_servers})})}var Da=require("uuid");var Gt=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ae(5);this.isJoinCompleted=!1;this.pendingTrickle=[];this.socket=null;this.callbacks=new Map;this._isConnected=!1;this.id=0;this.onCloseHandler=()=>{};this.resolvePingOnAnyResponse=()=>{this.callbacks.forEach((e,t)=>{var i;((i=e.metadata)==null?void 0:i.method)==="ping"&&(e.resolve({timestamp:Date.now()}),this.callbacks.delete(t))})};this.offlineListener=()=>{d.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{d.d(this.TAG,"Window network online"),this.observer.onNetworkOnline()};this.observer=e,window.addEventListener("offline",this.offlineListener),window.addEventListener("online",this.onlineListener),this.onMessageHandler=this.onMessageHandler.bind(this)}get isConnected(){return this._isConnected}setIsConnected(e,t=""){d.d(this.TAG,`isConnected set id: ${this.id}, oldValue: ${this._isConnected}, newValue: ${e}`),this._isConnected!==e&&(this._isConnected&&!e?(this._isConnected=e,this.rejectPendingCalls(t),this.observer.onOffline(t)):!this._isConnected&&e&&(this._isConnected=e,this.observer.onOnline()))}getPongResponseTimes(){return this.pongResponseTimes.toList()}internalCall(e,t){return c(this,null,function*(){var a;let i=(0,Da.v4)(),r={method:e,params:t,id:i,jsonrpc:"2.0"};(a=this.socket)==null||a.send(JSON.stringify(r));try{return yield new Promise((n,l)=>{this.callbacks.set(i,{resolve:n,reject:l,metadata:{method:e}})})}catch(o){if(o instanceof T)throw o;let n=o;throw h.WebsocketMethodErrors.ServerErrors(Number(n.code),Pr(e),n.message)}})}notify(e,t){var r,a;let i={method:e,params:t};((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN&&((a=this.socket)==null||a.send(JSON.stringify(i)))}open(e){return new Promise((t,i)=>{let r=!1;this.socket&&(this.socket.close(),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)),this.socket=new WebSocket(e);let a=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(h.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=n=>{d.w(`Websocket closed code=${n.code}`),r?this.setIsConnected(!1,`code: ${n.code}${n.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(h.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${n.code}`)))},this.socket.addEventListener("error",a);let o=()=>{var n,l;r=!0,t(),this.setIsConnected(!0),this.id++,(n=this.socket)==null||n.removeEventListener("open",o),(l=this.socket)==null||l.removeEventListener("error",a),this.pingPongLoop(this.id)};this.socket.addEventListener("open",o),this.socket.addEventListener("close",this.onCloseHandler),this.socket.addEventListener("message",this.onMessageHandler)})}close(){return c(this,null,function*(){window.removeEventListener("offline",this.offlineListener),window.removeEventListener("online",this.onlineListener),this.socket?(this.socket.close(1e3,"Normal Close"),this.setIsConnected(!1,"code: 1000, normal websocket close"),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)):this.setIsConnected(!1,"websocket not connected yet")})}join(e,t,i,r,a,o,n){return c(this,null,function*(){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:n,server_sub_degrade:r,simulcast:a,onDemandTracks:o},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:m})=>this.trickle(p,m)),this.pendingTrickle.length=0,d.d(this.TAG,`join: response=${JSON.stringify(u,null,1)}`),u})}trickle(e,t){this.isJoinCompleted?this.notify("trickle",{target:e,candidate:t}):this.pendingTrickle.push({target:e,candidate:t})}offer(e,t){return c(this,null,function*(){return yield this.call("offer",{desc:e,tracks:Object.fromEntries(t)})})}answer(e){this.notify("answer",{desc:e})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(){this.notify("leave",{})}endRoom(e,t){return c(this,null,function*(){yield this.call("end-room",{lock:e,reason:t})})}sendEvent(e){if(!this.isConnected)throw Error(`${this.TAG} not connected. Could not send event ${e}`);this.notify("analytics",e.toSignalParams())}ping(e){let t=Date.now(),i=new Promise(a=>{setTimeout(()=>{a(Date.now()-t)},e+1)}),r=this.internalCall("ping",{timestamp:t}).then(()=>Date.now()-t).catch(()=>Date.now()-t);return Promise.race([i,r])}requestRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}requestBulkRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}acceptRoleChangeRequest(e){return c(this,null,function*(){yield this.call("role-change",e)})}requestTrackStateChange(e){return c(this,null,function*(){yield this.call("track-update-request",e)})}requestMultiTrackStateChange(e){return c(this,null,function*(){yield this.call("change-track-mute-state-request",e)})}removePeer(e){return c(this,null,function*(){yield this.call("peer-leave-request",e)})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.call("rtmp-start",S({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",S({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",S({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",S({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",S({},e))})}getPeer(e){return c(this,null,function*(){yield this.call("get-peer",S({},e))})}joinGroup(e){return c(this,null,function*(){return yield this.call("group-join",{name:e})})}leaveGroup(e){return c(this,null,function*(){return yield this.call("group-leave",{name:e})})}addToGroup(e,t){return c(this,null,function*(){yield this.call("group-add",{name:t,peer_id:e})})}removeFromGroup(e,t){return c(this,null,function*(){yield this.call("group-remove",{name:t,peer_id:e})})}peerIterNext(e){return c(this,null,function*(){return yield this.call("peer-iter-next",e)})}findPeers(e){return c(this,null,function*(){return yield this.call("find-peer",e)})}setSessionMetadata(e){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",S({},e))}listenMetadataChange(e){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to observe session store key due to network disconnection");return this.call("listen-metadata-change",{keys:e})}getSessionMetadata(e){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("get-metadata",{key:e})}setPollInfo(e){return this.call("poll-info-set",S({},e))}getPollInfo(e){return this.call("poll-info-get",S({},e))}setPollQuestions(e){return this.call("poll-questions-set",S({},e))}startPoll(e){return this.call("poll-start",S({},e))}stopPoll(e){return this.call("poll-stop",S({},e))}getPollQuestions(e){return this.call("poll-questions-get",S({},e))}setPollResponses(e){return this.call("poll-response",S({},e))}getPollResponses(e){return this.call("poll-responses",S({},e))}getPollsList(e){return this.call("poll-list",S({},e))}getPollResult(e){return this.call("poll-result",S({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",S({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",S({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",S({},e))}validateConnection(){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to send message due to network disconnection")}onMessageHandler(e){let t=e.data,i=JSON.parse(t);if(this.resolvePingOnAnyResponse(),i.id)this.handleResponseWithId(i);else if(i.method)this.handleResponseWithMethod(i);else throw Error(`WebSocket message has no 'method' or 'id' field, message=${i}`)}handleResponseWithId(e){let t=e,i=t.id;if(this.callbacks.has(i)){let r=this.callbacks.get(i);this.callbacks.delete(i),t.result?r.resolve(t.result):r.reject(t.error)}else this.observer.onNotification(t)}handleResponseWithMethod(e){switch(e.method){case"offer":this.observer.onOffer(e.params);break;case"trickle":this.observer.onTrickle(e.params);break;case"on-error":this.observer.onServerError(h.WebsocketMethodErrors.ServerErrors(Number(e.params.code),"on-error",e.params.message));break;case"on-warning":d.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,a,o,n;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(a=t.metadata)==null?void 0:a.method}, id=${i}`),t.reject(h.WebSocketConnectionErrors.WebSocketConnectionLost((o=t.metadata)!=null&&o.method?Pr((n=t.metadata)==null?void 0:n.method):"RECONNECT_SIGNAL",e)),this.callbacks.delete(i))})}pingPongLoop(e){return c(this,null,function*(){var i,r;let t=((i=window.HMS)==null?void 0:i.PING_TIMEOUT)||12e3;if(this.isConnected){let a=yield this.ping(t);this.pongResponseTimes.enqueue(a),a>t?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${_s()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>this.pingPongLoop(e),((r=window.HMS)==null?void 0:r.PING_INTERVAL)||3e3)}})}call(e,t){return c(this,null,function*(){let r=h.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`);this.validateConnection();let a;for(a=1;a<=3;a++)try{return d.d(this.TAG,`Try number ${a} sending ${e}`,t),yield this.internalCall(e,t)}catch(o){if(r=o,d.e(this.TAG,`Failed sending ${e} try: ${a}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429))break;let l=(2+Math.random()*2)*1e3;yield le(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(a,3)} retries`,{method:e,params:t,error:r}),r})}};var wa=()=>{if(!N||typeof navigator.connection=="undefined")return;let s=navigator.connection;return{downlink:s.downlink,downlinkMax:s.downlinkMax,effectiveType:s.effectiveType,rtt:s.rtt,saveData:s.saveData,type:s.type}};var P="[HMSTransport]:",$t=class{constructor(e,t,i,r,a,o){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=a;this.analyticsTimer=o;this.state="Disconnected";this.trackStates=new Map;this.publishConnection=null;this.subscribeConnection=null;this.maxSubscribeBitrate=0;this.joinRetryCount=0;this.callbacks=new Map;this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;yield this.subscribeConnection.setRemoteDescription(e),d.d(P,`[SUBSCRIBE] Adding ${this.subscribeConnection.candidates.length} ice-candidates`,this.subscribeConnection.candidates);for(let i of this.subscribeConnection.candidates)yield this.subscribeConnection.addIceCandidate(i);this.subscribeConnection.candidates.length=0;let t=yield this.subscribeConnection.createAnswer();yield this.subscribeConnection.setLocalDescription(t),this.signal.answer(t),d.d(P,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(P,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t),this.state="Failed";let i;t instanceof T?i=t:i=h.GenericErrors.Unknown("PUBLISH",t.message),this.observer.onFailure(i),this.eventBus.analytics.publish(M.subscribeFail(i))}}),onTrickle:e=>c(this,null,function*(){let t=e.target===0?this.publishConnection:this.subscribeConnection;t!=null&&t.remoteDescription?yield t.addIceCandidate(e.candidate):t==null||t.candidates.push(e.candidate)}),onNotification:e=>this.observer.onNotification(e),onServerError:e=>c(this,null,function*(){yield this.observer.onStateChange("Failed",e)}),onFailure:e=>{this.joinParameters&&this.retryScheduler.schedule({category:1,error:e,task:this.retrySignalDisconnectTask,originalState:this.state})},onOffline:e=>c(this,null,function*(){d.d(P,"socket offline",Ji[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(P,"socket online",Ji[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new Gt(this.signalObserver);this.analyticsSignalTransport=new Zi(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.publishConnectionObserver={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:e=>{var r,a,o;if((e==="failed"?d.w.bind(d):d.d.bind(d))(P,`Publisher on dtls transport state change: ${e}`),!e||this.lastPublishDtlsState===e||(this.lastPublishDtlsState=e,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),e!=="connecting"&&e!=="failed"))return;let i=(o=(a=(r=this.initConfig)==null?void 0:r.config)==null?void 0:a.dtlsStateTimeouts)==null?void 0:o[e];!i||i<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var l;let n=(l=this.publishConnection)==null?void 0:l.nativeConnection.connectionState;if(n&&e&&n===e){let u=h.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${e} timeout:${i}ms`,!0);this.eventBus.analytics.publish(M.disconnect(u)),this.observer.onFailure(u)}},i))},onDTLSTransportError:e=>{d.e(P,`onDTLSTransportError ${e.name} ${e.message}`,e),this.eventBus.analytics.publish(M.disconnect(e))},onIceConnectionChange:e=>c(this,null,function*(){(e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Publish ice connection state change: ${e}`)}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,a,o,n;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Publish connection state change: ${e}`),e==="connected"&&((i=this.publishConnection)==null||i.logSelectedIceCandidatePairs()),e==="disconnected"&&setTimeout(()=>{var l,u,p,m,g;((l=this.publishConnection)==null?void 0:l.connectionState)==="disconnected"&&this.handleIceConnectionFailure(0,h.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(p=(u=this.publishConnection)==null?void 0:u.selectedCandidatePair)==null?void 0:p.local.candidate}; remote candidate - ${(g=(m=this.publishConnection)==null?void 0:m.selectedCandidatePair)==null?void 0:g.remote.candidate}`))},5e3),e==="failed"&&(yield this.handleIceConnectionFailure(0,h.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(a=(r=this.publishConnection)==null?void 0:r.selectedCandidatePair)==null?void 0:a.local.candidate}; remote candidate - ${(n=(o=this.publishConnection)==null?void 0:o.selectedCandidatePair)==null?void 0:n.remote.candidate}`)))})};this.subscribeConnectionObserver={onApiChannelMessage:e=>{this.observer.onNotification(JSON.parse(e))},onTrackAdd:e=>{d.d(P,"[Subscribe] onTrackAdd",`${e}`),this.observer.onTrackAdd(e)},onTrackRemove:e=>{d.d(P,"[Subscribe] onTrackRemove",`${e}`),this.observer.onTrackRemove(e)},onIceConnectionChange:e=>c(this,null,function*(){if((e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Subscribe ice connection state change: ${e}`),e==="connected"){let i=this.callbacks.get(qe);this.callbacks.delete(qe),i&&i.promise.resolve(!0)}}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,a,o;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Subscribe connection state change: ${e}`),e==="failed"&&(yield this.handleIceConnectionFailure(1,h.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(r=(i=this.subscribeConnection)==null?void 0:i.selectedCandidatePair)==null?void 0:r.local.candidate}; remote candidate - ${(o=(a=this.subscribeConnection)==null?void 0:a.selectedCandidatePair)==null?void 0:o.remote.candidate}`))),e==="disconnected"&&setTimeout(()=>{var n,l,u,p,m;((n=this.subscribeConnection)==null?void 0:n.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,h.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local.candidate}; remote candidate - ${(m=(p=this.subscribeConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:m.remote.candidate}`))},5e3),e==="connected"&&this.handleSubscribeConnectionConnected()})};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(P,"Local peer role updated to webrtc role, creating PeerConnections and performing inital publish negotiation \u23F3"),this.createPeerConnections(),yield this.negotiateOnFirstPublish())});this.retryPublishIceFailedTask=()=>c(this,null,function*(){if(this.publishConnection){let e=new Promise((t,i)=>{this.callbacks.set(Ke,{promise:{resolve:t,reject:i},action:"RESTART_ICE",extra:{}})});yield this.performPublishRenegotiation({iceRestart:this.publishConnection.connectionState!=="connected"}),yield e}return!0});this.retrySubscribeIceFailedTask=()=>c(this,null,function*(){if(this.subscribeConnection&&this.subscribeConnection.connectionState!=="connected"){let e=new Promise((i,r)=>{this.callbacks.set(qe,{promise:{resolve:i,reject:r},action:"RESTART_ICE",extra:{}})}),t=new Promise(i=>{setTimeout(i,6e4,!1)});return Promise.race([e,t])}return!0});this.retrySignalDisconnectTask=()=>c(this,null,function*(){var t;d.d(P,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId));let e=(t=this.store.getRoom())!=null&&t.joinedAt?this.signal.isConnected&&(yield this.retryPublishIceFailedTask()):this.signal.isConnected;return this.signal.trackUpdate(this.trackStates),e});var l,u;this.webrtcInternals=new pi(this.store,this.eventBus,(l=this.publishConnection)==null?void 0:l.nativeConnection,(u=this.subscribeConnection)==null?void 0:u.nativeConnection);let n=(p,m)=>c(this,null,function*(){p!==this.state&&(this.state=p,yield this.observer.onStateChange(this.state,m))});this.retryScheduler=new zi(n,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(p=>{var g,f;let m=((f=(g=p.getLocalPeerStats())==null?void 0:g.subscribe)==null?void 0:f.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,m)}),this.eventBus.localAudioEnabled.subscribe(({track:p})=>this.trackUpdate(p)),this.eventBus.localVideoEnabled.subscribe(({track:p})=>this.trackUpdate(p))}getWebrtcInternals(){return this.webrtcInternals}isFlagEnabled(e){var r;let t=(r=this.initConfig)==null?void 0:r.config;return((t==null?void 0:t.enabledFlags)||[]).includes(e)}preview(e,t,i,r,a=!1){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,a);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,a=!1){return c(this,null,function*(){d.d(P,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,a)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,a),yield this.initRtcStatsMonitor(),d.d(P,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(P,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let n=o;throw n.isTerminal=n.isTerminal||n.code===500,yield this.observer.onStateChange(this.state,n),n}d.d(P,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,a=!1){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new ji(e,i,r.name,r.metaData,t,a);try{return yield this.internalConnect(e,t,i)}catch(o){if(o instanceof T&&([v.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,v.WebSocketConnectionErrors.FAILED_TO_CONNECT,v.WebSocketConnectionErrors.ABNORMAL_CLOSE,v.APIErrors.ENDPOINT_UNREACHABLE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429"))){let l=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:l,originalState:this.state,maxFailedRetries:5,changeState:!1})}else throw o}})}leave(e){return c(this,null,function*(){var t,i,r,a,o;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(P,"leaving in transport");try{if(this.state="Leaving",(t=this.publishStatsAnalytics)==null||t.stop(),(i=this.subscribeStatsAnalytics)==null||i.stop(),(r=this.webrtcInternals)==null||r.cleanup(),yield(a=this.publishConnection)==null?void 0:a.close(),yield(o=this.subscribeConnection)==null?void 0:o.close(),e)try{this.signal.leave(),d.d(P,"signal leave done")}catch(n){d.w(P,"failed to send leave on websocket to server",n)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(n){this.eventBus.analytics.publish(M.disconnect(n)),d.e(P,"leave: FAILED \u274C",n)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){for(let t of e)try{yield this.publishTrack(t)}catch(i){this.eventBus.analytics.publish(M.publish({devices:this.deviceManager.getDevices(),error:i}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}trackUpdate(e){let i=Array.from(this.trackStates.values()).find(r=>e.type===r.type&&e.source===r.source);if(i){let r=new Dt(y(S({},i),{mute:!e.enabled}));this.trackStates.set(i.track_id,r),d.d(P,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[i.track_id,r]]))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(P,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Dt(e));let t=new Promise((a,o)=>{this.callbacks.set(Ke,{promise:{resolve:a,reject:o},action:"PUBLISH",extra:{}})}),i=e.stream;i.setConnection(this.publishConnection);let r=this.store.getSimulcastLayers(e.source);i.addTransceiver(e,r),d.time(`publish-${e.trackId}-${e.type}`),yield t,d.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{d.d(P,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof U?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(a=>d.w(P,"Failed setting maxBitrate and maxFramerate",a)),e.isPublished=!0,d.d(P,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(P,`\u23F3 unpublishTrack: trackId=${e.trackId}`,`${e}`),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId))this.trackStates.delete(e.publishedTrackId);else{let a=Array.from(this.trackStates.values()).find(o=>e.type===o.type&&e.source===o.source);a&&this.trackStates.delete(a.track_id)}let t=new Promise((r,a)=>{this.callbacks.set(Ke,{promise:{resolve:r,reject:a},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e),yield t,yield e.cleanup(),this.store.removeTrack(e),d.d(P,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}waitForLocalRoleAvailability(){if(!this.store.hasRoleDetailsArrived())return new Promise(e=>{this.eventBus.policyChange.subscribeOnce(()=>e())})}createConnectionsAndNegotiateJoin(e,t=!1){return c(this,null,function*(){let i=this.doesLocalPeerNeedWebRTC();i&&this.createPeerConnections(),this.analyticsTimer.start("join_response_time"),yield this.negotiateJoinWithRetry({name:e.name,data:e.metaData,autoSubscribeVideo:t,isWebRTC:i}),this.analyticsTimer.end("join_response_time")})}createPeerConnections(){this.initConfig&&(this.publishConnection||(this.publishConnection=new Ut(this.signal,this.initConfig.rtcConfiguration,this.publishConnectionObserver)),this.subscribeConnection||(this.subscribeConnection=new Bt(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),this.subscribeConnectionObserver)))}negotiateJoinWithRetry(a){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){try{yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})}catch(o){d.e(P,"Join negotiation failed \u274C",o);let n=o instanceof T?o:h.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${o.message}`),l=parseInt(`${n.code/100}`)===5||[v.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(n.code);if(n.code===410&&(n.isTerminal=!0),l){this.joinRetryCount=0,n.isTerminal=!1;let u=()=>c(this,null,function*(){return this.joinRetryCount++,yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})});yield this.retryScheduler.schedule({category:2,error:n,task:u,originalState:"Joined",maxFailedRetries:3,changeState:!1})}else throw o}})}negotiateJoin(a){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){return r?yield this.negotiateJoinWebRTC({name:e,data:t,autoSubscribeVideo:i}):yield this.negotiateJoinNonWebRTC({name:e,data:t,autoSubscribeVideo:i})})}negotiateJoinWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){if(d.d(P,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(P,"Publish peer connection not found, cannot negotiate"),!1;let a=yield this.publishConnection.createOffer();yield this.publishConnection.setLocalDescription(a);let o=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),l=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,o,n,l,a);yield this.publishConnection.setRemoteDescription(u);for(let p of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(p);return this.publishConnection.initAfterJoin(),!!u})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(P,"\u23F3 join: Negotiating Non-WebRTC");let a=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),n=this.isFlagEnabled("onDemandTracks");return!!(yield this.signal.join(e,t,!i,a,o,n))})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(P,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(P,"Publish peer connection not found, cannot negotiate"),!1;let e=yield this.publishConnection.createOffer(this.trackStates);yield this.publishConnection.setLocalDescription(e);let t=yield this.signal.offer(e,this.trackStates);yield this.publishConnection.setRemoteDescription(t);for(let i of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(i);return this.publishConnection.initAfterJoin(),!!t})}performPublishRenegotiation(e){return c(this,null,function*(){d.d(P,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(Ke);if(t){if(!this.publishConnection){d.e(P,"Publish peer connection not found, cannot renegotiate");return}try{let i=yield this.publishConnection.createOffer(this.trackStates,e);yield this.publishConnection.setLocalDescription(i),d.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(Ke),d.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),d.d(P,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(i){let r;i instanceof T?r=i:r=h.GenericErrors.Unknown("PUBLISH",i.message),t.promise.reject(r),d.d(P,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(0?3:4)||(e===0?this.retryScheduler.schedule({category:3,error:t,task:this.retryPublishIceFailedTask,originalState:"Joined"}):this.retryScheduler.schedule({category:4,error:t,task:this.retrySubscribeIceFailedTask,originalState:"Joined",maxFailedRetries:1}))})}internalConnect(e,t,i){return c(this,null,function*(){var a;d.d(P,"connect: started \u23F0");let r=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield Ft.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t});let o=this.store.getRoom();return o&&(o.effectsKey=(a=this.initConfig.config.vb)==null?void 0:a.effectsKey,o.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled")),this.analyticsTimer.end("init_response_time"),ve.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(P,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(o){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(M.connect(o,this.getAdditionalAnalyticsProperties(),r,new Date,t)),d.e(P,"\u274C internal connect: failed",o),o}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(P,"aborting join as transport state is disconnected"),h.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw h.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(P,"\u23F3 internal connect: connecting to ws endpoint",this.initConfig.endpoint);let i=new URL(this.initConfig.endpoint);i.searchParams.set("peer",t),i.searchParams.set("token",e),i.searchParams.set("user_agent_v2",this.store.getUserAgent()),i.searchParams.set("protocol_version",ta),i.searchParams.set("protocol_spec",ia),this.endpoint=i.toString(),this.analyticsTimer.start("ws_connect_time"),yield this.signal.open(this.endpoint),this.analyticsTimer.end("ws_connect_time"),this.analyticsTimer.start("on_policy_change_time"),this.analyticsTimer.start("room_state_time"),d.d(P,"\u2705 internal connect: connected to ws endpoint")})}initRtcStatsMonitor(){return c(this,null,function*(){var e,t,i;(i=this.webrtcInternals)==null||i.setPeerConnections({publish:(e=this.publishConnection)==null?void 0:e.nativeConnection,subscribe:(t=this.subscribeConnection)==null?void 0:t.nativeConnection}),this.initStatsAnalytics()})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new Nt(this.store,this.eventBus,this.getValueFromInitConfig("publishStats","maxSampleWindowSize",30),this.getValueFromInitConfig("publishStats","maxSamplePushInterval",300)),(e=this.getWebrtcInternals())==null||e.start()),this.isFlagEnabled("subscribeStats")&&(this.subscribeStatsAnalytics=new Ot(this.store,this.eventBus,this.getValueFromInitConfig("subscribeStats","maxSampleWindowSize",10),this.getValueFromInitConfig("subscribeStats","maxSamplePushInterval",60)),(t=this.getWebrtcInternals())==null||t.start())}getValueFromInitConfig(e,t,i){var r,a;return((a=(r=this.initConfig)==null?void 0:r.config[e])==null?void 0:a[t])||i}doesRoleNeedWebRTC(e){var r,a;if(!this.isFlagEnabled("nonWebRTCDisableOffer"))return!0;let t=!!(e.publishParams.allowed&&((r=e.publishParams.allowed)==null?void 0:r.length)>0),i=!!(e.subscribeParams.subscribeToRoles&&((a=e.subscribeParams.subscribeToRoles)==null?void 0:a.length)>0);return t||i}doesLocalPeerNeedWebRTC(){var t;let e=(t=this.store.getLocalPeer())==null?void 0:t.role;return e?this.doesRoleNeedWebRTC(e):!0}handleSubscribeConnectionConnected(){var t;(t=this.subscribeConnection)==null||t.logSelectedIceCandidatePairs();let e=this.callbacks.get(qe);this.callbacks.delete(qe),e&&e.promise.resolve(!0)}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw h.WebsocketMethodErrors.AlreadyJoined("JOIN",`Cannot join a meeting in ${this.state} state`);this.state==="Disconnected"&&(this.state="Connecting",this.observer.onStateChange(this.state))}sendErrorAnalyticsEvent(e,t){let i=this.getAdditionalAnalyticsProperties(),r;switch(t){case 0:r=M.connect(e,i);break;case 1:r=M.disconnect(e,i);break;case 2:r=M.join({error:e,time:this.analyticsTimer.getTimeTaken("join_time"),init_response_time:this.analyticsTimer.getTimeTaken("init_response_time"),ws_connect_time:this.analyticsTimer.getTimeTaken("ws_connect_time"),on_policy_change_time:this.analyticsTimer.getTimeTaken("on_policy_change_time"),local_audio_track_time:this.analyticsTimer.getTimeTaken("local_audio_track_time"),local_video_track_time:this.analyticsTimer.getTimeTaken("local_video_track_time"),retries_join:this.joinRetryCount});break;case 3:r=M.publish({error:e});break;case 4:r=M.subscribeFail(e);break}this.eventBus.analytics.publish(r)}getSubscribeConnection(){return this.subscribeConnection}getAdditionalAnalyticsProperties(){var o,n,l,u,p,m,g,f;let e=wa(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(R=>R.degraded).length,r=(u=(l=(n=(o=this.getWebrtcInternals())==null?void 0:o.getCurrentStats())==null?void 0:n.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,a=(f=(g=(m=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:m.getLocalPeerStats())==null?void 0:g.subscribe)==null?void 0:f.bitrate;return{network_info:e,document_hidden:t,num_degraded_tracks:i,bitrate:{publish:r,subscribe:a},max_sub_bitrate:this.maxSubscribeBitrate,recent_pong_response_times:this.signal.getPongResponseTimes(),transport_state:this.state}}};var Na=(s,e,t)=>c(void 0,null,function*(){let r=Error("something went wrong during fetch");for(let a=0;a<4;a++)try{let o=yield fetch(s,e),n=yield o.clone().json();if(t&&t.length&&!o.ok&&t.includes(n.code))throw h.APIErrors.ServerErrors(n.code,"GET_TOKEN",n.message,!1);return o}catch(o){r=o}throw["Failed to fetch","NetworkError"].some(a=>r.message.includes(a))?h.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});function sr(s){if(!s||s.length===0)throw h.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=s.split(".");if(e.length!==3)throw h.APIErrors.InvalidTokenFormat("INIT","Expected 3 '.' separate fields - header, payload and signature respectively");let t=atob(e[1]);try{let i=JSON.parse(t);return{roomId:i.room_id,userId:i.user_id,role:i.role}}catch(i){throw h.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var Oa={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},ar=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new ci;this.sdkState=S({},Oa);this.playlistSettings={video:{bitrate:Ur},audio:{bitrate:Vr}};this.handleAutoplayError=e=>{var t,i;(i=(t=this.errorListener)==null?void 0:t.onError)==null||i.call(t,e)};this.observer={onNotification:e=>{var t;if(e.method==="on-peer-leave-request"){this.handlePeerLeaveRequest(e.params);return}switch(e.method){case"on-policy-change":this.analyticsTimer.end("on_policy_change_time");break;case"peer-list":this.analyticsTimer.end("peer_list_time"),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled);break;case"room-state":this.analyticsTimer.end("room_state_time");break;default:}(t=this.notificationManager)==null||t.handleNotification(e,this.sdkState.isReconnecting)},onConnected:()=>{this.initNotificationManager()},onTrackAdd:e=>{var t;(t=this.notificationManager)==null||t.handleTrackAdd(e)},onTrackRemove:e=>{var t;(t=this.notificationManager)==null||t.handleTrackRemove(e)},onFailure:e=>{var t;(t=this.errorListener)==null||t.onError(e)},onStateChange:(e,t)=>c(this,null,function*(){var r,a;let i=o=>c(this,null,function*(){var n,l;yield this.internalLeave(!0,o),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(n=this.errorListener)==null?void 0:n.onError)==null||l.call(n,o)),this.sdkState.isReconnecting=!1});switch(e){case"Preview":case"Joined":this.initNotificationManager(),this.transportState==="Reconnecting"&&((r=this.listener)==null||r.onReconnected());break;case"Failed":yield i(t);break;case"Reconnecting":this.sdkState.isReconnecting=!0,(a=this.listener)==null||a.onReconnecting(t);break}this.transportState=e,d.d(this.TAG,"Transport State Change",this.transportState)})};this.handlePeerLeaveRequest=e=>{var r;let t=e.requested_by?this.store.getPeerById(e.requested_by):void 0,i={roomEnded:e.room_end,reason:e.reason,requestedBy:t};(r=this.listener)==null||r.onRemovedFromRoom(i),this.internalLeave(!1)};this.handleDeviceChange=e=>{var t,i,r,a,o,n;if(d.d(this.TAG,"Device Change event",e),(i=(t=this.deviceChangeListener)==null?void 0:t.onDeviceChange)==null||i.call(t,e),e.error&&e.type){let l=e.type.includes("audio")?(r=this.localPeer)==null?void 0:r.audioTrack:(a=this.localPeer)==null?void 0:a.videoTrack;(o=this.errorListener)==null||o.onError(e.error),[v.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,v.TracksErrors.DEVICE_IN_USE,v.TracksErrors.DEVICE_NOT_AVAILABLE].includes(e.error.code)&&l&&(l.setEnabled(!1),(n=this.listener)==null||n.onTrackUpdate(2,l,this.localPeer))}};this.handleAudioPluginError=e=>{var t;d.e(this.TAG,"Audio Plugin Error event",e),(t=this.errorListener)==null||t.onError(e)};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var r;yield this.transport.handleLocalRoleUpdate({oldRole:e,newRole:t}),yield(r=this.roleChangeManager)==null?void 0:r.handleLocalPeerRoleUpdate({oldRole:e,newRole:t})});this.sendAudioPresenceFailed=()=>{let e=h.TracksErrors.NoAudioDetected("PREVIEW");d.w(this.TAG,"Audio Presence Failure",this.transportState,e)};this.sendJoinAnalyticsEvent=(e=!1,t)=>{this.eventBus.analytics.publish(M.join(y(S({error:t},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("join_time"),is_preview_called:e,retries_join:this.transport.joinRetryCount})))};this.sendPreviewAnalyticsEvent=e=>{this.eventBus.analytics.publish(M.preview(y(S({error:e},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("preview_time")})))};this.sendAnalyticsEvent=e=>{this.analyticsEventsService.queue(e).flush()}}initNotificationManager(){this.notificationManager||(this.notificationManager=new Ki(this.store,this.eventBus,this.transport,this.listener,this.audioListener))}initStoreAndManagers(){var e;if(this.sdkState.isInitialised){(e=this.notificationManager)==null||e.setListener(this.listener),this.audioSinkManager.setListener(this.listener),this.interactivityCenter.setListener(this.listener);return}this.sdkState.isInitialised=!0,this.store=new It,this.eventBus=new Ci,this.wakeLockManager=new Ri,this.networkTestManager=new bi(this.eventBus,this.listener),this.playlistManager=new vt(this,this.eventBus),this.deviceManager=new Lt(this.store,this.eventBus),this.audioSinkManager=new Ct(this.store,this.deviceManager,this.eventBus),this.audioOutput=new Ii(this.deviceManager,this.audioSinkManager),this.audioSinkManager.setListener(this.listener),this.eventBus.autoplayError.subscribe(this.handleAutoplayError),this.localTrackManager=new Te(this.store,this.observer,this.deviceManager,this.eventBus,this.analyticsTimer),this.analyticsEventsService=new Hi(this.store),this.transport=new $t(this.observer,this.deviceManager,this.store,this.eventBus,this.analyticsEventsService,this.analyticsTimer),this.sessionStore=new qi(this.transport),this.interactivityCenter=new wt(this.transport,this.store,this.listener),this.eventBus.analytics.subscribe(this.sendAnalyticsEvent),this.eventBus.deviceChange.subscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.subscribe(this.handleAudioPluginError)}validateJoined(e){if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION",`Not connected - ${e}`)}sendHLSAnalytics(e){this.sendAnalyticsEvent(M.hlsPlayerError(e))}refreshDevices(){return c(this,null,function*(){this.validateJoined("refreshDevices"),yield this.deviceManager.init(!0)})}getWebrtcInternals(){var e;return(e=this.transport)==null?void 0:e.getWebrtcInternals()}getSessionStore(){return this.sessionStore}getPlaylistManager(){return this.playlistManager}getRecordingState(){var e;return(e=this.store.getRoom())==null?void 0:e.recording}getRTMPState(){var e;return(e=this.store.getRoom())==null?void 0:e.rtmp}getHLSState(){var e;return(e=this.store.getRoom())==null?void 0:e.hls}getTemplateAppData(){return this.store.getTemplateAppData()}getInteractivityCenter(){return this.interactivityCenter}getPeerListIterator(e){return new hi(this.transport,this.store,e)}updatePlaylistSettings(e){e.video&&Object.assign(this.playlistSettings.video,e.video),e.audio&&Object.assign(this.playlistSettings.audio,e.audio)}get localPeer(){var e;return(e=this.store)==null?void 0:e.getLocalPeer()}preview(e,t){return c(this,null,function*(){if(Rr(),br(),this.sdkState.isPreviewInProgress)return Promise.reject(h.GenericErrors.PreviewAlreadyInProgress("PREVIEW","Preview already called"));if(["Joined","Reconnecting"].includes(this.transportState))return this.midCallPreview(e.asRole,e.settings);this.analyticsTimer.start("preview_time"),this.setUpPreview(e,t),e.alwaysRequestPermissions&&this.localTrackManager.requestPermissions().then(()=>c(this,null,function*(){yield this.initDeviceManagers()}));let i=!1,r=!1,a=setTimeout(()=>{var o,n;(!i||!r)&&((n=(o=this.listener)==null?void 0:o.onNetworkQuality)==null||n.call(o,-1))},3e3);return new Promise((o,n)=>{let l=()=>c(this,null,function*(){var g;if(this.localPeer){let f=e.asRole&&this.store.getPolicyForRole(e.asRole);this.localPeer.asRole=f||this.localPeer.role}let p=yield this.localTrackManager.getTracksToPublish(e.settings);p.forEach(f=>this.setLocalPeerTrack(f)),(g=this.localPeer)!=null&&g.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),this.sdkState.isPreviewInProgress=!1,this.analyticsTimer.end("preview_time");let m=this.store.getRoom();m&&t.onPreview(m,p),this.sendPreviewAnalyticsEvent(),o()}),u=p=>{var m;this.analyticsTimer.end("preview_time"),p&&((m=this.errorListener)==null||m.onError(p)),this.sendPreviewAnalyticsEvent(p),this.sdkState.isPreviewInProgress=!1,n(p)};this.eventBus.policyChange.subscribeOnce(l),this.eventBus.leave.subscribeOnce(u),this.transport.preview(e.authToken,e.initEndpoint,this.localPeer.peerId,{name:e.userName,metaData:e.metaData||""},e.autoVideoSubscribe).then(p=>{var m;i=!0,clearTimeout(a),p&&e.captureNetworkQualityInPreview&&this.networkTestManager.start((m=p.config)==null?void 0:m.networkHealth).then(()=>{r=!0})}).catch(u)})})}midCallPreview(e,t){return c(this,null,function*(){var a,o;if(!this.localPeer||this.transportState!=="Joined")throw h.GenericErrors.NotConnected("VALIDATION","Not connected - midCallPreview");let i=e&&this.store.getPolicyForRole(e);if(!i)throw h.GenericErrors.InvalidRole("PREVIEW",`role ${e} does not exist in policy`);this.localPeer.asRole=i;let r=yield this.localTrackManager.getTracksToPublish(t);r.forEach(n=>this.setLocalPeerTrack(n)),(a=this.localPeer)!=null&&a.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),(o=this.listener)==null||o.onPreview(this.store.getRoom(),r)})}cancelMidCallPreview(){return c(this,null,function*(){var e,t,i;if((!this.localPeer||!this.localPeer.isInPreview())&&d.w(this.TAG,"Cannot cancel mid call preview as preview is not in progress"),(e=this.localPeer)!=null&&e.asRole&&this.localPeer.role){let r=this.localPeer.asRole,a=this.localPeer.role;delete this.localPeer.asRole,yield(t=this.roleChangeManager)==null?void 0:t.diffRolesAndPublishTracks({oldRole:r,newRole:a}),(i=this.listener)==null||i.onPeerUpdate(8,this.localPeer)}})}join(e,t){return c(this,null,function*(){var l,u,p,m,g,f;if(Rr(),br(),this.sdkState.isPreviewInProgress)throw h.GenericErrors.NotReady("JOIN","Preview is in progress, can't join");this.analyticsTimer.start("join_time"),this.sdkState.isJoinInProgress=!0;let{roomId:i,userId:r,role:a}=sr(e.authToken),o=((u=(l=this.localPeer)==null?void 0:l.asRole)==null?void 0:u.name)||((m=(p=this.localPeer)==null?void 0:p.role)==null?void 0:m.name);(g=this.networkTestManager)==null||g.stop(),this.listener=t,this.commonSetup(e,i,t),this.removeDevicesFromConfig(e),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),Pe.resumeContext();let n=this.store.getConfig();n!=null&&n.autoManageWakeLock&&this.wakeLockManager.acquireLock(),this.localPeer?(this.localPeer.name=e.userName,this.localPeer.role=this.store.getPolicyForRole(a),this.localPeer.customerUserId=r,this.localPeer.metadata=e.metaData,delete this.localPeer.asRole):this.createAndAddLocalPeerToStore(e,a,r),this.roleChangeManager=new Ht(this.store,this.transport,this.deviceManager,this.getAndPublishTracks.bind(this),this.removeTrack.bind(this),this.listener),this.eventBus.localRoleUpdate.subscribe(this.handleLocalRoleUpdate),d.d(this.TAG,`\u23F3 Joining room ${i}`),d.time(`join-room-${i}`);try{yield this.transport.join(e.authToken,this.localPeer.peerId,{name:e.userName,metaData:e.metaData},e.initEndpoint,e.autoVideoSubscribe),d.d(this.TAG,`\u2705 Joined room ${i}`),this.analyticsTimer.start("peer_list_time"),yield this.notifyJoin(),this.sdkState.isJoinInProgress=!1,yield this.publish(e.settings,o)}catch(R){throw this.analyticsTimer.end("join_time"),this.sdkState.isJoinInProgress=!1,(f=this.listener)==null||f.onError(R),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled,R),d.e(this.TAG,"Unable to join room",R),R}d.timeEnd(`join-room-${i}`)})}stringifyMetadata(e){e.metaData&&typeof e.metaData!="string"?e.metaData=JSON.stringify(e.metaData):e.metaData||(e.metaData="")}cleanup(){var e,t,i;this.cleanDeviceManagers(),this.eventBus.analytics.unsubscribe(this.sendAnalyticsEvent),this.analyticsTimer.cleanup(),Q.cleanup(),this.playlistManager.cleanup(),(e=this.wakeLockManager)==null||e.cleanup(),Te.cleanup(),this.notificationManager=void 0,d.cleanup(),this.sdkState=S({},Oa),this.localPeer&&((t=this.localPeer.audioTrack)==null||t.cleanup(),this.localPeer.audioTrack=void 0,(i=this.localPeer.videoTrack)==null||i.cleanup(),this.localPeer.videoTrack=void 0),this.store.cleanup(),this.listener=void 0,this.roleChangeManager&&this.eventBus.localRoleUpdate.unsubscribe(this.handleLocalRoleUpdate)}leave(e){return this.internalLeave(e)}internalLeave(e=!0,t){return c(this,null,function*(){var r,a,o;let i=(r=this.store)==null?void 0:r.getRoom();if(i){for(;(this.sdkState.isPreviewInProgress||this.sdkState.isJoinInProgress)&&!(t!=null&&t.isTerminal);)yield le(100);let n=i.id;(a=this.networkTestManager)==null||a.stop(),this.eventBus.leave.publish(t),d.d(this.TAG,`\u23F3 Leaving room ${n}`),yield(o=this.transport)==null?void 0:o.leave(e),this.cleanup(),d.d(this.TAG,`\u2705 Left room ${n}`)}})}getAuthTokenByRoomCode(e,t){return c(this,null,function*(){let i=(t||{}).endpoint||"https://auth.100ms.live/v2/token";this.analyticsTimer.start("GET_TOKEN");let r=yield Na(i,{method:"POST",body:JSON.stringify({code:e.roomCode,user_id:e.userId})},[429,500,501,502,503,504,505,506,507,508,509,510,511]),a=yield r.json();if(this.analyticsTimer.end("GET_TOKEN"),!r.ok)throw h.APIErrors.ServerErrors(a.code,"GET_TOKEN",a.message,!1);let{token:o}=a;if(!o)throw Error(a.message);return o})}getLocalPeer(){return this.store.getLocalPeer()}getPeers(){return this.store.getPeers()}getPeerMap(){return this.store.getPeerMap()}getAudioOutput(){return this.audioOutput}sendMessage(e,t){this.sendMessageInternal({message:t,type:e})}sendBroadcastMessage(e,t){return c(this,null,function*(){return yield this.sendMessageInternal({message:e,type:t})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getKnownRoles();if((t.filter(o=>r[o.name])||[]).length===0)throw h.GenericErrors.ValidationFailed("No valid role is present",t);return yield this.sendMessageInternal({message:e,recipientRoles:t,type:i})})}sendDirectMessage(e,t,i){return c(this,null,function*(){var o,n;if(((o=this.localPeer)==null?void 0:o.peerId)===t)throw h.GenericErrors.ValidationFailed("Cannot send message to self");let r=!!((n=this.store.getRoom())!=null&&n.large_room_optimization),a=this.store.getPeerById(t);if(!a)if(r){let{peers:l}=yield this.transport.signal.findPeers({peers:[t],limit:1});if(l.length===0)throw h.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);a=Re(l[0],this.store)}else throw h.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);return yield this.sendMessageInternal({message:e,recipientPeer:a,type:i})})}sendMessageInternal(a){return c(this,arguments,function*({recipientRoles:e,recipientPeer:t,type:i="chat",message:r}){if(r.replace(/\u200b/g," ").trim()==="")throw d.w(this.TAG,"sendMessage","Ignoring empty message send"),h.GenericErrors.ValidationFailed("Empty message not allowed");let o={info:{message:r,type:i}};return e!=null&&e.length&&(o.roles=e.map(n=>n.name)),t!=null&&t.peerId&&(o.peer_id=t.peerId),d.d(this.TAG,"Sending Message: ",o),yield this.transport.signal.broadcast(o)})}startScreenShare(e,t){return c(this,null,function*(){var n,l,u;let i=this.store.getPublishParams();if(!i)return;let{allowed:r}=i;if(!(r&&r.includes("screen"))){d.e(this.TAG,`Role ${(n=this.localPeer)==null?void 0:n.role} cannot share screen`);return}if((u=(l=this.localPeer)==null?void 0:l.auxiliaryTracks)!=null&&u.find(p=>p.source==="screen"))throw Error("Cannot share multiple screens");let o=yield this.getScreenshareTracks(e,t);if(!this.localPeer){d.d(this.TAG,"Screenshared when not connected"),o.forEach(p=>{p.cleanup()});return}yield this.transport.publish(o),o.forEach(p=>{var m,g,f;p.peerId=(m=this.localPeer)==null?void 0:m.peerId,(g=this.localPeer)==null||g.auxiliaryTracks.push(p),(f=this.listener)==null||f.onTrackUpdate(0,p,this.localPeer)})})}stopEndedScreenshare(e){return c(this,null,function*(){d.d(this.TAG,"\u2705 Screenshare ended natively"),yield this.stopScreenShare(),e()})}stopScreenShare(){return c(this,null,function*(){var t;d.d(this.TAG,"\u2705 Screenshare ended from app");let e=(t=this.localPeer)==null?void 0:t.auxiliaryTracks.filter(i=>i.source==="screen");if(e)for(let i of e)yield this.removeTrack(i.trackId)})}addTrack(e,t="regular"){return c(this,null,function*(){var u,p,m,g;if(!e){d.w(this.TAG,"Please pass a valid MediaStreamTrack");return}if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot addTrack");if(this.localPeer.auxiliaryTracks.find(f=>f.trackId===e.id))return;let r=e.kind,a=new MediaStream([e]),o=new we(a),n=r==="audio"?oe:U,l=new n(o,e,t,this.eventBus);this.setPlaylistSettings({track:e,hmsTrack:l,source:t}),yield(u=this.transport)==null?void 0:u.publish([l]),l.peerId=(p=this.localPeer)==null?void 0:p.peerId,(m=this.localPeer)==null||m.auxiliaryTracks.push(l),(g=this.listener)==null||g.onTrackUpdate(0,l,this.localPeer)})}removeTrack(e,t=!1){return c(this,null,function*(){var r;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot removeTrack");let i=this.localPeer.auxiliaryTracks.findIndex(a=>a.trackId===e);if(i>-1){let a=this.localPeer.auxiliaryTracks[i];a.isPublished?yield this.transport.unpublish([a]):yield a.cleanup(),t||this.stopPlaylist(a),this.localPeer.auxiliaryTracks.splice(i,1),(r=this.listener)==null||r.onTrackUpdate(1,a,this.localPeer)}else d.w(this.TAG,`No track found for ${e}`)})}setAnalyticsLevel(e){this.analyticsEventsService.level=e}setLogLevel(e){d.level=e}addAudioListener(e){var t;this.audioListener=e,(t=this.notificationManager)==null||t.setAudioListener(e)}addConnectionQualityListener(e){var t;(t=this.notificationManager)==null||t.setConnectionQualityListener(e)}changeRole(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){var i;e.length<=0||!t||(yield(i=this.transport)==null?void 0:i.signal.requestBulkRoleChange({roles:e.map(r=>r.name),role:t,force:!0}))})}acceptChangeRole(e){return c(this,null,function*(){var t,i;yield(i=this.transport)==null?void 0:i.signal.acceptRoleChangeRequest({requested_by:(t=e.requestedBy)==null?void 0:t.peerId,role:e.role.name,token:e.token})})}endRoom(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot end room");yield(i=this.transport)==null?void 0:i.signal.endRoom(e,t),yield this.leave()})}removePeer(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot remove peer");yield(i=this.transport)==null?void 0:i.signal.removePeer({requested_for:e,reason:t})})}startRTMPOrRecording(e){return c(this,null,function*(){var i,r;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start streaming or recording");let t={meeting_url:e.meetingURL,record:e.record};(i=e.rtmpURLs)!=null&&i.length&&(t.rtmp_urls=e.rtmpURLs),e.resolution&&(t.resolution=e.resolution),yield(r=this.transport)==null?void 0:r.signal.startRTMPOrRecording(t)})}stopRTMPAndRecording(){return c(this,null,function*(){var e;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop streaming or recording");yield(e=this.transport)==null?void 0:e.signal.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){var i;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start HLS streaming");let t={};e&&e.variants&&e.variants.length>0&&(t.variants=e.variants.map(r=>{let a={meeting_url:r.meetingURL};return r.metadata&&(a.metadata=r.metadata),a})),e!=null&&e.recording&&(t.hls_recording={single_file_per_layer:e.recording.singleFilePerLayer,hls_vod:e.recording.hlsVod}),yield(i=this.transport)==null?void 0:i.signal.startHLSStreaming(t)})}stopHLSStreaming(e){return c(this,null,function*(){var t,i,r;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop HLS streaming");if(e){let a={variants:(t=e==null?void 0:e.variants)==null?void 0:t.map(o=>{let n={meeting_url:o.meetingURL};return o.metadata&&(n.metadata=o.metadata),n})};yield(i=this.transport)==null?void 0:i.signal.stopHLSStreaming(a)}yield(r=this.transport)==null?void 0:r.signal.stopHLSStreaming()})}sendHLSTimedMetadata(e){return c(this,null,function*(){var t;if(this.validateJoined("sendHLSTimedMetadata"),e.length>0){let i={metadata_objs:e};yield(t=this.transport)==null?void 0:t.signal.sendHLSTimedMetadata(i)}})}changeName(e){return c(this,null,function*(){var i,r;this.validateJoined("changeName");let t=this.store.getLocalPeer();t&&t.name!==e&&(yield(i=this.transport)==null?void 0:i.signal.updatePeer({name:e}),(r=this.notificationManager)==null||r.updateLocalPeer({name:e}))})}changeMetadata(e){return c(this,null,function*(){var t,i;this.validateJoined("changeMetadata"),yield(t=this.transport)==null?void 0:t.signal.updatePeer({data:e}),(i=this.notificationManager)==null||i.updateLocalPeer({metadata:e})})}setSessionMetadata(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.setSessionMetadata({key:"default",data:e})})}getSessionMetadata(){return c(this,null,function*(){var t;return(yield(t=this.transport)==null?void 0:t.signal.getSessionMetadata("default")).data})}getRoles(){return Object.values(this.store.getKnownRoles())}changeTrackState(e,t){return c(this,null,function*(){var r;if(e.type==="video"&&e.source!=="regular"){d.w(this.TAG,"Muting non-regular video tracks is currently not supported");return}if(e.enabled===t){d.w(this.TAG,`Aborting change track state, track already has enabled - ${t}`,e);return}if(!this.store.getTrackById(e.trackId))throw h.GenericErrors.ValidationFailed("No track found for change track state",e);let i=this.store.getPeerByTrackId(e.trackId);if(!i)throw h.GenericErrors.ValidationFailed("No peer found for change track state",e);yield(r=this.transport)==null?void 0:r.signal.requestTrackStateChange({requested_for:i.peerId,track_id:e.trackId,stream_id:e.stream.id,mute:!t})})}changeMultiTrackState(e){return c(this,null,function*(){var o;if(typeof e.enabled!="boolean")throw h.GenericErrors.ValidationFailed("Pass a boolean for enabled");let{enabled:t,roles:i,type:r,source:a}=e;yield(o=this.transport)==null?void 0:o.signal.requestMultiTrackStateChange({value:!t,type:r,source:a,roles:i==null?void 0:i.map(n=>n==null?void 0:n.name)})})}raiseLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("raiseLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.joinGroup(fe)})}lowerLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("lowerLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.leaveGroup(fe)})}raiseRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.addToGroup(e,fe)})}lowerRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.removeFromGroup(e,fe)})}setFrameworkInfo(e){this.frameworkInfo=S(S({},this.frameworkInfo),e)}attachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.attach(t):yield e.addSink(t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.detach(t):yield e.removeSink(t)})}publish(e,t){return c(this,null,function*(){var i,r,a;if([this.store.getPublishParams(),!this.sdkState.published,!Ce].every(o=>!!o)){let o=t&&t!==((r=(i=this.localPeer)==null?void 0:i.role)==null?void 0:r.name)?()=>{var n;return(n=this.roleChangeManager)==null?void 0:n.diffRolesAndPublishTracks({oldRole:this.store.getPolicyForRole(t),newRole:this.localPeer.role})}:()=>this.getAndPublishTracks(e);yield(a=o==null?void 0:o())==null?void 0:a.catch(n=>{var l;d.e(this.TAG,"Error in publish",n),(l=this.listener)==null||l.onError(n)})}})}getAndPublishTracks(e){return c(this,null,function*(){var i,r;let t=yield this.localTrackManager.getTracksToPublish(e);yield this.setAndPublishTracks(t),(r=(i=this.localPeer)==null?void 0:i.audioTrack)==null||r.initAudioLevelMonitor(),this.sdkState.published=!0})}setAndPublishTracks(e){return c(this,null,function*(){var t;for(let i of e)yield this.transport.publish([i]),this.setLocalPeerTrack(i),(t=this.listener)==null||t.onTrackUpdate(0,i,this.localPeer);yield this.initDeviceManagers()})}setLocalPeerTrack(e){var t;switch(e.peerId=(t=this.localPeer)==null?void 0:t.peerId,e.type){case"audio":this.localPeer.audioTrack=e;break;case"video":this.localPeer.videoTrack=e;break}}initDeviceManagers(){return c(this,null,function*(){var e,t,i,r,a;this.sdkState.deviceManagersInitialised||(this.sdkState.deviceManagersInitialised=!0,yield this.deviceManager.init(),(yield this.deviceManager.updateOutputDevice((t=(e=this.store.getConfig())==null?void 0:e.settings)==null?void 0:t.audioOutputDeviceId))||(yield this.deviceManager.updateOutputDevice((r=(i=Q.getSelection())==null?void 0:i.audioOutput)==null?void 0:r.deviceId)),this.audioSinkManager.init((a=this.store.getConfig())==null?void 0:a.audioSinkElementId))})}cleanDeviceManagers(){this.eventBus.deviceChange.unsubscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.unsubscribe(this.handleAudioPluginError),this.eventBus.autoplayError.unsubscribe(this.handleAutoplayError),this.deviceManager.cleanup(),this.audioSinkManager.cleanup()}initPreviewTrackAudioLevelMonitor(){var t;let e=(t=this.localPeer)==null?void 0:t.audioTrack;e==null||e.initAudioLevelMonitor(),this.eventBus.trackAudioLevelUpdate.subscribe(i=>{var a;let r=i&&i.track.trackId===(e==null?void 0:e.trackId)?[{audioLevel:i.audioLevel,peer:this.localPeer,track:e}]:[];this.store.updateSpeakers(r),(a=this.audioListener)==null||a.onAudioLevelUpdate(r)}),this.eventBus.localAudioSilence.subscribe(this.sendAudioPresenceFailed)}notifyJoin(){var i;let e=this.store.getLocalPeer(),t=this.store.getRoom();if(!t){d.w(this.TAG,"notify join - room not present");return}if(t.joinedAt=new Date,e&&(e.joinedAt=t.joinedAt),e!=null&&e.role){this.analyticsTimer.end("join_time"),(i=this.listener)==null||i.onJoin(t);return}return new Promise((r,a)=>{this.eventBus.policyChange.subscribeOnce(()=>{var o;this.analyticsTimer.end("join_time"),(o=this.listener)==null||o.onJoin(t),r()}),this.eventBus.leave.subscribeOnce(o=>{a(o)})})}setUpPreview(e,t){this.listener=t,this.sdkState.isPreviewCalled=!0,this.sdkState.isPreviewInProgress=!0;let{roomId:i,userId:r,role:a}=sr(e.authToken);this.commonSetup(e,i,t),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),this.createAndAddLocalPeerToStore(e,a,r,e.asRole)}setPlaylistSettings(r){return c(this,arguments,function*({track:e,hmsTrack:t,source:i}){var a,o;if(i==="videoplaylist"){let n={};if(e.kind==="audio")n.maxBitrate=((a=this.playlistSettings.audio)==null?void 0:a.bitrate)||Vr;else{n.maxBitrate=((o=this.playlistSettings.video)==null?void 0:o.bitrate)||Ur;let{width:l,height:u}=e.getSettings();n.width=l,n.height=u}yield t.setSettings(n)}else i==="audioplaylist"&&(yield t.setSettings({maxBitrate:64}))})}createAndAddLocalPeerToStore(e,t,i,r){let a=this.store.getPolicyForRole(t),o=r?this.store.getPolicyForRole(r):void 0,n=new Tt({name:e.userName||"",customerUserId:i,metadata:e.metaData||"",role:a,asRole:o||a});this.store.addPeer(n)}commonSetup(e,t,i){this.stringifyMetadata(e),e.initEndpoint||(e.initEndpoint="https://prod-init.100ms.live"),this.errorListener=i,this.deviceChangeListener=i,this.initStoreAndManagers(),this.store.setErrorListener(this.errorListener),this.store.getRoom()||this.store.setRoom(new Rt(t))}removeDevicesFromConfig(e){this.store.getConfig()&&e.settings&&(delete e.settings.audioOutputDeviceId,delete e.settings.videoDeviceId,delete e.settings.audioInputDeviceId)}getScreenshareTracks(e,t){return c(this,null,function*(){let[i,r]=yield this.localTrackManager.getLocalScreen(t),a=()=>{this.stopEndedScreenshare(e)},o=[];if(t!=null&&t.audioOnly){if(i.nativeTrack.stop(),!r)throw h.TracksErrors.NothingToReturn("TRACK","Select share audio when sharing screen","No audio found");o.push(r),r.nativeTrack.addEventListener("ended",a)}else o.push(i),i.nativeTrack.addEventListener("ended",a),r&&o.push(r);return o})}stopPlaylist(e){e.source==="audioplaylist"?this.playlistManager.stop("audio"):e.source==="videoplaylist"&&this.playlistManager.stop("video")}};var Oe=class s{constructor(e,t,i){this.getStats=()=>(this.stats||(this.stats=new Ze(this.store,this.sdk)),this.stats);e?this.store=e:this.store=s.createNewHMSStore(Ai("HMSStore"),rt),i?this.notifications=i:this.notifications=new vi(this.store),t?this.actions=t:(this.sdk=new ar,this.actions=new Pi(this.store,this.sdk,this.notifications)),this.actions.setFrameworkInfo({type:"js",sdkVersion:Hr().version}),this.initialTriggerOnSubscribe=!1,N&&(window.__hms=this)}triggerOnSubscribe(){this.initialTriggerOnSubscribe||(s.makeStoreTriggerOnSubscribe(this.store),this.initialTriggerOnSubscribe=!0)}getStore(){return this.store}getHMSActions(){return this.actions}getActions(){return this.actions}getNotifications(){return{onNotification:this.notifications.onNotification}}static createNewHMSStore(e,t){let i=(0,Va.default)(()=>t()),r=i.setState;i.setState=n=>{let l=typeof n=="function"?(0,xa.produce)(n):n;r(l)};let a=i.getState;i.getState=n=>n?n(a()):a(),s.compareWithShallowCheckInSubscribe(i);let o=s.setUpDevtools(i,e);return y(S({},i),{namedSetState:o})}static makeStoreTriggerOnSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,a)=>(i(e.getState(r),void 0),t(i,r,a))}static compareWithShallowCheckInSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,a)=>(r||(r=o=>o),a=a||Ua.default,t(i,r,a))}static setUpDevtools(e,t){let i;try{i=window.__REDUX_DEVTOOLS_EXTENSION__||window.top.__REDUX_DEVTOOLS_EXTENSION__}catch(o){}if(!i)return o=>{e.setState(o)};let r=i.connect(s.devtoolsOptions(t));r.prefix=t?`${t} > `:"";let a=e.setState;return e.setState=o=>{a(o),r.send(`${r.prefix}setState`,e.getState())},r.subscribe(s.devtoolsSubscribe(r,e,a)),r.send("setUpStore",e.getState()),(o,n)=>{a(o);let l=n||`${r.prefix}action`;r.send(l,e.getState())}}static devtoolsOptions(e){return{name:e,actionsBlacklist:["audioLevel","playlistProgress","connectionQuality"]}}static devtoolsSubscribe(e,t,i){return r=>{var a,o,n,l;if(r.type==="DISPATCH"&&r.state)["JUMP_TO_ACTION","JUMP_TO_STATE"].includes(r.payload.type)?i(JSON.parse(r.state)):t.setState(JSON.parse(r.state));else if(r.type==="DISPATCH"&&((a=r.payload)==null?void 0:a.type)==="COMMIT")e.init(t.getState());else if(r.type==="DISPATCH"&&((o=r.payload)==null?void 0:o.type)==="IMPORT_STATE"){let u=(n=r.payload.nextLiftedState)==null?void 0:n.actionsById;(((l=r.payload.nextLiftedState)==null?void 0:l.computedStates)||[]).forEach(({state:m},g)=>{let f=u[g]||`${e.prefix}setState`;g===0?e.init(m):(i(m),e.send(f,t.getState()))})}}}};var Fa=(s,e,t)=>{let i;t.getState(J)==="Connected"&&(i=Ba(s,e,t)),t.subscribe(r=>{["Connected","Reconnecting"].includes(r)?i||(i=Ba(s,e,t)):["Disconnected","Failed"].includes(r)&&i&&(vc(e,r),i(),i=void 0)},J)},Ba=(s,e,t)=>{var a,o;let i=Tc(t,e);(a=s.getWebrtcInternals())==null||a.start();let r=(o=s.getWebrtcInternals())==null?void 0:o.onStatsChange(n=>fc(e,n,t,s));return()=>{i(),r&&r()}},Tc=(s,e)=>{let t,i,r;return s.getState(ne)?e.namedSetState(a=>{a.localPeer.id=s.getState(ne)},"localpeer-id"):t=s.subscribe(a=>{a&&e.namedSetState(o=>{o.localPeer.id=a},"localpeer-id")},ne),s.getState($)?e.namedSetState(a=>{a.localPeer.videoTrack=s.getState($)},"localpeer-videotrack-id"):i=s.subscribe(a=>{a&&e.namedSetState(o=>{o.localPeer.videoTrack=a},"localpeer-videotrack-id")},$),s.getState(Y)?e.namedSetState(a=>{a.localPeer.audioTrack=s.getState(Y)},"localpeer-audiotrack-id"):r=s.subscribe(a=>{a&&e.namedSetState(o=>{o.localPeer.audioTrack=a},"localpeer-audiotrack-id")},Y),()=>{t==null||t(),i==null||i(),r==null||r()}},fc=(s,e,t,i)=>{let r=t.getState(D);s.namedSetState(a=>{let o=t.getState(ne),n={},l=Object.keys(r).filter(p=>r[p].peerId!==o);for(let p of l){let m=e.getRemoteTrackStats(p);m&&(n[p]=m)}es(a.remoteTrackStats,n);let u={[o]:e.getLocalPeerStats()};es(a.peerStats,u),ka(a.localTrackStats,e.getLocalTrackStats(),i.store.getLocalPeerTracks())},"webrtc-stats")},vc=(s,e="resetState")=>{s.namedSetState(t=>{Object.assign(t,st())},e)};var Ze=class{constructor(e,t){this.hmsStore=e;this.sdk=t;this.store=Oe.createNewHMSStore(Ai("HMSStatsStore"),st),this.getState=this.store.getState,this.subscribe=this.store.subscribe,this.getPublishPeerConnection=()=>new Promise(i=>{var r,a;this.hmsStore.getState(J)==="Connected"?i((a=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:a.getPublishPeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getPublishPeerConnection())},J)}),this.getSubscribePeerConnection=()=>new Promise(i=>{var r,a;this.hmsStore.getState(J)==="Connected"?i((a=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:a.getSubscribePeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getSubscribePeerConnection())},J)}),this.sdk&&Fa(this.sdk,this.store,this.hmsStore)}};var B=require("reselect");var Mc=s=>s.localPeer.id,yc=s=>s.localPeer.audioTrack,kc=s=>s.localPeer.videoTrack,Ec=(s,e)=>e,Ga=(s,e)=>e,Pc=s=>s.remoteTrackStats,$a=s=>s.peerStats,ds=s=>s.localTrackStats,ye=(0,B.createSelector)([$a,Mc],(s,e)=>s[e]),Ac=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.packetsLost}),bc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.jitter}),Rc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.publish)==null?void 0:e.bitrate}),Hc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.bitrate}),Ic=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.publish)==null?void 0:e.availableOutgoingBitrate}),Cc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.availableIncomingBitrate}),Lc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.publish)==null?void 0:e.bytesSent}),Dc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.bytesReceived}),wc=(0,B.createSelector)([$a,Ec],(s,e)=>e?s[e]:void 0),_c=(0,B.createSelector)([Pc,Ga],(s,e)=>e?s[e]:void 0),ls=(0,B.createSelector)([ds,Ga],(s,e)=>e?s[e]:void 0),Nc=A(wc),Oc=A(_c),xc=(0,B.createSelector)([ds,yc],(s,e)=>{var t;return e?(t=s[e])==null?void 0:t[0]:void 0}),Uc=A((0,B.createSelector)(ls,s=>s==null?void 0:s[0])),Vc=(0,B.createSelector)([ds,kc],(s,e)=>{var t;return e?(t=s[e])==null?void 0:t[0]:void 0}),Bc=A((0,B.createSelector)(ls,s=>s)),Fc=s=>A((0,B.createSelector)(ls,e=>{let t=Object.keys(be).find(i=>be[i]===s);return s&&(e==null?void 0:e.find(i=>i.rid===t))||(e==null?void 0:e[0])})),Wa={localPeerStats:ye,packetsLost:Ac,jitter:bc,publishBitrate:Rc,subscribeBitrate:Hc,availablePublishBitrate:Ic,availableSubscribeBitrate:Cc,totalBytesSent:Lc,totalBytesReceived:Dc,peerStatsByID:Nc,trackStatsByID:Oc,localAudioTrackStatsByID:Uc,localVideoTrackStatsByID:Bc,localVideoTrackStatsByLayer:Fc,localAudioTrackStats:xc,localVideoTrackStats:Vc};
82
+ }`}};var ft=class extends je{constructor(t){super(y(S({},t),{isLocal:!1}));this.isLocal=!1;this.auxiliaryTracks=[];this.fromRoomState=!1;this.fromRoomState=!!t.fromRoomState}};var Re=(s,e)=>new ft({peerId:s.peer_id,name:s.info.name,role:e.getPolicyForRole(s.role),customerUserId:s.info.user_id,metadata:s.info.data,groups:s.groups});var hi=class{constructor(e,t,i){this.transport=e;this.store=t;this.options=i;this.isEnd=!1;this.iterator=null;this.total=0;this.defaultPaginationLimit=10}validateConnection(){if(!this.transport||!this.store)throw Error("Use usePaginatedParticipants or hmsActions.getPeerListIterator after preview or join has happened")}hasNext(){return!this.isEnd}getTotal(){return this.total}findPeers(){return c(this,null,function*(){var t;this.validateConnection();let e=yield this.transport.signal.findPeers(y(S({},this.options||{}),{limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}));return this.updateState(e),this.processPeers(e.peers)})}next(){return c(this,null,function*(){var t;this.validateConnection();let e;return!this.iterator&&!this.isEnd?yield this.findPeers():this.iterator?(e=yield this.transport.signal.peerIterNext({iterator:this.iterator,limit:((t=this.options)==null?void 0:t.limit)||this.defaultPaginationLimit}),this.updateState(e),this.processPeers(e.peers)):[]})}processPeers(e){let t=[];return e.forEach(i=>{let r=Re(i,this.store);t.push(r)}),t}updateState(e){this.isEnd=e.eof,this.total=e.total,e.iterator&&(this.iterator=e.iterator)}};var Qe=class{constructor(e){this.TAG="[AudioContextManager]";this.audioContext=new AudioContext,this.source=this.audioContext.createMediaElementSource(e),this.source.connect(this.audioContext.destination)}resumeContext(){return c(this,null,function*(){this.audioContext.state==="suspended"&&(yield this.audioContext.resume(),d.d(this.TAG,"AudioContext is resumed"))})}getAudioTrack(){return this.destinationNode&&this.source.disconnect(this.destinationNode),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.source.connect(this.destinationNode),this.destinationNode.stream.getAudioTracks()[0]}cleanup(){this.audioContext.state!=="closed"&&this.audioContext.close().catch(e=>{d.d(this.TAG,"AudioContext close error",e.message)})}};var ua=require("eventemitter2"),He=class extends ua.EventEmitter2{on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,t){return super.emit(e,t)}listeners(e){return super.listeners(e)}};var Si=class extends He{constructor(){super(...arguments);this.audioElement=null;this.TAG="[PlaylistAudioManager]";this.seeked=!1}play(t){return c(this,null,function*(){return this.audioElement=this.getAudioElement(),new Promise((i,r)=>{this.audioElement=this.getAudioElement(),this.audioElement.src=t,this.seeked=!1,this.audioElement.onerror=()=>{let a=`Error loading ${t}`;d.e(this.TAG,a),this.stop(),r(a)},this.audioElement.oncanplaythrough=()=>c(this,null,function*(){try{if(!this.audioElement)return;if(this.audioContextManager.resumeContext(),this.track)this.seeked?this.seeked=!1:(yield this.audioElement.play(),i([this.track]));else{yield this.audioElement.play();let a=this.audioContextManager.getAudioTrack();this.track=a,i([a])}}catch(a){d.e(this.TAG,"Error playing audio",t,a.message),r(a)}}),this.audioElement.onseeked=()=>{this.seeked=!0}})})}getTracks(){return this.track?[this.track.id]:[]}getElement(){return this.audioElement||(this.audioElement=this.getAudioElement()),this.audioElement}stop(){var t,i,r;(t=this.audioElement)==null||t.pause(),(i=this.audioElement)==null||i.removeAttribute("src"),this.audioElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.track=void 0}getAudioElement(){if(this.audioElement)return this.audioElement;let t=document.createElement("audio");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Qe(t),t}};var mi=class extends He{constructor(){super(...arguments);this.TAG="[PlaylistVideoManager]";this.videoElement=null;this.canvasContext=null;this.tracks=[];this.DEFAUL_FPS=24;this.seeked=!1;this.drawImage=()=>{var t,i,r;this.videoElement&&!this.videoElement.paused&&!this.videoElement.ended&&((r=this.canvasContext)==null||r.drawImage(this.videoElement,0,0,(t=this.canvas)==null?void 0:t.width,(i=this.canvas)==null?void 0:i.height),this.timer=setTimeout(()=>{this.drawImage()},1e3/this.DEFAUL_FPS))}}play(t){return this.videoElement=this.getVideoElement(),this.createCanvas(),new Promise((i,r)=>{this.videoElement=this.getVideoElement(),this.videoElement.src=t,this.seeked=!1,this.videoElement.onerror=()=>{let a=`Error loading ${t}`;d.e(this.TAG,a),this.stop(),r(a)},this.videoElement.oncanplaythrough=()=>c(this,null,function*(){var a,o,n;try{if(!this.videoElement)return;if(this.canvas.width=this.videoElement.videoWidth,this.canvas.height=this.videoElement.videoHeight,this.tracks.length===0){this.clearCanvasAndTracks();let l=this.canvas.captureStream();if(!l){d.e(this.TAG,"Browser does not support captureStream");return}this.videoElement.onplay=this.drawImage,yield this.audioContextManager.resumeContext(),yield this.videoElement.play();let u=this.audioContextManager.getAudioTrack();l.addTrack(u),l.getTracks().forEach(p=>{this.tracks.push(p)}),i(this.tracks)}else this.seeked?(this.seeked=!1,(n=this.canvasContext)==null||n.drawImage(this.videoElement,0,0,(a=this.canvas)==null?void 0:a.width,(o=this.canvas)==null?void 0:o.height)):(yield this.videoElement.play(),i(this.tracks))}catch(l){d.e(this.TAG,"Error playing video",t,l.message),r(l)}}),this.videoElement.onseeked=()=>{this.seeked=!0}})}getTracks(){return this.tracks.map(t=>t.id)}getElement(){return this.videoElement||(this.videoElement=this.getVideoElement()),this.videoElement}stop(){var t,i,r;(t=this.videoElement)==null||t.pause(),(i=this.videoElement)==null||i.removeAttribute("src"),this.videoElement=null,(r=this.audioContextManager)==null||r.cleanup(),this.clearCanvasAndTracks()}clearCanvasAndTracks(){var t;this.tracks=[],(t=this.canvasContext)==null||t.clearRect(0,0,this.canvas.width,this.canvas.height),clearTimeout(this.timer)}getVideoElement(){if(this.videoElement)return this.videoElement;let t=document.createElement("video");return t.crossOrigin="anonymous",t.addEventListener("timeupdate",i=>this.emit("progress",i)),t.addEventListener("ended",()=>{this.emit("ended",null)}),this.audioContextManager=new Qe(t),t}createCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"))}};var gi={audio:{list:[],currentIndex:-1,isAutoplayOn:!0},video:{list:[],currentIndex:-1,isAutoplayOn:!0}},vt=class extends He{constructor(t,i){super();this.sdk=t;this.eventBus=i;this.state={audio:S({},gi.audio),video:S({},gi.video)};this.TAG="[PlaylistManager]";this.handlePausePlaylist=r=>c(this,[r],function*({enabled:t,track:i}){var o;if(t)return;let a;i.source==="audioplaylist"&&(a="audio"),i.source==="videoplaylist"&&(a="video"),a&&((o=this.getElement(a))==null||o.pause())});this.addTrack=(t,i)=>c(this,null,function*(){yield this.sdk.addTrack(t,i),d.d(this.TAG,"Playlist track added",Xt(t))});this.removeTrack=t=>c(this,null,function*(){yield this.sdk.removeTrack(t,!0),d.d(this.TAG,"Playlist track removed",t)});this.audioManager=new Si,this.videoManager=new mi,this.addListeners()}getList(t="audio"){return this.state[t].list}setList(t){if(!t||t.length===0){d.w(this.TAG,"Please pass in a list of HMSPlaylistItem's");return}t.forEach(i=>{this.state[i.type].list.find(r=>r.id===i.id)||this.state[i.type].list.push(i)})}clearList(t){return c(this,null,function*(){this.isPlaying(t)&&(yield this.stop(t)),this.state[t].list=[]})}removeItem(t,i){return c(this,null,function*(){let{list:r,currentIndex:a}=this.state[i],o=r.findIndex(n=>t===n.id);return o>-1?(a===o&&this.isPlaying(i)&&(yield this.stop(i)),r.splice(o,1),!0):!1})}seek(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");let a=this.getElement(i);if(a){let o=Math.max(a.currentTime+t,0);a.currentTime=Math.min(o,a.duration)}}seekTo(t,i="audio"){let{currentIndex:r}=this.state[i];if(r===-1)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","No item is currently playing");if(t<0)throw Error("value cannot be negative");let a=this.getElement(i);a&&(a.currentTime=Math.min(t,a.duration))}setVolume(t,i="audio"){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");let r=this.getElement(i);r&&(r.volume=t*.01)}getVolume(t="audio"){let i=this.getElement(t);return i?Math.floor(i.volume*100):0}getCurrentTime(t="audio"){let i=this.getElement(t);return(i==null?void 0:i.currentTime)||0}getCurrentIndex(t="audio"){return this.state[t].currentIndex}getCurrentProgress(t="audio"){var n;let{list:i,currentIndex:r}=this.state[t],a=(n=i[r])==null?void 0:n.url,o=this.getElement(t);return!a||!o?0:Math.floor(100*(o.currentTime/o.duration))}getCurrentSelection(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r!==-1)return i[r]}isPlaying(t="audio"){let i=this.getElement(t);return!!i&&!i.paused}setIsAutoplayOn(t="audio",i){this.state[t].isAutoplayOn=i}getPlaybackRate(t="audio"){let i=this.getElement(t);return i?i.playbackRate:1}setPlaybackRate(t="audio",i){if(i<.25||i>2)throw Error("Please pass a value between 0.25 and 2.0");let r=this.getElement(t);r&&(r.playbackRate=i)}setEnabled(a,o){return c(this,arguments,function*(t,{id:i,type:r="audio"}){let l=this.state[r].list.findIndex(p=>p.id===i);if(!i||l===-1){d.w(this.TAG,"Pass a valid id");return}let u=this.state[r].list[l].url;t?yield this.play(u,r):yield this.pause(u,r),this.state[r].currentIndex=l,this.setDuration(r)})}playNext(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r>=i.length-1)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached end of playlist");yield this.play(i[r+1].url,t),this.state[t].currentIndex=r+1,this.setDuration(t)})}playPrevious(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r}=this.state[t];if(r<=0)throw h.PlaylistErrors.NoEntryToPlay("PLAYLIST","Reached start of playlist");yield this.play(i[r-1].url,t),this.state[t].currentIndex=r-1,this.setDuration(t)})}stop(){return c(this,arguments,function*(t="audio"){var r;let i=t==="audio"?this.audioManager:this.videoManager;(r=i.getElement())==null||r.pause(),yield this.removeTracks(t),i.stop(),this.state[t].currentIndex=-1})}cleanup(){this.state={audio:S({},gi.audio),video:S({},gi.video)},this.eventBus.localAudioEnabled.unsubscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.unsubscribe(this.handlePausePlaylist),this.audioManager.stop(),this.videoManager.stop()}onProgress(t){this.videoManager.on("progress",()=>{try{t({type:"video",progress:this.getCurrentProgress("video")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}}),this.audioManager.on("progress",()=>{try{t({type:"audio",progress:this.getCurrentProgress("audio")})}catch(i){d.e(this.TAG,"Error in onProgress callback")}})}onNewTrackStart(t){this.on("newTrackStart",t)}onPlaylistEnded(t){this.on("playlistEnded",t)}onCurrentTrackEnded(t){this.on("currentTrackEnded",t)}getElement(t="audio"){return t==="audio"?this.audioManager.getElement():this.videoManager.getElement()}removeTracks(){return c(this,arguments,function*(t="audio"){let r=(t==="audio"?this.audioManager:this.videoManager).getTracks();for(let a of r)yield this.removeTrack(a)})}play(r){return c(this,arguments,function*(t,i="audio"){let a=i==="audio"?this.audioManager:this.videoManager,o=a.getElement();if(this.isItemCurrentlyPlaying(t,i)){d.w(this.TAG,`The ${i} is currently playing`);return}if(o!=null&&o.src.includes(t))yield o.play();else{o==null||o.pause();let n=yield a.play(t);for(let l of n)yield this.addTrack(l,i==="audio"?"audioplaylist":"videoplaylist")}})}isItemCurrentlyPlaying(t,i){let r=this.getElement(i);return!!(r&&!r.paused&&r.src.includes(t))}setDuration(t="audio"){let i=this.getElement(t),{list:r,currentIndex:a}=this.state[t];r[a]&&(r[a].duration=(i==null?void 0:i.duration)||0),this.emit("newTrackStart",r[a])}pause(r){return c(this,arguments,function*(t,i="audio"){let a=this.getElement(i);a&&!a.paused&&a.src.includes(t)?(a.pause(),d.d(this.TAG,"paused url",t)):d.w(this.TAG,"The passed in url is not currently playing")})}addListeners(){this.audioManager.on("ended",()=>this.handleEnded("audio")),this.videoManager.on("ended",()=>this.handleEnded("video")),this.eventBus.localAudioEnabled.subscribe(this.handlePausePlaylist),this.eventBus.localVideoEnabled.subscribe(this.handlePausePlaylist)}handleEnded(){return c(this,arguments,function*(t="audio"){let{list:i,currentIndex:r,isAutoplayOn:a}=this.state[t];r===i.length-1?(yield this.stop(t),this.emit("playlistEnded",t)):a?this.playNext(t):yield this.pause(i[r].url,t),this.emit("currentTrackEnded",i[r])})}};var Mt="HMS-Store:",k=class{static v(e,...t){this.log(0,e,...t)}static d(...e){this.log(1,...e)}static i(...e){this.log(2,...e)}static w(...e){this.log(3,...e)}static e(...e){this.log(6,...e)}static time(e){this.log(4,"[HMSPerformanceTiming]",e)}static timeEnd(e){this.log(5,"[HMSPerformanceTiming]",e,e)}static cleanup(){performance.clearMarks(),performance.clearMeasures()}static log(e,...t){if(!(this.level.valueOf()>e.valueOf()))switch(e){case 0:{console.log(Mt,...t);break}case 1:{console.debug(Mt,...t);break}case 2:{console.info(Mt,...t);break}case 3:{console.warn(Mt,...t);break}case 6:{console.error(Mt,...t);break}case 4:{performance.mark(t[1]);break}case 5:{let i=t[0],r=t[1];try{let a=performance.measure(r,r);this.log(1,i,r,a==null?void 0:a.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(a){this.log(1,i,r,a)}break}}}};k.level=0;var Kr=(s,e)=>e,yt=(s,e)=>e,pa=(s,e)=>e,dn=(s,e)=>e,ln=(s,e)=>e,z=(0,H.createSelector)([F,Kr],(s,e)=>e?s[e]:null),qr=(0,H.createSelector)([D,yt],(s,e)=>e?s[e]:null),un=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="video"?t:null}),pn=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="audio"?t:null}),hn=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="audio"&&(t==null?void 0:t.source)==="screen"?t:null}),Sn=(0,H.createSelector)([D,yt],(s,e)=>{if(!e)return null;let t=s[e];return(t==null?void 0:t.type)==="video"&&(t==null?void 0:t.source)==="screen"?t:null}),mn=(0,H.createSelector)([Tr,ln],(s,e)=>e?s[e]:null),W=A(z),gn=A((0,H.createSelector)([Jt,dn],(s,e)=>{if(s)return e?s[e]:s}));function Tn(s){return e=>{if(e.sessionStore)return s?e.sessionStore[s]:e.sessionStore}}var fn=(...s)=>(0,H.createSelector)([Jt],e=>{if(e){if(s&&s.length>0){let t=e;for(let i of s){if(!i)return t;t=t==null?void 0:t[i]}return t}return e}}),vn=A((0,H.createSelector)(z,s=>s==null?void 0:s.name)),kt=A(qr),jr=A(un),Mn=A(pn),yn=A(hn),kn=A(Sn),ha=A((s,e)=>{let t=z(s,e);if(t&&t.videoTrack&&t.videoTrack!=="")return s.tracks[t.videoTrack]}),Sa=A((s,e)=>{let t=z(s,e);if(t&&t.audioTrack&&t.audioTrack!=="")return s.tracks[t.audioTrack]}),En=ha,Pn=A((s,e)=>{let t=z(s,e);return(t==null?void 0:t.auxiliaryTracks.map(i=>s.tracks[i]))||[]}),ma=(s,e)=>e?s.speakers[e]:null,An=A((0,H.createSelector)(ma,s=>(s==null?void 0:s.audioLevel)||0)),bn=(s,e)=>{let t=Sa(e)(s);return ma(s,t==null?void 0:t.id)},Rn=A((0,H.createSelector)(bn,s=>(s==null?void 0:s.audioLevel)||0)),Hn=A((s,e)=>{if(e)return s.connectionQualities[e]}),In=A((s,e)=>{let t=z(s,e);if(t){let i=t==null?void 0:t.auxiliaryTracks.find(r=>at(s.tracks[r]));return i?s.tracks[i]:void 0}}),Cn=A((0,H.createSelector)(D,z,(s,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=s[i];return nt(r)&&ot(r)});return t?s[t]:void 0})),Ln=A((0,H.createSelector)(D,z,(s,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=s[i];return nt(r)&&at(r)});return t?s[t]:void 0})),Dn=A((0,H.createSelector)(D,z,(s,e)=>{let t=e==null?void 0:e.auxiliaryTracks.find(i=>{let r=s[i];return jt(r)&&at(r)});return t?s[t]:void 0})),Jr=A((0,H.createSelector)(D,z,(s,e)=>Ie(s,e))),wn=s=>(0,H.createSelector)(Jr(s),e=>e.video),Qr=s=>(0,H.createSelector)(Jr(s),e=>e.audio),_n=A((s,e)=>{let t=z(s,e);return xe(s,t==null?void 0:t.audioTrack)}),Nn=A((s,e)=>{let t=z(s,e);return xe(s,t==null?void 0:t.videoTrack)}),zr=A((s,e)=>{if(e&&s.tracks[e])return s.tracks[e].volume===0}),On=A((s,e)=>{let t=z(s,e);return zr(t==null?void 0:t.audioTrack)(s)}),xn=A((s,e)=>{let t=Qr(e)(s);return zr(t==null?void 0:t.id)(s)}),Yr=A((s,e)=>{let t=qr(s,e);if(t){if(t.type!=="audio"){k.w("Please pass audio track here");return}return t.volume}}),Un=A((s,e)=>{let t=z(s,e);return Yr(t==null?void 0:t.audioTrack)(s)}),Vn=A((s,e)=>{let t=Qr(e)(s);return Yr(t==null?void 0:t.id)(s)}),Bn=A((s,e)=>{let t=qr(s,e);if(t){if(t.type!=="video"){k.w("Please pass video track here");return}return t.layer}}),ga=(0,H.createSelector)([Ue,ne,Kr],(s,e,t)=>{if(t)return s.filter(i=>{var r;return!i.recipientPeer&&!((r=i.recipientRoles)!=null&&r.length)||i.sender&&![e,t].includes(i.sender)?!1:[e,t].includes(i.recipientPeer)})}),Ta=(0,H.createSelector)([Ue,pa],(s,e)=>{if(e)return s.filter(t=>{var i,r;return(i=t.recipientRoles)!=null&&i.length?(r=t.recipientRoles)==null?void 0:r.includes(e):!1})}),fa=(0,H.createSelector)(Ue,s=>s.filter(e=>{var t;return!e.recipientPeer&&!((t=e.recipientRoles)!=null&&t.length)})),Fn=(0,H.createSelector)([Ta,pa],s=>s?s.filter(e=>!e.read).length:0),Gn=(0,H.createSelector)([ga,Kr],s=>s?s.filter(e=>!e.read).length:0),$n=(0,H.createSelector)(fa,s=>s.filter(e=>!e.read).length),Wn=A(ga),Kn=A(Ta),qn=A(Fn),jn=A(Gn),Jn=s=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName===s)),Qn=s=>(0,H.createSelector)([ie],e=>e.filter(t=>t.roleName?s.includes(t.roleName):!1)),zn=s=>(0,H.createSelector)(W(s),e=>{try{return e!=null&&e.metadata&&e.metadata!==""?JSON.parse(e.metadata):{}}catch(t){return console.error("cannot parse peer metadata",t),{}}}),Yn=s=>(0,H.createSelector)(W(s),e=>!!(e!=null&&e.isHandRaised)),Xn=s=>(0,H.createSelector)(W(s),e=>e==null?void 0:e.name),Xr=A(mn),Zn=s=>(0,H.createSelector)(dt,e=>e[s]);var Et=require("reselect");var ec=(0,Et.createSelector)([F,D],(s,e)=>Object.values(s).map(i=>{var r;return{peer:i,isAudioEnabled:i.audioTrack?(r=e[i.audioTrack])==null?void 0:r.enabled:!1}})),tc=s=>s.roleChangeRequests[0]||null,ic=(0,Et.createSelector)([tc,F,re],(s,e,t)=>s?{requestedBy:s.requestedBy?e[s.requestedBy]:void 0,role:t[s.roleName],token:s.token}:null),rc=(0,Et.createSelector)([lt],s=>ct(s)),sc=(0,Et.createSelector)([mr],s=>ct(s));var he=require("reselect");var va=s=>(0,he.createSelector)([re],e=>e[s]),ac=s=>(0,he.createSelector)(va(s),e=>ct(e)),oc=(0,he.createSelector)([$,D],(s,e)=>{let t=null;return s&&(t=e[s]),(t==null?void 0:t.plugins)||[]}),nc=(0,he.createSelector)([Y,D],(s,e)=>{let t=null;return s&&(t=e[s]),(t==null?void 0:t.plugins)||[]}),cc=s=>(0,he.createSelector)([oc],e=>e.includes(s)),dc=s=>(0,he.createSelector)([nc],e=>e.includes(s)),lc=s=>(0,he.createSelector)(ie,e=>e.find(s)),uc=s=>(0,he.createSelector)(ie,e=>e.filter(s)),pc=s=>(0,he.createSelector)(x,e=>e.joinedAt&&Date.now()-e.joinedAt.getTime()<=s);var Ba=require("immer"),Fa=it(require("zustand/shallow")),Ga=it(require("zustand/vanilla"));var Ma=require("eventemitter2");var Ti={0:"PEER_JOINED",1:"PEER_LEFT",8:"ROLE_UPDATED",10:"NAME_UPDATED",11:"METADATA_UPDATED",12:"HAND_RAISE_CHANGED"},Pt={0:"TRACK_ADDED",1:"TRACK_REMOVED",2:"TRACK_MUTED",3:"TRACK_UNMUTED",5:"TRACK_DEGRADED",6:"TRACK_RESTORED",4:"TRACK_DESCRIPTION_CHANGED"},fi={0:"POLL_CREATED",1:"POLL_STARTED",2:"POLL_STOPPED",3:"POLL_VOTES_UPDATED"};var Zr="hmsNotification",vi=class{constructor(e){this.id=0;this.onNotification=(e,t)=>{let i=r=>{if(t){let a;if(Array.isArray(t)?a=t.includes(r.type):a=t===r.type,!a)return}e(r)};return this.eventEmitter.addListener(Zr,i),()=>{this.eventEmitter.removeListener(Zr,i)}};this.store=e,this.eventEmitter=new Ma.EventEmitter2({maxListeners:Object.keys(qt).length})}sendPlaylistTrackEnded(e){let t=this.createNotification("PLAYLIST_TRACK_ENDED",e,"info");this.emitEvent(t)}sendDeviceChange(e){var i;let t=this.createNotification("DEVICE_CHANGE_UPDATE",e,e.error?"error":"info",`Selected ${e.type} device - ${(i=e.selection)==null?void 0:i.label}`);this.emitEvent(t)}sendLeaveRoom(e){var r;let t=(r=e.requestedBy)==null?void 0:r.name,i=this.createNotification(e.roomEnded||!t?"ROOM_ENDED":"REMOVED_FROM_ROOM",e,"info",`${e.roomEnded?"Room ended":"Removed from room"} ${t?`by ${t}`:""}`);this.emitEvent(i)}sendPeerList(e){if(e.length===0)return;let t=this.createNotification("PEER_LIST",e,"info");this.emitEvent(t)}sendPeerUpdate(e,t){let i=this.store.getState(W(t==null?void 0:t.id))||t,r=Ti[e];if(r&&i){let a=this.createNotification(r,i,"info");this.emitEvent(a)}}sendTrackUpdate(e,t){let i=this.store.getState(kt(t)),r=Pt[e];if(r){let a=this.createNotification(r,i,"info");this.emitEvent(a)}}sendMessageReceived(e){let t=this.createNotification("NEW_MESSAGE",e,"info");this.emitEvent(t)}sendError(e){let t=this.createNotification("ERROR",e,"error");this.emitEvent(t)}sendReconnecting(e){let t=this.createNotification("RECONNECTING",e,"error");this.emitEvent(t)}sendReconnected(){let e=this.createNotification("RECONNECTED",null,"info");this.emitEvent(e)}sendChangeTrackStateRequest(e){let t=this.createNotification("CHANGE_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendChangeMultiTrackStateRequest(e){let t=this.createNotification("CHANGE_MULTI_TRACK_STATE_REQUEST",e,"info");this.emitEvent(t)}sendPollUpdate(e,t){let i=fi[e],r=this.store.getState(Xr(t));if(i){let a=this.createNotification(i,r,"info");this.emitEvent(a)}}emitEvent(e){this.eventEmitter.emit(Zr,e)}createNotification(e,t,i,r=""){return this.id++,{id:this.id,type:e,message:r,data:t,severity:i}}};var Mi=class{constructor(e){this.queuedUpdates={};this.timers={};this.DEFAULT_INTERVAL_MS=50;this.store=e}setState(e,t,i=this.DEFAULT_INTERVAL_MS){this.queuedUpdates[t]=this.queuedUpdates[t]||[],this.queuedUpdates[t].push(e),!this.timers[t]&&(window?this.timers[t]=window.setTimeout(()=>this.setStateBatched(t),i):this.setStateBatched(t))}setStateBatched(e){var t;if(((t=this.queuedUpdates[e])==null?void 0:t.length)>0){let i=r=>{this.queuedUpdates[e].forEach(a=>{try{a(r)}catch(o){k.w("failed to update store",o)}})};console.time(`timed-${e}`),this.store.namedSetState(i,e),console.timeEnd(`timed-${e}`)}delete this.queuedUpdates[e],window&&this.timers[e]&&(window.clearTimeout(this.timers[e]),delete this.timers[e])}};function ya(s){return s instanceof te||s instanceof _}var ka=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?(Z(r.auxiliaryTracks,a.auxiliaryTracks)&&(a.auxiliaryTracks=r.auxiliaryTracks),r.groups&&Z(r.groups,a.groups)&&(a.groups=r.groups),Object.assign(r,a)):is(r,a)?delete s[i]:yi(r,a)&&(s[i]=a)}},Ea=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?(ts(r,a),Object.assign(r,a)):is(r,a)?delete s[i]:yi(r,a)&&(s[i]=a)}},Pa=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?(r.questions&&Z(r.questions,a.questions)&&(a.questions=r.questions),Object.assign(r,a)):yi(r,a)&&(s[i]=a)}},es=(s,e)=>{let t=At(Object.keys(s),Object.keys(e));for(let i of t){let r=s[i],a=e[i];_e(r,a)?Object.assign(r,a):is(r,a)?delete s[i]:yi(r,a)&&(s[i]=a)}},Aa=(s,e,t)=>{let i=t.reduce((a,o)=>(a[o.firstTrackId]=Object.values(e[o.getTrackIDBeingSent()]||{}).sort((n,l)=>!n.rid||!l.rid?0:n.rid<l.rid?-1:1),a),{}),r=At(Object.keys(s),Object.keys(i));for(let a of r){if(!i[a]){delete s[a];continue}s[a]=i[a]}},ts=(s,e)=>{s.plugins&&Z(s.plugins,e.plugins)&&(e.plugins=s.plugins),s.type==="video"&&s.layerDefinitions&&Z(s.layerDefinitions,e.layerDefinitions)&&(e.layerDefinitions=s.layerDefinitions)},_e=(s,e)=>s&&e,is=(s,e)=>s&&!e,yi=(s,e)=>!s&&e,Z=(s,e)=>{if(s===e||s.length===0&&(e==null?void 0:e.length)===0)return!0;if(!s||!e||s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]!==e[t])return!1;return!0},At=(s,e)=>{let t=new Set;for(let i of s)t.add(i);for(let i of e)t.add(i);return Array.from(t)};var w=class s{static convertPeer(e){var t,i,r;return{id:e.peerId,name:e.name,roleName:(t=e.role)==null?void 0:t.name,isLocal:e.isLocal,videoTrack:(i=e.videoTrack)==null?void 0:i.trackId,audioTrack:(r=e.audioTrack)==null?void 0:r.trackId,auxiliaryTracks:e.auxiliaryTracks.map(a=>a.trackId),customerUserId:e.customerUserId,metadata:e.metadata,joinedAt:e.joinedAt,groups:e.groups,isHandRaised:e.isHandRaised}}static convertTrack(e,t){let i={id:e.trackId,source:e.source,type:e.type,enabled:e.enabled,displayEnabled:e.enabled,peerId:e.peerId||t};return this.enrichTrack(i,e),i}static enrichTrack(e,t){let i=t.getMediaTrackSettings();t instanceof te&&(e.volume=t.getVolume()||0),s.updateDeviceID(e,t),s.enrichLocalTrack(e,t),e.type==="video"&&(e.source==="screen"?(e.displaySurface=i.displaySurface,s.enrichScreenTrack(e,t)):e.source==="regular"&&(e.facingMode=i.facingMode),e.height=i.height,e.width=i.width,s.enrichVideoTrack(e,t)),s.enrichPluginsDetails(e,t)}static enrichLocalTrack(e,t){(t instanceof U||t instanceof oe)&&(e.isPublished=t.isPublished)}static updateDeviceID(e,t){var i;t instanceof U||t instanceof oe?e.deviceID=t.settings.deviceId:e.deviceID=(i=t.getMediaTrackSettings())==null?void 0:i.deviceId}static enrichVideoTrack(e,t){t instanceof _&&(e.layer=t.getLayer(),e.preferredLayer=t.getPreferredLayer(),e.degraded=t.degraded),(t instanceof _||t instanceof U)&&(Z(t.getSimulcastDefinitions(),e.layerDefinitions)||(e.layerDefinitions=t.getSimulcastDefinitions()))}static enrichScreenTrack(e,t){var i,r;if(t instanceof U){let a=(i=t.getCaptureHandle)==null?void 0:i.call(t);(a==null?void 0:a.handle)!==((r=e.captureHandle)==null?void 0:r.handle)&&(e.captureHandle=a),t.isCurrentTab&&(e.displaySurface="selfBrowser")}}static enrichPluginsDetails(e,t){(t instanceof U||t instanceof oe)&&(Z(t.getPlugins(),e.plugins)||(e.plugins=t.getPlugins()))}static convertRoom(e,t){let{recording:i,rtmp:r,hls:a}=s.convertRecordingStreamingState(e==null?void 0:e.recording,e==null?void 0:e.rtmp,e==null?void 0:e.hls);return{id:e.id,name:e.name,localPeer:t,recording:i,rtmp:r,hls:a,sessionId:e.sessionId,startedAt:e.startedAt,joinedAt:e.joinedAt,peerCount:e.peerCount,isLargeRoom:e.large_room_optimization,isEffectsEnabled:e.isEffectsEnabled,effectsKey:e.effectsKey}}static convertMessage(e,t){var i,r,a,o;return{sender:(i=e.peer)==null?void 0:i.peer_id,senderName:(r=e.peer)==null?void 0:r.info.name,senderRole:(a=e.peer)==null?void 0:a.role,senderUserId:(o=e.peer)==null?void 0:o.info.user_id,recipientPeer:e.private?t:void 0,recipientRoles:e.roles,time:new Date(e.timestamp),type:e.info.type,message:e.info.message,id:e.message_id}}static convertRoles(e){let t={};return e&&e.forEach(i=>{t[i.name]=i}),t}static convertRoleChangeRequest(e){var t;return{requestedBy:(t=e.requestedBy)==null?void 0:t.peerId,roleName:e.role.name,token:e.token}}static convertException(e){return{code:e.code,action:e.action,name:e.name,message:e.message,description:e.description,isTerminal:e.isTerminal,nativeError:e.nativeError,timestamp:new Date}}static convertDeviceChangeUpdate(e){let t={devices:e.devices,selection:e.selection,type:e.type};return e.error&&(t.error=this.convertException(e.error)),t}static convertPlaylist(e){let t=this.getConvertedPlaylistType(e,"audio"),i=this.getConvertedPlaylistType(e,"video");return{audio:t,video:i}}static convertPlaylistItem(e,t){let i=t.type,r=e.getCurrentSelection(i),a=e.isPlaying(i),o=t.url===(r==null?void 0:r.url);return y(S({},t),{type:t.type,selected:o,playing:o&&a})}static getConvertedPlaylistType(e,t){let i={},r=e.getCurrentSelection(t),a=e.getCurrentProgress(t),o=e.getVolume(t),n=e.getList(t),l=e.getCurrentIndex(t);return e.getList(t).forEach(u=>{i[u.id]=s.convertPlaylistItem(e,u)}),{list:i,selection:{id:r==null?void 0:r.id,hasPrevious:l>0,hasNext:l<n.length-1},progress:a,volume:o,currentTime:e.getCurrentTime(t),playbackRate:e.getPlaybackRate(t)}}static convertRecordingStreamingState(e,t,i){var r;return{recording:{browser:S({running:!1},e==null?void 0:e.browser),server:S({running:!1},e==null?void 0:e.server),hls:S({running:!1},e==null?void 0:e.hls)},rtmp:S({running:!1},t),hls:{variants:((r=i==null?void 0:i.variants)==null?void 0:r.map(a=>a))||[],running:!!(i!=null&&i.running),error:i==null?void 0:i.error}}}};var bt=class{constructor(e,t,i,r){this.playlistManager=e;this.syncPlaylistState=i;this.store=r;this.type=t}play(e){return c(this,null,function*(){if(!e){k.w("Please pass id to play");return}yield this.playlistManager.setEnabled(!0,{id:e,type:this.type})})}pause(){return c(this,null,function*(){let e=this.type==="audio"?Mr:yr,t=this.store.getState(e.selection);if(!t.id){k.w("No item is currently playing to pause");return}yield this.playlistManager.setEnabled(!1,{id:t.id,type:this.type})})}playNext(){return c(this,null,function*(){yield this.playlistManager.playNext(this.type)})}playPrevious(){return c(this,null,function*(){yield this.playlistManager.playPrevious(this.type)})}seek(e){this.playlistManager.seek(e,this.type),this.syncPlaylistState(`seekOn${this.type}Playlist`)}seekTo(e){this.playlistManager.seekTo(e,this.type),this.syncPlaylistState(`seekToOn${this.type}Playlist`)}setVolume(e){this.playlistManager.setVolume(e,this.type),this.syncPlaylistState(`setVolumeOn${this.type}Playlist`)}setList(e){this.playlistManager.setList(e),this.syncPlaylistState(`setListOn${this.type}Playlist`)}stop(){return c(this,null,function*(){yield this.playlistManager.stop(this.type),this.syncPlaylistState(`stop${this.type}Playlist`)})}setIsAutoplayOn(e){this.playlistManager.setIsAutoplayOn(this.type,e)}setPlaybackRate(e){this.playlistManager.setPlaybackRate(this.type,e),this.syncPlaylistState(`set${this.type}PlaybackRate`)}removeItem(e){return c(this,null,function*(){let t=yield this.playlistManager.removeItem(e,this.type);return t&&this.syncPlaylistState(`remove${this.type}PlaylistItem`),t})}clearList(){return c(this,null,function*(){yield this.playlistManager.clearList(this.type),this.syncPlaylistState(`clear${this.type}Playlist`)})}};var ki=class{constructor(e,t){this.sdk=e;this.setLocally=t}get sdkSessionStore(){return this.sdk.getSessionStore()}set(e,t){return c(this,null,function*(){let{value:i}=yield this.sdkSessionStore.set(String(e),t);this.setLocally({key:e,value:i})})}observe(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.observe(t)})}unobserve(e){return c(this,null,function*(){let t=Array.isArray(e)?e.map(i=>String(i)):[String(e)];yield this.sdkSessionStore.unobserve(t)})}};var Ei=class{constructor(e,t){this.intervalMs=100,this.shouldMonitor=!1,this.hasStarted=!1,this.unsubs=[],this.analysers={},this.store=e,this.actions=t}start(){return c(this,null,function*(){if(this.hasStarted)return;this.hasStarted=!0,k.d("starting audio level monitor for remote peers",this.store);let e=this.store.getState(Se);k.d("starting audio levels is connected to room",e),e&&(yield this.monitorAudioLevels());let t=this.store.subscribe(this.monitorAudioLevels.bind(this),Se);this.unsubs.push(t)})}stop(){return c(this,null,function*(){this.hasStarted&&(this.hasStarted=!1,this.shouldMonitor=!1,this.unsubs.forEach(e=>e()),k.d("stopped audio level monitor for remote peers"))})}monitorAudioLevels(){return c(this,null,function*(){if(!this.store.getState(Se)){this.shouldMonitor&&(k.i("room no longer connected, stopping audio level monitoring for remote"),this.shouldMonitor=!1);return}if(this.shouldMonitor)return;k.i("monitoring audio levels"),this.shouldMonitor=!0;let t=()=>{this.shouldMonitor?(this.logAllPeersAudioLevels(),setTimeout(t,this.intervalMs)):k.i("stopped monitoring audio levels")};setTimeout(t,1e3)})}logAllPeersAudioLevels(){return c(this,null,function*(){var r;if(!window.__triggerBeamEvent__)return;let t=this.store.getState(ie).filter(a=>!!a.audioTrack),i=[];for(let a of t){let o=this.actions.hmsSDKTracks[a.audioTrack],n=(r=o==null?void 0:o.stream)==null?void 0:r.nativeStream;if(a.joinedAt&&n){let l=yield this.getAudioLevel(a,n);l.level>0&&i.push(l)}}if(i.length>0){let a={event:"app-audio-level",data:i};window.__triggerBeamEvent__(JSON.stringify(a))}})}getAudioLevel(e,t){return c(this,null,function*(){this.analysers[t.id]||(this.analysers[t.id]=this.createAnalyserNode(t));let i=this.analysers[t.id],r=this.calculateAudioLevel(i);return{peerId:e.id,peerName:e.name,level:r}})}createAnalyserNode(e){this.audioContext||(this.audioContext=new AudioContext);let t=this.audioContext.createAnalyser();return this.audioContext.createMediaStreamSource(e).connect(t),t}calculateAudioLevel(e){let t=new Uint8Array(e.fftSize);e.getByteTimeDomainData(t);let i=.009,r=i;for(let n of t)r=Math.max(r,(n-128)/128);let a=(Math.log(i)-Math.log(r))/Math.log(i);return Math.ceil(Math.min(Math.max(a*100,0),100))}};var Pi=class{constructor(e,t,i){this.isRoomJoinCalled=!1;this.ignoredMessageTypes=[];this.setProgress=({type:e,progress:t})=>{this.setState(i=>{i.playlist[e].progress=t,i.playlist[e].currentTime=this.sdk.getPlaylistManager().getCurrentTime(e)},"playlistProgress")};this.syncPlaylistState=e=>{this.setState(t=>{Object.assign(t.playlist,w.convertPlaylist(this.sdk.getPlaylistManager()))},e)};this.sendPeerUpdateNotification=(e,t)=>{let i=this.store.getState(W(t.peerId)),r=Ti[e]||"peerUpdate";if(e===8)this.syncRoomState(r),this.updateMidCallPreviewRoomState(e,t);else if([0,1].includes(e))this.syncRoomState(r),i||(i=this.store.getState(W(t.peerId)));else if([12,13,14].includes(e))this.syncRoomState(r),i||(i=this.store.getState(W(t.peerId)));else{let a=w.convertPeer(t);this.setState(o=>{let n=o.peers[a.id];_e(n,a)&&(Z(n.auxiliaryTracks,a.auxiliaryTracks)&&(n.auxiliaryTracks=a.auxiliaryTracks),Object.assign(n,a)),i=a},r)}this.hmsNotifications.sendPeerUpdate(e,i)};this.getSDKHMSPeer=e=>this.sdk.getPeerMap()[e];this.setState=(e,t)=>this.store.namedSetState(e,t);this.store=e,this.sdk=t,this.hmsNotifications=i,this.sessionStore=new ki(this.sdk,this.setSessionStoreValueLocally.bind(this)),this.actionBatcher=new Mi(e)}getLocalTrack(e){return this.sdk.store.getLocalPeerTracks().find(t=>t.trackId===e)}get interactivityCenter(){return this.sdk.getInteractivityCenter()}setPlaylistSettings(e){this.sdk.updatePlaylistSettings(e)}refreshDevices(){return c(this,null,function*(){yield this.sdk.refreshDevices()})}unblockAudio(){return c(this,null,function*(){yield this.sdk.getAudioOutput().unblockAutoplay()})}setVolume(e,t){return c(this,null,function*(){t?yield this.setTrackVolume(e,t):(yield this.sdk.getAudioOutput().setVolume(e),this.syncRoomState("setOutputVolume"))})}setAudioOutputDevice(e){return c(this,null,function*(){(yield this.sdk.getAudioOutput().setDevice(e))&&this.setState(i=>{i.settings.audioOutputDeviceId=e},"setAudioOutputDevice")})}setPreferredLayer(e,t){return c(this,null,function*(){var r;let i=this.sdk.store.getTrackById(e);if(i)if(i instanceof _){if(t==="none"){k.d("layer none will be ignored");return}if(((r=this.store.getState(jr(e)))==null?void 0:r.preferredLayer)===t){k.d(`preferred layer is already ${t}`);return}this.setState(o=>{let n=o.tracks[e];n&&(n.preferredLayer=t)},"setPreferredLayer"),yield i.setPreferredLayer(t)}else k.d(`track ${e} is not a remote video track`);else this.logPossibleInconsistency(`track ${e} not present, unable to set preffer layer`)})}getAuthTokenByRoomCode(e,t){return this.sdk.getAuthTokenByRoomCode(e,t)}preview(e){return c(this,null,function*(){let t=this.store.getState(J);if(t==="Preview"||t==="Connecting"){this.logPossibleInconsistency("attempting to call preview while room is in preview/connecting");return}try{t!=="Connected"&&this.setState(i=>{i.room.roomState="Connecting"},"connecting"),yield this.sdkPreviewWithListeners(e)}catch(i){throw k.e("Cannot show preview. Failed to connect to room - ",i),i}})}cancelMidCallPreview(){return c(this,null,function*(){return this.sdk.cancelMidCallPreview()})}join(e){return c(this,null,function*(){if(this.isRoomJoinCalled){this.logPossibleInconsistency("room join is called again");return}try{this.isRoomJoinCalled=!0,this.setState(t=>{t.room.roomState="Connecting"},"join"),yield this.sdkJoinWithListeners(e)}catch(t){throw this.isRoomJoinCalled=!1,k.e("Failed to connect to room - ",t),t}})}leave(){return c(this,null,function*(){let e=this.store.getState(Se),t=!0;e||(t=!1,this.logPossibleInconsistency("room leave is called when no room is connected"));let i=this.store.getState(J);return this.setState(r=>{r.room.roomState="Disconnecting"},"leaving"),this.sdk.leave(t).then(()=>{this.resetState("leave"),this.beamSpeakerLabelsLogger&&this.beamSpeakerLabelsLogger.stop().catch(k.e),k.i("left room")}).catch(r=>{k.e("error in leaving room - ",r),this.setState(a=>{a.room.roomState=i},"revertLeave")})})}setScreenShareEnabled(e,t){return c(this,null,function*(){typeof t=="boolean"&&(t={audioOnly:t});try{e?yield this.startScreenShare(t):yield this.stopScreenShare()}catch(i){throw this.hmsNotifications.sendError(w.convertException(i)),i}})}addTrack(e,t="regular"){return c(this,null,function*(){yield this.sdk.addTrack(e,t),this.syncRoomState("addTrack")})}removeTrack(e){return c(this,null,function*(){yield this.sdk.removeTrack(e),this.syncRoomState("removeTrack")})}setLocalAudioEnabled(e){return c(this,null,function*(){let t=this.store.getState(Y);t&&(yield this.setEnabledTrack(t,e))})}setLocalVideoEnabled(e){return c(this,null,function*(){let t=this.store.getState($);t&&(yield this.setEnabledTrack(t,e))})}setEnabledTrack(e,t){return c(this,null,function*(){var a;if(((a=this.store.getState().tracks[e])==null?void 0:a.enabled)===t){this.logPossibleInconsistency(`local track[${e}] enabled state - ${t}`);return}this.setState(o=>{o.tracks[e]?o.tracks[e].displayEnabled=t:this.logPossibleInconsistency("track id not found for setEnabled")},"displayEnabled");try{yield this.setEnabledSDKTrack(e,t),this.syncRoomState("setEnabled")}catch(o){throw this.setState(n=>{n.tracks[e].displayEnabled=!t},"rollbackDisplayEnabled"),this.hmsNotifications.sendError(w.convertException(o)),o}let r=t?3:2;this.hmsNotifications.sendTrackUpdate(r,e)})}setAudioSettings(e){return c(this,null,function*(){let t=this.store.getState(Y);t&&(yield this.setSDKLocalAudioTrackSettings(t,e),this.syncRoomState("setAudioSettings"))})}setVideoSettings(e){return c(this,null,function*(){let t=this.store.getState($);t&&(yield this.setSDKLocalVideoTrackSettings(t,e),this.syncRoomState("setVideoSettings"))})}switchCamera(){return c(this,null,function*(){let e=this.store.getState($);if(e){let t=this.sdk.store.getLocalPeerTracks().find(i=>i.trackId===e);t&&(yield t.switchCamera(),this.syncRoomState("switchCamera"))}})}sendMessage(e){this.sendBroadcastMessage(e)}sendBroadcastMessage(e,t){return c(this,null,function*(){let{message_id:i,timestamp:r}=yield this.sdk.sendBroadcastMessage(e,t);this.updateMessageInStore({message:e,type:t,id:i,time:r})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getState(re),a=t.map(l=>r[l]),{message_id:o,timestamp:n}=yield this.sdk.sendGroupMessage(e,a,i);this.updateMessageInStore({message:e,recipientRoles:t,type:i,id:o,time:n})})}sendDirectMessage(e,t,i){return c(this,null,function*(){let{message_id:r,timestamp:a}=yield this.sdk.sendDirectMessage(e,t,i);this.updateMessageInStore({message:e,recipientPeer:t,type:i,id:r,time:a})})}updateMessageInStore(e){var r;if(!e.message)throw k.w("sendMessage","Failed to send message",e),Error(`sendMessage Failed - ${JSON.stringify(e)}`);let t=this.sdk.getLocalPeer(),i={read:!0,id:e.id,time:new Date(e.time),message:e.message,type:e.type||"chat",recipientPeer:e.recipientPeer,recipientRoles:e.recipientRoles,senderName:t==null?void 0:t.name,sender:t==null?void 0:t.peerId,senderRole:(r=t==null?void 0:t.role)==null?void 0:r.name,ignored:!!e.type&&this.ignoredMessageTypes.includes(e.type)};this.putMessageInStore(i)}setMessageRead(e,t){this.setState(i=>{t?i.messages.byID[t]?i.messages.byID[t].read=e:this.logPossibleInconsistency("no message with id is found"):i.messages.allIDs.forEach(r=>{i.messages.byID[r].read=e})},"setMessageRead")}attachVideo(e,t){return c(this,null,function*(){if(this.localAndVideoUnmuting(e))return new Promise(i=>{let r=this.store.subscribe(a=>c(this,null,function*(){a&&(yield this.attachVideoInternal(e,t),r(),i())}),Qt)});yield this.attachVideoInternal(e,t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.sdk.store.getTrackById(e);(i==null?void 0:i.type)==="video"?yield this.sdk.detachVideo(i,t):(t&&(t.srcObject=null),k.d("possible inconsistency detected - no video track found to remove sink"))})}addPluginToVideoTrack(e,t){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"add",t)})}addPluginsToVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"add")})}removePluginsFromVideoStream(e){return c(this,null,function*(){return this.addRemoveMediaStreamVideoPlugins(e,"remove")})}addPluginToAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"add")})}validateVideoPluginSupport(e){let t={};if(t.isSupported=!1,!e)return k.w("no plugin passed in for checking support"),t.errMsg="no plugin passed in for checking support",t;let i=this.store.getState($);if(!i)return k.w("video Track not added to local peer yet"),t.errMsg="call this function only after local peer has video track",t;let r=this.sdk.store.getTrackById(i);return r?t=r.validatePlugin(e):(k.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}validateAudioPluginSupport(e){let t={};if(t.isSupported=!1,!e)return k.w('no plugin passed in for checking support"'),t.errMsg='no plugin passed in for checking support"',t;let i=this.store.getState(Y);if(!i)return k.w("audio track not added to local peer yet"),t.errMsg="call this function only after local peer has audio track",t;let r=this.sdk.store.getTrackById(i);return r?t=r.validatePlugin(e):(k.w(`track ${i} not present, unable to validate plugin`),t.errMsg=`track ${i} not present, unable to validate plugin`),t}removePluginFromVideoTrack(e){return c(this,null,function*(){return this.addRemoveVideoPlugin(e,"remove")})}removePluginFromAudioTrack(e){return c(this,null,function*(){return this.addRemoveAudioPlugin(e,"remove")})}changeRole(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){yield this.sdk.changeRoleOfPeer(e,t,i)})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){let i=this.sdk.getRoles().filter(r=>e.includes(r.name));yield this.sdk.changeRoleOfPeersWithRoles(i,t)})}acceptChangeRole(e){return c(this,null,function*(){let t=e.requestedBy?this.getSDKHMSPeer(e.requestedBy.id):void 0;t||k.w(`peer for which role change is requested no longer available - ${e.requestedBy}`);let i={requestedBy:t,role:e.role,token:e.token};yield this.sdk.acceptChangeRole(i),this.removeRoleChangeRequest(e)})}raiseLocalPeerHand(){return c(this,null,function*(){yield this.sdk.raiseLocalPeerHand()})}lowerLocalPeerHand(){return c(this,null,function*(){yield this.sdk.lowerLocalPeerHand()})}raiseRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.raiseRemotePeerHand(e)})}lowerRemotePeerHand(e){return c(this,null,function*(){yield this.sdk.lowerRemotePeerHand(e)})}getPeerListIterator(e){let t=this.sdk.getPeerListIterator(e);return{hasNext:()=>t.hasNext(),next:()=>c(this,null,function*(){return(yield t.next()).map(r=>w.convertPeer(r))}),findPeers:()=>c(this,null,function*(){return(yield t.findPeers()).map(r=>w.convertPeer(r))}),getTotal:()=>t.getTotal()}}initAppData(e){this.setState(t=>{t.appData=e},"initAppData")}setAppData(e,t,i){let r=(t==null?void 0:t.constructor.name)==="Object";this.setState(a=>{if(a.appData)i&&r?Object.assign(a.appData[e],t):a.appData[e]=t;else{let o={[e]:t};a.appData=o}},`setAppData-${e}`)}rejectChangeRole(e){this.removeRoleChangeRequest(e)}endRoom(e,t){return c(this,null,function*(){let i=this.store.getState(gr);if(!(i!=null&&i.endRoom)){k.w("You are not allowed to perform this action - endRoom");return}let r=this.store.getState(J);this.setState(a=>{a.room.roomState="Disconnecting"},"endingRoom");try{yield this.sdk.endRoom(e,t),this.resetState("endRoom")}catch(a){k.e("error in ending room - ",a),this.setState(o=>{o.room.roomState=r},"revertEndRoom")}})}removePeer(e,t){return c(this,null,function*(){var r;let i=(r=this.sdk.getLocalPeer())==null?void 0:r.peerId;e!==i&&(yield this.sdk.removePeer(e,t))})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.sdk.startRTMPOrRecording(e)})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.sdk.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){yield this.sdk.startHLSStreaming(e)})}stopHLSStreaming(e){return c(this,null,function*(){yield this.sdk.stopHLSStreaming(e)})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.sdk.sendHLSTimedMetadata(e)})}changeName(e){return c(this,null,function*(){yield this.sdk.changeName(e)})}changeMetadata(e){return c(this,null,function*(){typeof e!="string"&&(e=JSON.stringify(e)),yield this.sdk.changeMetadata(e)})}setSessionMetadata(e){return c(this,null,function*(){yield this.sdk.setSessionMetadata(e),this.setState(t=>{t.sessionMetadata=e},"setSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"setSessionMetadata")})}populateSessionMetadata(){return c(this,null,function*(){let e=yield this.sdk.getSessionMetadata();this.setState(t=>{t.sessionMetadata=e},"populateSessionMetadata"),this.setSessionStoreValueLocally({key:"default",value:e},"populateSessionmetadata")})}setRemoteTrackEnabled(e,t){return c(this,null,function*(){if(typeof e=="string"){let i=this.sdk.store.getTrackById(e);i&&ya(i)?yield this.sdk.changeTrackState(i,t):this.logPossibleInconsistency(`No remote track with ID ${e} found for change track state`)}else Array.isArray(e)&&e.forEach(i=>this.setRemoteTrackEnabled(i,t))})}setRemoteTracksEnabled(e){return c(this,null,function*(){let t={enabled:e.enabled,type:e.type,source:e.source};if(e.roles){let i=this.store.getState(re);t.roles=e.roles.map(r=>i[r])}yield this.sdk.changeMultiTrackState(t)})}setLogLevel(e){k.level=e,this.sdk.setLogLevel(e)}setFrameworkInfo(e){this.sdk.setFrameworkInfo(e)}ignoreMessageTypes(e,t=!1){if(t)this.ignoredMessageTypes=e;else for(let i of e)this.ignoredMessageTypes.includes(i)||this.ignoredMessageTypes.push(i)}enableBeamSpeakerLabelsLogging(){return c(this,null,function*(){this.beamSpeakerLabelsLogger||(k.i("enabling beam speaker labels logging"),this.beamSpeakerLabelsLogger=new Ei(this.store,this),yield this.beamSpeakerLabelsLogger.start())})}resetState(e="resetState"){this.isRoomJoinCalled=!1,k.cleanup(),this.setState(t=>{Object.assign(t,rt())},e)}sdkJoinWithListeners(e){return c(this,null,function*(){yield this.sdk.join(e,{onJoin:this.onJoin.bind(this),onPreview:this.onPreview.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onTrackUpdate:this.onTrackUpdate.bind(this),onMessageReceived:this.onMessageReceived.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onRoleChangeRequest:this.onRoleChangeRequest.bind(this),onRoleUpdate:this.onRoleUpdate.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onChangeTrackStateRequest:this.onChangeTrackStateRequest.bind(this),onChangeMultiTrackStateRequest:this.onChangeMultiTrackStateRequest.bind(this),onRemovedFromRoom:this.onRemovedFromRoom.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this),onSessionStoreUpdate:this.onSessionStoreUpdate.bind(this),onPollsUpdate:this.onPollsUpdate.bind(this),onWhiteboardUpdate:this.onWhiteboardUpdate.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)}),this.sdk.addConnectionQualityListener({onConnectionQualityUpdate:this.onConnectionQualityUpdate.bind(this)})})}onRemovedFromRoom(e){var r;let t=this.store.getState(W((r=e.requestedBy)==null?void 0:r.peerId));this.hmsNotifications.sendLeaveRoom(y(S({},e),{requestedBy:t||void 0}));let i=e.roomEnded||!t?"roomEnded":"removedFromRoom";k.i(`resetting state after peer removed ${i}`,e),this.resetState(i)}onDeviceChange(e){let t=e.devices;if(!t)return;let i=this.store.getState(j);if(this.setState(r=>{Z(r.devices.audioInput,t.audioInput)||(r.devices.audioInput=t.audioInput),Z(r.devices.videoInput,t.videoInput)||(r.devices.videoInput=t.videoInput),Z(r.devices.audioOutput,t.audioOutput)||(r.devices.audioOutput=t.audioOutput);let a=this.sdk.getLocalPeer();i!=null&&i.id&&a&&Object.assign(r.settings,this.getMediaSettings(a))},"deviceChange"),e.selection){let r=w.convertDeviceChangeUpdate(e);this.hmsNotifications.sendDeviceChange(r)}}sdkPreviewWithListeners(e){return c(this,null,function*(){yield this.sdk.preview(e,{onPreview:this.onPreview.bind(this),onError:this.onError.bind(this),onReconnected:this.onReconnected.bind(this),onReconnecting:this.onReconnecting.bind(this),onDeviceChange:this.onDeviceChange.bind(this),onRoomUpdate:this.onRoomUpdate.bind(this),onPeerUpdate:this.onPeerUpdate.bind(this),onNetworkQuality:this.onNetworkQuality.bind(this)}),this.sdk.addAudioListener({onAudioLevelUpdate:this.onAudioLevelUpdate.bind(this)})})}onNetworkQuality(e){this.setState(t=>{var r;let i=t.room.localPeer||((r=this.sdk.getLocalPeer())==null?void 0:r.peerId);i&&(t.connectionQualities[i]={peerID:i,downlinkQuality:e})},"ConnectionQuality")}onSessionStoreUpdate(e){this.setSessionStoreValueLocally(e,"sessionStoreUpdate")}onPollsUpdate(e,t){let i=fi[e];this.setState(r=>{let a=t.reduce((o,n)=>{var l;return o[n.id]=y(S({},n),{questions:(l=n.questions)==null?void 0:l.map(u=>{var p,m;return y(S({},u),{answer:u.answer?S({},u.answer):void 0,options:(p=u.options)==null?void 0:p.map(g=>S({},g)),responses:(m=u.responses)==null?void 0:m.map(g=>S({},g))})})}),o},{});Pa(r.polls,a)},i),t.forEach(r=>this.hmsNotifications.sendPollUpdate(e,r.id))}onWhiteboardUpdate(e){this.setState(t=>{t.whiteboards[e.id]=e},"whiteboardUpdate")}startScreenShare(e){return c(this,null,function*(){this.store.getState(zt)?this.logPossibleInconsistency("start screenshare is called while it's on"):(yield this.sdk.startScreenShare(()=>this.syncRoomState("screenshareStopped"),e),this.syncRoomState("startScreenShare"))})}stopScreenShare(){return c(this,null,function*(){this.store.getState(zt)?(yield this.sdk.stopScreenShare(),this.syncRoomState("stopScreenShare")):this.logPossibleInconsistency("stop screenshare is called while it's not on")})}attachVideoInternal(e,t){return c(this,null,function*(){let i=this.sdk.store.getTrackById(e);i||(i=this.getLocalTrack(e)),i&&i.type==="video"?yield this.sdk.attachVideo(i,t):this.logPossibleInconsistency("no video track found to add sink")})}syncRoomState(e){e=`${e}_fullSync`,k.time(`store-sync-${e}`);let t={},i=[],r={},a={},o={},n,l=this.sdk.getPeers();for(let g of l){let f=w.convertPeer(g);t[f.id]=f,i.push(f.id),o[f.id]={peerID:f.id,downlinkQuality:g.networkQuality||-1};let R=[g.audioTrack,g.videoTrack,...g.auxiliaryTracks];for(let b of R){if(!b)continue;let G=w.convertTrack(b);r[G.id]=G}if(g.isLocal){let b=g;n=this.getPreviewFields(b),Object.assign(a,this.getMediaSettings(b))}}let u=this.sdk.getRecordingState(),p=this.sdk.getRTMPState(),m=this.sdk.getHLSState();this.setState(g=>{var b;g.room.peers=i;let f=g.peers,R=g.tracks;ka(f,t),Ea(R,r),Object.assign(g.settings,a),Object.assign(g.connectionQualities,o),(b=g.preview)!=null&&b.localPeer&&(n!=null&&n.localPeer)?Object.assign(g.preview,n):g.preview=n,Object.assign(g.roles,w.convertRoles(this.sdk.getRoles())),Object.assign(g.playlist,w.convertPlaylist(this.sdk.getPlaylistManager())),Object.assign(g.room,w.convertRecordingStreamingState(u,p,m)),Object.assign(g.templateAppData,this.sdk.getTemplateAppData())},e),k.timeEnd(`store-sync-${e}`)}onPreview(e){this.setState(t=>{var i;Object.assign(t.room,w.convertRoom(e,(i=this.sdk.getLocalPeer())==null?void 0:i.peerId)),t.room.roomState="Preview"},"previewStart"),this.syncRoomState("previewSync")}onJoin(e){let t=this.sdk.getPlaylistManager();this.audioPlaylist=new bt(t,"audio",this.syncPlaylistState.bind(this),this.store),this.videoPlaylist=new bt(t,"video",this.syncRoomState.bind(this),this.store),this.syncRoomState("joinSync"),this.setState(i=>{var r;Object.assign(i.room,w.convertRoom(e,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId)),i.room.isConnected=!0,i.room.roomState="Connected"},"joined"),t.onProgress(this.setProgress),t.onNewTrackStart(i=>{this.syncPlaylistState(`${i.type}PlaylistUpdate`)}),t.onPlaylistEnded(i=>{this.syncPlaylistState(`${i}PlaylistEnded`)}),t.onCurrentTrackEnded(i=>{this.hmsNotifications.sendPlaylistTrackEnded(w.convertPlaylistItem(t,i)),this.syncPlaylistState(`${i.type}PlaylistItemEnded`)})}onRoomUpdate(e,t){this.setState(i=>{var r;Object.assign(i.room,w.convertRoom(t,(r=this.sdk.getLocalPeer())==null?void 0:r.peerId))},e)}onPeerUpdate(e,t){if(![4,5].includes(e)){if(Array.isArray(t)){let i=this.store.getState(F),r=t.filter(o=>!i[o.peerId]);if(this.syncRoomState("peersJoined"),this.store.getState(Se)){let o=[];for(let n of t){let l=this.store.getState(W(n.peerId));l&&o.push(l)}this.hmsNotifications.sendPeerList(o)}else r.forEach(o=>{let n=this.store.getState(W(o.peerId));n&&this.hmsNotifications.sendPeerUpdate(0,n)});return}this.sendPeerUpdateNotification(e,t)}}onTrackUpdate(e,t,i){if(e===1)this.hmsNotifications.sendTrackUpdate(e,t.trackId),this.handleTrackRemove(t,i);else if([0,1].includes(e)){let r=Pt[e];this.syncRoomState(r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}else{let r=Pt[e]||"trackUpdate",a=w.convertTrack(t);this.setState(o=>{let n=o.tracks[a.id];_e(n,a)&&(ts(n,a),Object.assign(n,a))},r),this.hmsNotifications.sendTrackUpdate(e,t.trackId)}}onMessageReceived(e){let t=w.convertMessage(e,this.store.getState(ne));t.read=!1,t.ignored=this.ignoredMessageTypes.includes(t.type),this.putMessageInStore(t),this.hmsNotifications.sendMessageReceived(t)}putMessageInStore(e){e.ignored||this.actionBatcher.setState(t=>{t.messages.byID[e.id]=e,t.messages.allIDs.push(e.id)},"newMessage",150)}onAudioLevelUpdate(e){this.setState(t=>{let i={};e.forEach(a=>{if(!a.track||!a.peer)return;let o=a.track.trackId;i[o]=a.audioLevel,t.speakers[o]||(t.speakers[o]={audioLevel:a.audioLevel,peerID:a.peer.peerId,trackID:o})});let r=Object.entries(t.speakers);for(let[a,o]of r)o.audioLevel=i[a]||0,o.audioLevel===0&&delete t.speakers[a]},"audioLevel")}onConnectionQualityUpdate(e){this.setState(t=>{e.forEach(i=>{let r=i.peerID;r&&(t.connectionQualities[r]?Object.assign(t.connectionQualities[r],i):t.connectionQualities[r]=i)})},"connectionQuality")}onChangeTrackStateRequest(e){var a;let t=this.store.getState(W((a=e.requestedBy)==null?void 0:a.peerId)),i=this.getStoreLocalTrackIDfromSDKTrack(e.track),r=this.store.getState(kt(i));if(!r)return this.logPossibleInconsistency(`Not found track for which track state change was requested, ${e.track}`);e.enabled||this.syncRoomState("changeTrackStateRequest"),this.hmsNotifications.sendChangeTrackStateRequest({requestedBy:t||void 0,track:r,enabled:e.enabled})}onChangeMultiTrackStateRequest(e){var a;let t=this.store.getState(W((a=e.requestedBy)==null?void 0:a.peerId));e.enabled||this.syncRoomState("changeMultiTrackStateRequest");let i=[],r=this.store.getState(D);for(let o of e.tracks){let n=this.getStoreLocalTrackIDfromSDKTrack(o);n&&r[n]&&i.push(r[n])}this.hmsNotifications.sendChangeMultiTrackStateRequest({requestedBy:t||void 0,tracks:i,enabled:e.enabled,type:e.type,source:e.source})}onReconnected(){this.syncRoomState("reconnectedSync"),this.hmsNotifications.sendReconnected(),this.setState(e=>{e.room.roomState=e.room.isConnected?"Connected":"Preview"},"reconnected")}onReconnecting(e){let t=w.convertException(e);k.e("Reconnection: received error from sdk",t),this.hmsNotifications.sendReconnecting(t),this.setState(i=>{i.room.roomState="Reconnecting",i.errors.push(t)},"reconnecting")}onError(e){let t=w.convertException(e);t.isTerminal?(this.leave().then(()=>k.e("error from SDK, left room.")),this.setState(i=>{i.room.roomState="Failed",i.errors.push(t)},"errorTerminal")):this.store.getState().errors.length<50&&this.setState(r=>{r.errors.push(t)},"error"),this.syncRoomState("errorSync"),this.hmsNotifications.sendError(t),k.e("received error from sdk",t instanceof T?`${t}`:t)}handleTrackRemove(e,t){this.setState(i=>{let r=i.peers[t.peerId],a=i.tracks,o=e.trackId;if(this.isSameStoreSDKTrack(o,r==null?void 0:r.audioTrack))r==null||delete r.audioTrack;else if(this.isSameStoreSDKTrack(o,r==null?void 0:r.videoTrack))r==null||delete r.videoTrack;else{let n=r==null?void 0:r.auxiliaryTracks.indexOf(o);n>-1&&this.isSameStoreSDKTrack(o,r==null?void 0:r.auxiliaryTracks[n])&&(r==null||r.auxiliaryTracks.splice(n,1))}delete a[o]},"trackRemoved")}setEnabledSDKTrack(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setEnabled(t):this.logPossibleInconsistency(`track ${e} not present, unable to enabled/disable`)})}setSDKLocalVideoTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}setSDKLocalAudioTrackSettings(e,t){return c(this,null,function*(){let i=this.getLocalTrack(e);i?yield i.setSettings(t):this.logPossibleInconsistency(`local track ${e} not present, unable to set settings`)})}getMediaSettings(e){var a;let t=this.store.getState(ur),i=e.audioTrack,r=e.videoTrack;return{audioInputDeviceId:(i==null?void 0:i.settings.deviceId)||t.audioInputDeviceId,videoInputDeviceId:(r==null?void 0:r.settings.deviceId)||t.videoInputDeviceId,audioOutputDeviceId:(a=this.sdk.getAudioOutput().getDevice())==null?void 0:a.deviceId}}getPreviewFields(e){var i,r;if(!e.isInPreview())return;let t=w.convertPeer(e);return{localPeer:t.id,audioTrack:t.audioTrack,videoTrack:t.videoTrack,asRole:((i=e.asRole)==null?void 0:i.name)||((r=e.role)==null?void 0:r.name)}}setTrackVolume(e,t){return c(this,null,function*(){let i=this.sdk.store.getTrackById(t);i?i instanceof Ee?(yield i.setVolume(e),this.setState(r=>{let a=r.tracks[t];a&&a.type==="audio"&&(a.volume=e)},"trackVolume")):k.w(`track ${t} is not an audio track`):this.logPossibleInconsistency(`track ${t} not present, unable to set volume`)})}localAndVideoUnmuting(e){let t=this.store.getState(j);if((t==null?void 0:t.videoTrack)!==e)return!1;let i=this.store.getState(hr),r=this.store.getState(Qt);return i&&!r}logPossibleInconsistency(e){k.w("possible inconsistency detected - ",e)}addRemoveVideoPlugin(e,t,i){return c(this,null,function*(){if(!e){k.w("Invalid plugin received in store");return}let r=this.store.getState($);if(r){let a=this.getLocalTrack(r);a?(t==="add"?yield a.addPlugin(e,i):t==="remove"&&(yield a.removePlugin(e)),this.syncRoomState(`${t}VideoPlugin`)):this.logPossibleInconsistency(`track ${r} not present, unable to ${t} plugin`)}})}addRemoveMediaStreamVideoPlugins(e,t){return c(this,null,function*(){if(e.length===0){k.w("Invalid plugin received in store");return}let i=this.store.getState($);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addStreamPlugins(e):t==="remove"&&(yield r.removeStreamPlugins(e)),this.syncRoomState(`${t}MediaStreamPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}})}addRemoveAudioPlugin(e,t){return c(this,null,function*(){if(!e){k.w("Invalid plugin received in store");return}let i=this.store.getState(Y);if(i){let r=this.getLocalTrack(i);r?(t==="add"?yield r.addPlugin(e):t==="remove"&&(yield r.removePlugin(e)),this.syncRoomState(`${t}AudioPlugin`)):this.logPossibleInconsistency(`track ${i} not present, unable to ${t} plugin`)}})}isSameStoreSDKTrack(e,t){var i;return t?((i=this.sdk.store.getTrackById(t))==null?void 0:i.trackId)===e:!1}onRoleChangeRequest(e){this.setState(t=>{t.roleChangeRequests.length===0&&t.roleChangeRequests.push(w.convertRoleChangeRequest(e))},"roleChangeRequest")}removeRoleChangeRequest(e){this.setState(t=>{let i=t.roleChangeRequests.findIndex(r=>r.token===e.token);i!==-1&&t.roleChangeRequests.splice(i,1)},"removeRoleChangeRequest")}onRoleUpdate(){this.syncRoomState("roleUpdate")}getStoreLocalTrackIDfromSDKTrack(e){return this.store.getState(pr).find(i=>{var r;return((r=this.sdk.store.getTrackById(i))==null?void 0:r.trackId)===e.trackId})}updateMidCallPreviewRoomState(e,t){t.isLocal&&e===8&&this.store.getState(Sr)&&this.setState(i=>{i.room.roomState="Connected"},"midCallPreviewCompleted")}setSessionStoreValueLocally(e,t="setSessionStore"){let i=Array.isArray(e)?e:[e];this.setState(r=>{i.forEach(a=>{r.sessionStore[a.key]=a.value})},t)}};var Ai=s=>N?`${s} ${document.title}`:s;var Rt=class{constructor(e){this.recording={server:{running:!1},browser:{running:!1},hls:{running:!1}};this.rtmp={running:!1};this.hls={running:!1,variants:[]};this.id=e}};var bi=class{constructor(e,t){this.eventBus=e;this.listener=t;this.TAG="[NetworkTestManager]";this.controller=new AbortController;this.start=e=>c(this,null,function*(){var u;if(!e)return;let{url:t,timeout:i,scoreMap:r}=e,a=this.controller.signal,o=Date.now(),n=0,l=X(i).then(()=>{this.controller.abort()});try{let m=(u=(yield fetch(`${t}?${Date.now()}`,{signal:a})).body)==null?void 0:u.getReader();if(!m)throw Error("unable to process request");let g=()=>c(this,null,function*(){if(m)try{let f=!1;for(;!f;){let{value:R,done:b}=yield m.read();f=b,R&&(n+=R.byteLength,this.sendScore({scoreMap:r,downloadedSize:n,startTime:o}))}}catch(f){f.name!=="AbortError"&&d.d(this.TAG,f)}});return Promise.race([g(),l]).then(()=>{this.sendScore({scoreMap:r,downloadedSize:n,startTime:o,finished:!0})}).catch(f=>{d.d(this.TAG,f),this.updateScoreToListener(0),this.eventBus.analytics.publish(M.previewNetworkQuality({error:f.message}))})}catch(p){p.name!=="AbortError"?(d.d(this.TAG,p),this.updateScoreToListener(0),this.eventBus.analytics.publish(M.previewNetworkQuality({error:p.message}))):d.d(this.TAG,p)}});this.stop=()=>{this.controller.signal.aborted||this.controller.abort()};this.sendScore=({scoreMap:e,downloadedSize:t,startTime:i,finished:r=!1})=>{let a=(Date.now()-i)/1e3,n=t/1024/a*8,l=-1;for(let u in e){let p=e[u];n>=p.low&&(!p.high||n<=p.high)&&(l=Number(u))}this.updateScoreToListener(l),r&&this.eventBus.analytics.publish(M.previewNetworkQuality({score:l,downLink:n.toFixed(2)}))}}updateScoreToListener(e){var t,i;e!==this.score&&(this.score=e,(i=(t=this.listener)==null?void 0:t.onNetworkQuality)==null||i.call(t,e))}};var Ht=class{constructor(e,t,i,r,a,o){this.store=e;this.transport=t;this.deviceManager=i;this.publish=r;this.removeAuxiliaryTrack=a;this.listener=o;this.handleLocalPeerRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var a;let r=this.store.getLocalPeer();r&&(yield this.diffRolesAndPublishTracks({oldRole:e,newRole:t}),(a=this.listener)==null||a.onPeerUpdate(8,r))});this.diffRolesAndPublishTracks=i=>c(this,[i],function*({oldRole:e,newRole:t}){var f,R,b,G,et,us;let r=new Set(e.publishParams.allowed),a=new Set(t.publishParams.allowed),o=this.removeTrack(r,a,"video"),n=this.removeTrack(r,a,"audio"),l=this.removeTrack(r,a,"screen"),u=this.hasSimulcastDifference((f=e.publishParams.simulcast)==null?void 0:f.video,(R=t.publishParams.simulcast)==null?void 0:R.video),p=this.hasSimulcastDifference((b=e.publishParams.simulcast)==null?void 0:b.screen,(G=t.publishParams.simulcast)==null?void 0:G.screen),m=(us=(et=this.store.getLocalPeer())==null?void 0:et.videoTrack)==null?void 0:us.enabled;yield this.removeAudioTrack(n),yield this.removeVideoTracks(o||u),yield this.removeScreenTracks(l||p);let g=this.getSettings();u&&(g.isVideoMuted=!m),yield this.publish(g),yield this.syncDevices(g,t)})}syncDevices(e,t){return c(this,null,function*(){(!e.isAudioMuted||!e.isVideoMuted)&&t.publishParams.allowed.length>0&&(yield this.deviceManager.init(!0))})}removeVideoTracks(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.videoTrack&&(t.videoTrack.isPublished?yield this.transport.unpublish([t.videoTrack]):yield t.videoTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.videoTrack,t),t.videoTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="video")})}removeAudioTrack(e){return c(this,null,function*(){var i;if(!e)return;let t=this.store.getLocalPeer();t!=null&&t.audioTrack&&(t.audioTrack.isPublished?yield this.transport.unpublish([t.audioTrack]):yield t.audioTrack.cleanup(),(i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t),t.audioTrack=void 0),yield this.removeAuxTracks(r=>r.source!=="screen"&&r.type==="audio")})}removeScreenTracks(e){return c(this,null,function*(){e&&(yield this.removeAuxTracks(t=>t.source==="screen"))})}removeAuxTracks(e){return c(this,null,function*(){let t=this.store.getLocalPeer();if(t!=null&&t.auxiliaryTracks){let i=[...t.auxiliaryTracks];for(let r of i)e(r)&&(yield this.removeAuxiliaryTrack(r.trackId))}})}removeTrack(e,t,i){return e.has(i)&&!t.has(i)}hasSimulcastDifference(e,t){var i,r,a;return!e&&!t?!1:((i=e==null?void 0:e.layers)==null?void 0:i.length)!==((r=t==null?void 0:t.layers)==null?void 0:r.length)?!0:!!((a=e==null?void 0:e.layers)!=null&&a.some(o=>{var l;let n=(l=t==null?void 0:t.layers)==null?void 0:l.find(u=>u.rid===o.rid);return(n==null?void 0:n.maxBitrate)!==o.maxBitrate||(n==null?void 0:n.maxFramerate)!==o.maxFramerate}))}getSettings(){var t,i,r;let e=(t=this.store.getConfig())==null?void 0:t.settings;return{isAudioMuted:(i=e==null?void 0:e.isAudioMuted)!=null?i:!0,isVideoMuted:(r=e==null?void 0:e.isVideoMuted)!=null?r:!0,audioInputDeviceId:(e==null?void 0:e.audioInputDeviceId)||"default",audioOutputDeviceId:(e==null?void 0:e.audioOutputDeviceId)||"default",videoDeviceId:(e==null?void 0:e.videoDeviceId)||"default"}}};var rs=class{constructor(){this.TAG="[HTTPAnalyticsTransport]";this.failedEvents=new de("client-events");this.isConnected=!0;this.env=null;this.websocketURL=""}setEnv(e){this.env=e,this.flushFailedEvents()}setWebsocketEndpoint(e){this.websocketURL=e}sendEvent(e){if(!this.env){this.addEventToStorage(e);return}let t={event:e.name,payload:e.properties,event_id:String(e.timestamp),peer:e.metadata.peer,timestamp:e.timestamp,device_id:e.device_id,cluster:{websocket_url:this.websocketURL}},i=this.env==="prod"?ia:ra;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.metadata.token}`,user_agent_v2:e.metadata.userAgent},body:JSON.stringify(t)}).then(r=>{if(r.status===401){this.removeFromStorage(e);return}if(r.status!==200)throw Error(r.statusText);this.removeFromStorage(e)}).catch(r=>{d.v(this.TAG,"Failed to send event",r,e),this.addEventToStorage(e)})}flushFailedEvents(){let e=this.failedEvents.get();e==null||e.forEach(t=>this.sendEvent(t))}addEventToStorage(e){let t=this.failedEvents.get()||[];t.find(i=>i.timestamp===e.timestamp)||(t.length===100&&t.shift(),t.push(e),this.failedEvents.set(t))}removeFromStorage(e){let t=this.failedEvents.get()||[],i=t.findIndex(r=>r.timestamp===e.timestamp);i>-1&&(t.splice(i,1),this.failedEvents.set(t))}},ve=new rs;var It=class{constructor(){this.knownRoles={};this.peers={};this.tracks=new Map;this.peerTrackStates={};this.speakers=[];this.roleDetailsArrived=!1;this.env="prod";this.simulcastEnabled=!1;this.userAgent=ut(this.env);this.polls=new Map;this.whiteboards=new Map}getConfig(){return this.config}setSimulcastEnabled(e){this.simulcastEnabled=e}getEnv(){return this.env}getPublishParams(){let e=this.getLocalPeer(),t=(e==null?void 0:e.asRole)||(e==null?void 0:e.role);return t==null?void 0:t.publishParams}getRoom(){return this.room}getPolicyForRole(e){return this.knownRoles[e]}getKnownRoles(){return this.knownRoles}getTemplateAppData(){return this.templateAppData}getLocalPeer(){if(this.localPeerId&&this.peers[this.localPeerId])return this.peers[this.localPeerId]}getRemotePeers(){return Object.values(this.peers).filter(e=>!e.isLocal)}getPeers(){return Object.values(this.peers)}getPeerMap(){return this.peers}getPeerById(e){if(this.peers[e])return this.peers[e]}getTracksMap(){return this.tracks}getTracks(){return Array.from(this.tracks.values())}getVideoTracks(){return this.getTracks().filter(e=>e.type==="video")}getRemoteVideoTracks(){return this.getTracks().filter(e=>e instanceof _)}getAudioTracks(){return this.getTracks().filter(e=>e.type==="audio")}getPeerTracks(e){let t=e?this.peers[e]:void 0,i=[];return t!=null&&t.videoTrack&&i.push(t.videoTrack),t!=null&&t.audioTrack&&i.push(t.audioTrack),i.concat((t==null?void 0:t.auxiliaryTracks)||[])}getLocalPeerTracks(){return this.getPeerTracks(this.localPeerId)}hasTrack(e){return this.tracks.has(e)}getTrackById(e){var r,a;let t=Array.from(this.tracks.values()).find(o=>o.trackId===e);if(t)return t;let i=this.getLocalPeer();if(i){if((r=i.audioTrack)!=null&&r.isPublishedTrackId(e))return i.audioTrack;if((a=i.videoTrack)!=null&&a.isPublishedTrackId(e))return i.videoTrack}}getPeerByTrackId(e){let t=Array.from(this.tracks.values()).find(i=>i.trackId===e);return t!=null&&t.peerId?this.peers[t.peerId]:void 0}getSpeakers(){return this.speakers}getSpeakerPeers(){return this.speakers.map(e=>e.peer)}getUserAgent(){return this.userAgent}createAndSetUserAgent(e){this.userAgent=ut(this.env,e)}setRoom(e){this.room=e}setKnownRoles(e){var i,r;if(this.knownRoles=e.known_roles,this.addPluginsToRoles(e.plugins),this.roleDetailsArrived=!0,this.templateAppData=e.app_data,!this.simulcastEnabled)return;let t=(i=this.knownRoles[e.name])==null?void 0:i.publishParams;this.videoLayers=this.convertSimulcastLayers((r=t.simulcast)==null?void 0:r.video),this.updatePeersPolicy()}hasRoleDetailsArrived(){return this.roleDetailsArrived}setConfig(e){var t,i,r;if(Q.rememberDevices(!!e.rememberDeviceSelection),e.rememberDeviceSelection){let a=Q.getSelection();a&&(e.settings||(e.settings={}),(t=a.audioInput)!=null&&t.deviceId&&(e.settings.audioInputDeviceId=e.settings.audioInputDeviceId||a.audioInput.deviceId),(i=a.audioOutput)!=null&&i.deviceId&&(e.settings.audioOutputDeviceId=e.settings.audioOutputDeviceId||a.audioOutput.deviceId),(r=a.videoInput)!=null&&r.deviceId&&(e.settings.videoDeviceId=e.settings.videoDeviceId||a.videoInput.deviceId))}e.autoManageVideo=e.autoManageVideo!==!1,e.autoManageWakeLock=e.autoManageWakeLock!==!1,this.config=e,this.setEnv()}addPeer(e){this.peers[e.peerId]=e,e.isLocal&&(this.localPeerId=e.peerId)}addTrack(e){this.tracks.set(e,e)}getTrackState(e){return this.peerTrackStates[e]}setTrackState(e){this.peerTrackStates[e.trackInfo.track_id]=e}removePeer(e){this.localPeerId===e&&(this.localPeerId=void 0),delete this.peers[e]}removeTrack(e){this.tracks.delete(e)}updateSpeakers(e){this.speakers=e}updateAudioOutputVolume(e){return c(this,null,function*(){for(let t of this.getAudioTracks())yield t.setVolume(e)})}updateAudioOutputDevice(e){return c(this,null,function*(){let t=[];this.getAudioTracks().forEach(i=>{i instanceof te&&t.push(i.setOutputDevice(e))}),yield Promise.all(t)})}getSimulcastLayers(e){var t;return!this.simulcastEnabled||!["screen","regular"].includes(e)?[]:e==="screen"?[]:((t=this.videoLayers)==null?void 0:t.layers)||[]}convertSimulcastLayers(e){if(e)return y(S({},e),{layers:(e.layers||[]).map(t=>y(S({},t),{maxBitrate:t.maxBitrate*1e3}))})}getSimulcastDefinitionsForPeer(e,t){var n,l,u;if([!e||!e.role,t==="screen",!this.simulcastEnabled].some(p=>!!p))return[];let i=this.getPolicyForRole(e.role.name).publishParams,r,a,o;return t==="regular"?(r=(n=i.simulcast)==null?void 0:n.video,a=i.video.width,o=i.video.height):t==="screen"&&(r=(l=i.simulcast)==null?void 0:l.screen,a=i.screen.width,o=i.screen.height),((u=r==null?void 0:r.layers)==null?void 0:u.map(p=>{let m=be[p.rid],g={width:Math.floor(a/p.scaleResolutionDownBy),height:Math.floor(o/p.scaleResolutionDownBy)};return{layer:m,resolution:g}}))||[]}setPoll(e){this.polls.set(e.id,e)}getPoll(e){return this.polls.get(e)}setWhiteboard(e){this.whiteboards.set(e.id,e)}getWhiteboard(e){return e?this.whiteboards.get(e):this.whiteboards.values().next().value}getErrorListener(){return this.errorListener}cleanup(){let e=this.getTracks();for(let t of e)t.cleanup();this.room=void 0,this.config=void 0,this.localPeerId=void 0,this.roleDetailsArrived=!1}setErrorListener(e){this.errorListener=e}updatePeersPolicy(){this.getPeers().forEach(e=>{var t;if(!e.role){(t=this.errorListener)==null||t.onError(h.GenericErrors.InvalidRole("VALIDATION",""));return}e.role=this.getPolicyForRole(e.role.name)})}addPluginsToRoles(e){if(!e)return;let t=(i,r,a)=>{var n;let o=this.knownRoles[i].permissions;o[r]||(o[r]=[]),(n=o[r])==null||n.push(a)};Object.keys(e).forEach(i=>{var o,n,l;let r=i;if(!e[r])return;let a=e[r].permissions;(o=a==null?void 0:a.admin)==null||o.forEach(u=>t(u,r,"admin")),(n=a==null?void 0:a.reader)==null||n.forEach(u=>t(u,r,"read")),(l=a==null?void 0:a.writer)==null||l.forEach(u=>t(u,r,"write"))})}setEnv(){var r;let t=((r=this.config)==null?void 0:r.initEndpoint).split("https://")[1],i="prod";t.startsWith("prod")?i="prod":t.startsWith("qa")?i="qa":t.startsWith("dev")&&(i="dev"),this.env=i,ve.setEnv(i)}};var Ri=class{constructor(){this.TAG="[WakeLockManager]";this.wakeLock=null;this.acquireLock=()=>c(this,null,function*(){yield this.requestWakeLock(),document==null||document.addEventListener("visibilitychange",this.visibilityHandler)});this.cleanup=()=>c(this,null,function*(){if(this.wakeLock&&!this.wakeLock.released)try{yield this.wakeLock.release(),d.d(this.TAG,"Wake lock released")}catch(e){let t=e;d.w(this.TAG,"Error while releasing wake lock",`name=${t.name}, message=${t.message}`)}this.wakeLock=null});this.visibilityHandler=()=>c(this,null,function*(){(document==null?void 0:document.visibilityState)==="visible"&&(!this.wakeLock||this.wakeLock.released)&&(d.d(this.TAG,"Re-acquiring wake lock due to visibility change"),yield this.requestWakeLock())});this.requestWakeLock=()=>c(this,null,function*(){try{if(!("wakeLock"in navigator)){d.d(this.TAG,"Wake lock feature not supported");return}this.wakeLock=yield navigator.wakeLock.request("screen"),d.d(this.TAG,"Wake lock acquired")}catch(e){let t=e;d.w(this.TAG,"Error acquiring wake lock",`name=${t.name}, message=${t.message}`)}})}};var Hi=class{constructor(e){this.store=e;this.bufferSize=100;this.TAG="[AnalyticsEventsService]";this.transport=null;this.pendingEvents=[];this.level=1}setTransport(e){this.transport=e}reset(){this.transport=null,this.pendingEvents=[]}queue(e){if(e.level>=this.level&&(this.pendingEvents.push(e),this.pendingEvents.length>this.bufferSize)){let t=this.pendingEvents.shift();d.d(this.TAG,"Max buffer size reached","Removed event to accommodate new events",t)}return this}flushFailedClientEvents(){ve.flushFailedEvents()}flush(){var e;try{for(;this.pendingEvents.length>0;){let t=this.pendingEvents.shift();t&&(t.metadata.peer.peer_id=(e=this.store.getLocalPeer())==null?void 0:e.peerId,t.metadata.userAgent=this.store.getUserAgent(),this.transport&&this.transport.transportProvider.isConnected?this.transport.sendEvent(t):this.sendClientEventOnHTTP(t))}}catch(t){d.w(this.TAG,"Flush Failed",t)}}sendClientEventOnHTTP(e){var r,a,o,n;let t=this.store.getRoom(),i=this.store.getLocalPeer();e.metadata.token=(r=this.store.getConfig())==null?void 0:r.authToken,e.metadata.peer={session_id:t==null?void 0:t.sessionId,room_id:t==null?void 0:t.id,room_name:t==null?void 0:t.name,template_id:t==null?void 0:t.templateId,joined_at:(a=t==null?void 0:t.joinedAt)==null?void 0:a.getTime(),session_started_at:(o=t==null?void 0:t.startedAt)==null?void 0:o.getTime(),role:(n=i==null?void 0:i.role)==null?void 0:n.name,user_name:i==null?void 0:i.name,user_data:i==null?void 0:i.metadata,peer_id:i==null?void 0:i.peerId},ve.sendEvent(e)}};var Ra=require("uuid");var ba={autoplayFailed:void 0,initialized:!1,autoplayCheckPromise:void 0},Ct=class{constructor(e,t,i){this.store=e;this.deviceManager=t;this.eventBus=i;this.autoPausedTracks=new Set;this.TAG="[AudioSinkManager]:";this.volume=100;this.state=S({},ba);this.handleAudioPaused=e=>c(this,null,function*(){var a;let i=(a=e.target.srcObject)==null?void 0:a.getAudioTracks()[0];if(!(i!=null&&i.enabled))return;d.d(this.TAG,"Audio Paused",e.target.id);let r=this.store.getTrackById(e.target.id);r&&(Yt()?(yield X(500),this.playAudioFor(r)):this.autoPausedTracks.add(r))});this.handleTrackUpdate=({track:e})=>{d.d(this.TAG,"Track updated",`${e}`)};this.handleTrackAdd=r=>c(this,[r],function*({track:e,peer:t,callListener:i=!0}){var o,n;let a=document.createElement("audio");a.style.display="none",a.id=e.trackId,a.addEventListener("pause",this.handleAudioPaused),a.onerror=()=>c(this,null,function*(){var u,p;d.e(this.TAG,"error on audio element",a.error);let l=h.TracksErrors.AudioPlaybackError(`Audio playback error for track - ${e.trackId} code - ${(u=a==null?void 0:a.error)==null?void 0:u.code}`);this.eventBus.analytics.publish(M.audioPlaybackError(l)),((p=a==null?void 0:a.error)==null?void 0:p.code)===MediaError.MEDIA_ERR_DECODE&&(this.removeAudioElement(a,e),yield X(500),yield this.handleTrackAdd({track:e,peer:t,callListener:!1}))}),e.setAudioElement(a),e.setVolume(this.volume),d.d(this.TAG,"Audio track added",`${e}`),this.init(),yield this.autoSelectAudioOutput(),(o=this.audioSink)==null||o.append(a),this.outputDevice&&(yield e.setOutputDevice(this.outputDevice)),a.srcObject=new MediaStream([e.nativeTrack]),i&&((n=this.listener)==null||n.onTrackUpdate(0,e,t)),yield this.handleAutoplayError(e)});this.handleAutoplayError=e=>c(this,null,function*(){if(this.state.autoplayFailed===void 0&&(this.state.autoplayCheckPromise||(this.state.autoplayCheckPromise=new Promise(t=>{this.playAudioFor(e).then(t)})),yield this.state.autoplayCheckPromise),this.state.autoplayFailed){this.autoPausedTracks.add(e);return}yield this.playAudioFor(e)});this.handleAudioDeviceChange=e=>{e.error||!e.selection||e.type==="video"||this.unpauseAudioTracks()};this.handleTrackRemove=e=>{this.autoPausedTracks.delete(e);let t=document.getElementById(e.trackId);t&&this.removeAudioElement(t,e),this.audioSink&&this.audioSink.childElementCount===0&&(this.state.autoplayCheckPromise=void 0,this.state.autoplayFailed=void 0),d.d(this.TAG,"Audio track removed",`${e}`)};this.unpauseAudioTracks=()=>c(this,null,function*(){let e=[];this.autoPausedTracks.forEach(t=>{e.push(this.playAudioFor(t))}),yield Promise.all(e)});this.removeAudioElement=(e,t)=>{e&&(d.d(this.TAG,"removing audio element",`${t}`),e.removeEventListener("pause",this.handleAudioPaused),e.srcObject=null,e.remove(),t.setAudioElement(null))};this.autoSelectAudioOutput=()=>c(this,null,function*(){var e,t,i;if(((e=this.audioSink)==null?void 0:e.children.length)===0){let r=(t=this.deviceManager.audioInput)==null?void 0:t.find(o=>o.label.includes("earpiece")),a=(i=this.store.getLocalPeer())==null?void 0:i.audioTrack;a&&r&&(yield a.setSettings({deviceId:r==null?void 0:r.deviceId}),yield a.setSettings({deviceId:"default"}))}});this.eventBus.audioTrackAdded.subscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.subscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.subscribe(this.handleTrackUpdate),this.eventBus.deviceChange.subscribe(this.handleAudioDeviceChange)}setListener(e){this.listener=e}get outputDevice(){return this.deviceManager.outputDevice}getVolume(){return this.volume}setVolume(e){return c(this,null,function*(){yield this.store.updateAudioOutputVolume(e),this.volume=e})}unblockAutoplay(){return c(this,null,function*(){this.autoPausedTracks.size>0&&this.unpauseAudioTracks()})}init(e){if(this.state.initialized||this.audioSink)return;this.state.initialized=!0;let t=document.createElement("div");t.id=`HMS-SDK-audio-sink-${(0,Ra.v4)()}`,(e&&document.getElementById(e)||document.body).append(t),this.audioSink=t,d.d(this.TAG,"audio sink created",this.audioSink)}cleanup(){var e;(e=this.audioSink)==null||e.remove(),this.audioSink=void 0,this.eventBus.audioTrackAdded.unsubscribe(this.handleTrackAdd),this.eventBus.audioTrackRemoved.unsubscribe(this.handleTrackRemove),this.eventBus.audioTrackUpdate.unsubscribe(this.handleTrackUpdate),this.eventBus.deviceChange.unsubscribe(this.handleAudioDeviceChange),this.autoPausedTracks=new Set,this.state=S({},ba)}playAudioFor(e){return c(this,null,function*(){let t=e.getAudioElement();if(!t){d.w(this.TAG,"No audio element found on track",e.trackId);return}try{yield t.play(),this.state.autoplayFailed=!1,this.autoPausedTracks.delete(e),d.d(this.TAG,"Played track",`${e}`)}catch(i){this.autoPausedTracks.add(e),d.w(this.TAG,"Failed to play track",`${e}`,i);let r=i;if(!this.state.autoplayFailed&&r.name==="NotAllowedError"){this.state.autoplayFailed=!0;let a=h.TracksErrors.AutoplayBlocked("AUTOPLAY","");a.addNativeError(r),this.eventBus.analytics.publish(M.autoplayError()),this.eventBus.autoplayError.publish(a)}}})}};var Lt=class{constructor(e,t){this.store=e;this.eventBus=t;this.audioInput=[];this.audioOutput=[];this.videoInput=[];this.hasWebcamPermission=!1;this.hasMicrophonePermission=!1;this.TAG="[Device Manager]:";this.initialized=!1;this.videoInputChanged=!1;this.audioInputChanged=!1;this.updateOutputDevice=e=>c(this,null,function*(){let t=this.audioOutput.find(i=>i.deviceId===e);return t&&(this.outputDevice=t,yield this.store.updateAudioOutputDevice(t),Q.updateSelection("audioOutput",{deviceId:t.deviceId,groupId:t.groupId})),t});this.getCurrentSelection=()=>{var o,n;let e=this.store.getLocalPeer(),t=this.createIdentifier((o=e==null?void 0:e.audioTrack)==null?void 0:o.getMediaTrackSettings()),i=this.createIdentifier((n=e==null?void 0:e.videoTrack)==null?void 0:n.getMediaTrackSettings()),r=this.audioInput.find(l=>this.createIdentifier(l)===t),a=this.videoInput.find(l=>this.createIdentifier(l)===i);return{audioInput:r,videoInput:a,audioOutput:this.outputDevice}};this.computeChange=(e,t)=>e.length!==t.length?!0:t.some(i=>!e.includes(this.createIdentifier(i)));this.enumerateDevices=()=>c(this,null,function*(){try{let e=yield navigator.mediaDevices.enumerateDevices(),t=this.videoInput.map(this.createIdentifier),i=this.audioInput.map(this.createIdentifier);this.audioInput=[],this.audioOutput=[],this.videoInput=[],e.forEach(r=>{r.kind==="audioinput"&&r.label?(this.hasMicrophonePermission=!0,this.audioInput.push(r)):r.kind==="audiooutput"?this.audioOutput.push(r):r.kind==="videoinput"&&r.label&&(this.hasWebcamPermission=!0,this.videoInput.push(r))}),this.videoInputChanged=this.computeChange(t,this.videoInput),this.audioInputChanged=this.computeChange(i,this.audioInput),Q.setDevices({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput]}),this.logDevices("Enumerate Devices")}catch(e){d.e(this.TAG,"Failed enumerating devices",e)}});this.handleDeviceChange=ii(()=>c(this,null,function*(){yield this.enumerateDevices(),this.logDevices("After Device Change");let e=this.store.getLocalPeer(),t=e==null?void 0:e.audioTrack;yield this.setOutputDevice(!0),t&&(yield this.handleAudioInputDeviceChange(e==null?void 0:e.audioTrack)),yield this.handleVideoInputDeviceChange(e==null?void 0:e.videoTrack),this.eventBus.analytics.publish(M.deviceChange({selection:this.getCurrentSelection(),type:"change",devices:this.getDevices()}))}),500).bind(this);this.handleAudioInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No Audio track on local peer");return}if(!this.audioInputChanged){d.d(this.TAG,"No Change in AudioInput Device");return}let t=this.getNewAudioInputDevice();if(!t||!t.deviceId){this.eventBus.analytics.publish(M.deviceChange({selection:{audioInput:t},error:h.TracksErrors.SelectedDeviceMissing("audio"),devices:this.getDevices(),type:"audioInput"})),d.e(this.TAG,"Audio device not found");return}let{settings:i}=e,r=new ae().codec(i.codec).maxBitrate(i.maxBitrate).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"audioInput"}),this.logDevices("Audio Device Change Success")}catch(a){d.e(this.TAG,"[Audio Device Change]",a),this.eventBus.analytics.publish(M.deviceChange({selection:{audioInput:t},devices:this.getDevices(),type:"audioInput",error:a})),this.eventBus.deviceChange.publish({error:a,selection:t,type:"audioInput",devices:this.getDevices()})}});this.handleVideoInputDeviceChange=e=>c(this,null,function*(){if(!e){d.d(this.TAG,"No video track on local peer");return}if(!this.videoInputChanged){d.d(this.TAG,"No Change in VideoInput Device");return}let t=this.videoInput[0];if(!t||!t.deviceId){this.eventBus.analytics.publish(M.deviceChange({selection:{videoInput:t},error:h.TracksErrors.SelectedDeviceMissing("video"),devices:this.getDevices(),type:"video"})),d.e(this.TAG,"Video device not found");return}let{settings:i}=e,r=new ee().codec(i.codec).maxBitrate(i.maxBitrate).maxFramerate(i.maxFramerate).setWidth(i.width).setHeight(i.height).deviceId(t.deviceId).build();try{yield e.setSettings(r,!0),this.eventBus.deviceChange.publish({devices:this.getDevices(),selection:t,type:"video"}),this.logDevices("Video Device Change Success")}catch(a){d.e(this.TAG,"[Video Device Change]",a),this.eventBus.analytics.publish(M.deviceChange({selection:{videoInput:t},devices:this.getDevices(),type:"video",error:a})),this.eventBus.deviceChange.publish({error:a,type:"video",selection:t,devices:this.getDevices()})}});let i=({enabled:r,track:a})=>r&&a.source==="regular";this.eventBus.localVideoEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.videoInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})})),this.eventBus.localAudioEnabled.waitFor(i).then(()=>c(this,null,function*(){yield this.enumerateDevices(),this.audioInputChanged&&this.eventBus.deviceChange.publish({devices:this.getDevices()})}))}init(e=!1){return c(this,null,function*(){this.initialized&&!e||(!this.initialized&&navigator.mediaDevices.addEventListener("devicechange",this.handleDeviceChange),this.initialized=!0,yield this.enumerateDevices(),this.logDevices("Init"),yield this.setOutputDevice(),this.eventBus.deviceChange.publish({devices:this.getDevices()}),this.eventBus.analytics.publish(M.deviceChange({selection:this.getCurrentSelection(),type:"list",devices:this.getDevices()})))})}getDevices(){return{audioInput:this.audioInput,audioOutput:this.audioOutput,videoInput:this.videoInput}}cleanup(){this.initialized=!1,this.audioInput=[],this.audioOutput=[],this.videoInput=[],this.outputDevice=void 0,navigator.mediaDevices.removeEventListener("devicechange",this.handleDeviceChange)}createIdentifier(e){return e?`${e.deviceId}${e.groupId}`:""}getNewAudioInputDevice(){let e=this.store.getLocalPeer(),t=e==null?void 0:e.audioTrack,i=this.audioInput.find(a=>a.deviceId===(t==null?void 0:t.getManuallySelectedDeviceId()));if(i)return i;t==null||t.resetManuallySelectedDeviceId();let r=this.audioInput.find(a=>a.deviceId==="default");return r?this.audioInput.find(o=>o.deviceId!=="default"&&r.label.includes(o.label)):this.audioInput[0]}setOutputDevice(e=!1){return c(this,null,function*(){let t=this.getNewAudioInputDevice(),i=this.createIdentifier(this.outputDevice);this.outputDevice=this.getAudioOutputDeviceMatchingInput(t),this.outputDevice||(this.outputDevice=this.audioOutput.find(r=>this.createIdentifier(r)===i),this.outputDevice||(this.outputDevice=this.audioOutput.find(r=>r.deviceId==="default")||this.audioOutput[0])),yield this.store.updateAudioOutputDevice(this.outputDevice),e&&i!==this.createIdentifier(this.outputDevice)&&(this.eventBus.analytics.publish(M.deviceChange({selection:{audioOutput:this.outputDevice},devices:this.getDevices(),type:"audioOutput"})),this.eventBus.deviceChange.publish({selection:this.outputDevice,type:"audioOutput",devices:this.getDevices()}))})}getAudioOutputDeviceMatchingInput(e){var o,n;let t=((n=(o=this.store.getConfig())==null?void 0:o.settings)==null?void 0:n.speakerAutoSelectionBlacklist)||[];if(t==="all"||!e)return;let i=e.label.toLowerCase()||"";if(t.some(l=>i.includes(l.toLowerCase())))return;let r=this.audioOutput.find(l=>e.deviceId!=="default"&&l.label===e.label);if(r)return r;let a=this.audioOutput.find(l=>l.groupId===e.groupId);if(a&&this.audioOutput[0].deviceId==="default"&&a.groupId===this.audioOutput[0].groupId)return a}logDevices(e=""){d.d(this.TAG,e,JSON.stringify({videoInput:[...this.videoInput],audioInput:[...this.audioInput],audioOutput:[...this.audioOutput],selected:this.getCurrentSelection()},null,4))}};var Ii=class{constructor(e,t){this.deviceManager=e;this.audioSinkManager=t}getVolume(){return this.audioSinkManager.getVolume()}setVolume(e){if(e<0||e>100)throw Error("Please pass a valid number between 0-100");this.audioSinkManager.setVolume(e)}getDevice(){return this.deviceManager.outputDevice}setDevice(e){return this.deviceManager.updateOutputDevice(e)}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield Pe.resumeContext()})}};var Ha=require("eventemitter2");var O=class{constructor(e,t){this.eventName=e;this.eventEmitter=t;this.publish=e=>{this.eventEmitter.emit(this.eventName,e)};this.subscribe=e=>{this.eventEmitter.on(this.eventName,e)};this.subscribeOnce=e=>{this.eventEmitter.once(this.eventName,e)};this.unsubscribe=e=>{this.eventEmitter.off(this.eventName,e)};this.waitFor=e=>this.eventEmitter.waitFor(this.eventName,{filter:e});this.removeAllListeners=()=>{this.eventEmitter.removeAllListeners(this.eventName)}}};var Ci=class{constructor(){this.eventEmitter=new Ha.EventEmitter2;this.deviceChange=new O(V.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new O(V.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new O(V.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.statsUpdate=new O(V.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new O(V.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new O(V.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new O(V.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new O(V.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new O(V.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.analytics=new O(V.ANALYTICS,this.eventEmitter);this.policyChange=new O(V.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new O(V.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new O(V.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new O(V.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new O(V.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new O(V.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new O(V.LEAVE,this.eventEmitter)}};var Dt=class{constructor(e){this.type=e.type,this.source=e.source||"regular",this.description="",e instanceof ke?(this.mute=!e.enabled,this.track_id=e.publishedTrackId,this.stream_id=e.stream.id):(this.mute=e.mute,this.track_id=e.track_id,this.stream_id=e.stream_id)}};var Li=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var a,o,n;let t=e["speaker-list"],i=t.map(l=>({audioLevel:l.level,peer:this.store.getPeerById(l.peer_id),track:this.store.getTrackById(l.track_id)}));(a=this.audioListener)==null||a.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(o=this.listener)==null||o.onPeerUpdate(4,l)}else(n=this.listener)==null||n.onPeerUpdate(5,null)}};var Di=class{constructor(e){this.listener=e;this.TAG="[BroadcastManager]"}handleNotification(e,t){e==="on-broadcast"&&this.handleBroadcast(t)}handleBroadcast(e){var t,i;d.d(this.TAG,`Received Message from sender=${(t=e==null?void 0:e.peer)==null?void 0:t.peer_id}: ${e}`),(i=this.listener)==null||i.onMessageReceived(e)}};var wi=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(a=>{let o=this.store.getPeerById(a.peer_id);return o&&o.updateNetworkQuality(a.downlink_score),{peerID:a.peer_id,downlinkQuality:a.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var ze=class{constructor(e,t,i){this.store=e;this.eventBus=t;this.listener=i;this.TAG="[TrackManager]";this.tracksToProcess=new Map;this.handleTrackAdd=e=>{d.d(this.TAG,"ONTRACKADD",`${e}`),this.tracksToProcess.set(e.trackId,e),this.processPendingTracks()};this.handleTrackRemovedPermanently=e=>{d.d(this.TAG,"ONTRACKREMOVE",e),Object.keys(e.tracks).forEach(i=>{var n;let r=this.store.getTrackState(i);if(!r)return;let a=this.store.getTrackById(i);if(!a){d.d(this.TAG,"Track not found in store");return}a.type==="audio"&&this.eventBus.audioTrackRemoved.publish(a),this.store.removeTrack(a);let o=this.store.getPeerById(r.peerId);o&&(this.removePeerTracks(o,a),(n=this.listener)==null||n.onTrackUpdate(1,a,o))})};this.handleTrackLayerUpdate=e=>{for(let t in e.tracks){let i=e.tracks[t],r=this.store.getTrackById(t);!r||!this.store.getPeerByTrackId(t)||r instanceof _&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var a,o;let i=this.store.getPeerById(e.peer.peer_id),r=e.peer;if(!i&&!r){d.d(this.TAG,"Track Update ignored - Peer not added to store");return}i||(i=Re(r,this.store),this.store.addPeer(i));for(let n in e.tracks){let l=Object.assign({},(a=this.store.getTrackState(n))==null?void 0:a.trackInfo),u=e.tracks[n],p=this.store.getTrackById(n);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:S(S({},l),u)}),!p||this.tracksToProcess.has(n))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{p.setEnabled(!u.mute);let m=this.processTrackUpdate(p,l,u);m&&((o=this.listener)==null||o.onTrackUpdate(m,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var a;let i=this.store.getTrackState(t.trackId);if(!i){d.d(this.TAG,"TrackState not added to store",`peerId - ${t.peerId}`,`trackId -${t.trackId}`);return}let r=this.store.getPeerById(i.peerId);if(!r){d.d(this.TAG,"Peer not added to store, peerId",i.peerId);return}t.source=i.trackInfo.source,t.peerId=r.peerId,t.logIdentifier=r.name,t.setEnabled(!i.trackInfo.mute),this.addAudioTrack(r,t),this.addVideoTrack(r,t),t.type==="audio"?this.eventBus.audioTrackAdded.publish({track:t,peer:r}):(a=this.listener)==null||a.onTrackUpdate(0,t,r),this.tracksToProcess.delete(t.trackId)})}}handleTrackMetadataAdd(e){d.d(this.TAG,"TRACK_METADATA_ADD",JSON.stringify(e,null,2));for(let t in e.tracks){let i=e.tracks[t];this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:i})}this.processPendingTracks()}handleTrackRemove(e,t=!0){var a;d.d(this.TAG,"ONTRACKREMOVE",`${e}`);let i=this.store.getTrackState(e.trackId);if(!i)return;if(!this.store.hasTrack(e)){d.d(this.TAG,"Track not found in store");return}if(t){this.store.removeTrack(e);let o=this.store.getPeerById(i.peerId);if(!o)return;this.removePeerTracks(o,e),(a=this.listener)==null||a.onTrackUpdate(1,e,o),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var a,o;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(a=this.listener)==null||a.onTrackUpdate(5,e,i):(o=this.listener)==null||o.onTrackUpdate(6,e,i)}removePeerTracks(e,t){let i=e.auxiliaryTracks.indexOf(t);i>-1?(e.auxiliaryTracks.splice(i,1),d.d(this.TAG,"auxiliary track removed",`${t}`)):t.type==="audio"&&e.audioTrack===t?(e.audioTrack=void 0,d.d(this.TAG,"audio track removed",`${t}`)):t.type==="video"&&e.videoTrack===t&&(e.videoTrack=void 0,d.d(this.TAG,"video track removed",`${t}`))}addAudioTrack(e,t){var i;t.type==="audio"&&(t.source==="regular"&&(!e.audioTrack||((i=e.audioTrack)==null?void 0:i.trackId)===t.trackId)?e.audioTrack=t:e.auxiliaryTracks.push(t),this.store.addTrack(t),d.d(this.TAG,"audio track added",`${t}`))}addVideoTrack(e,t){if(t.type!=="video")return;let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);if(i.setSimulcastDefinitons(r),this.addAsPrimaryVideoTrack(e,i))e.videoTrack?e.videoTrack.replaceTrack(i):e.videoTrack=i,this.store.addTrack(e.videoTrack);else{let a=e.auxiliaryTracks.findIndex(o=>o.trackId===i.trackId);a===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[a].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[a]))}d.d(this.TAG,"video track added",`${t}`)}addAsPrimaryVideoTrack(e,t){var i;return t.source==="regular"&&(!e.videoTrack||((i=e.videoTrack)==null?void 0:i.trackId)===t.trackId)}processTrackUpdate(e,t,i){let r;return t.mute!==i.mute?(r=i.mute?2:3,e.type==="audio"&&this.eventBus.audioTrackUpdate.publish({track:e,enabled:!i.mute})):t.description!==i.description&&(r=4),r}};var _i=class extends ze{constructor(t,i,r,a){super(t,i,a);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u;if(t.type!=="video")return;let a=this.store.getPeerById(i);if(!a||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let o=new me(new MediaStream,this.transport.getSubscribeConnection()),n=Te.getEmptyVideoTrack();n.enabled=!t.mute;let l=new _(o,n,t.source);l.setTrackId(t.track_id),l.peerId=a.peerId,l.logIdentifier=a.name,this.addVideoTrack(a,l),r&&((u=this.listener)==null||u.onTrackUpdate(0,a.videoTrack,a))}}handleTrackMetadataAdd(t){super.handleTrackMetadataAdd(t);for(let i in t.tracks)t.tracks[i].type==="video"&&this.processTrackInfo(t.tracks[i],t.peer.peer_id)}handleTrackRemove(t){let i=t.type==="video"&&t.source==="regular";super.handleTrackRemove(t,!i),i&&this.processTrackInfo({track_id:t.trackId,mute:!t.enabled,type:t.type,source:t.source,stream_id:t.stream.id},t.peerId,!1)}addAsPrimaryVideoTrack(t,i){return i.source!=="regular"?!1:!t.videoTrack||t.videoTrack.trackId===i.trackId?!0:t.videoTrack.enabled&&le(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var a,o,n,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(o=(a=i==null?void 0:i.role)==null?void 0:a.subscribeParams)==null?void 0:o.subscribeToRoles)==null?void 0:l.includes((n=r.role)==null?void 0:n.name))}};var Ni=class{constructor(e,t,i,r){this.store=e;this.peerManager=t;this.trackManager=i;this.listener=r;this.TAG="[PeerListManager]";this.handleInitialPeerList=e=>{let t=Object.values(e.peers);this.peerManager.handlePeerList(t)};this.handleReconnectPeerList=e=>{this.handleRepeatedPeerList(e.peers)};this.handlePreviewRoomState=e=>{if(!this.store.hasRoleDetailsArrived())return;let t=e.peers;if(t==null){e.peer_count===0&&this.handleRepeatedPeerList({});return}Object.keys(t).forEach(i=>{t[i].tracks={},t[i].is_from_room_state=!0}),this.handleRepeatedPeerList(t)};this.handleRepeatedPeerList=e=>{let t=this.store.getRemotePeers(),i=Object.values(e),r=t.filter(o=>!e[o.peerId]);r.length>0&&d.d(this.TAG,`${r}`),r.forEach(o=>{var l;let n={peer_id:o.peerId,role:((l=o.role)==null?void 0:l.name)||"",info:{name:o.name,data:o.metadata||"",user_id:o.customerUserId||""},tracks:{},groups:[],realtime:o.realtime};this.peerManager.handlePeerLeave(n)});let a=[];i.forEach(o=>{let n=this.store.getPeerById(o.peer_id),l=Object.values(o.tracks);n&&(this.store.getPeerTracks(n.peerId).forEach(p=>{var m;o.tracks[p.trackId]||(this.removePeerTrack(n,p.trackId),(m=this.listener)==null||m.onTrackUpdate(1,p,n))}),l.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:n.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:o,tracks:o.tracks},!1),this.peerManager.handlePeerUpdate(o)),a.push(o)}),a.length>0&&this.peerManager.handlePeerList(a)}}handleNotification(e,t,i){if(e==="peer-list"){let r=t;i?(d.d(this.TAG,"RECONNECT_PEER_LIST event",JSON.stringify(r,null,2)),this.handleReconnectPeerList(r)):(d.d(this.TAG,"PEER_LIST event",JSON.stringify(r,null,2)),this.handleInitialPeerList(r))}else if(e==="room-state"){let r=t;this.handlePreviewRoomState(r)}}removePeerTrack(e,t){var i,r;if(d.d(this.TAG,`removing track - ${t} from ${e}`),((i=e.audioTrack)==null?void 0:i.trackId)===t)e.audioTrack=void 0;else if(((r=e.videoTrack)==null?void 0:r.trackId)===t)e.videoTrack=void 0;else{let a=e.auxiliaryTracks.findIndex(o=>o.trackId===t);a>=0&&e.auxiliaryTracks.splice(a,1)}}};var L=s=>s?new Date(s):void 0;var Oi=class{constructor(e,t,i){this.store=e;this.trackManager=t;this.listener=i;this.TAG="[PeerManager]";this.handlePeerList=e=>{var r,a;if(e.length===0){(r=this.listener)==null||r.onPeerUpdate(9,[]);return}let t=[],i=new Set(e.map(o=>o.peer_id));this.store.getRemotePeers().forEach(({peerId:o,fromRoomState:n})=>{!i.has(o)&&n&&this.store.removePeer(o)});for(let o of e)t.push(this.makePeer(o));(a=this.listener)==null||a.onPeerUpdate(9,t),this.trackManager.processPendingTracks()};this.handlePeerJoin=e=>{var i;let t=this.makePeer(e);(i=this.listener)==null||i.onPeerUpdate(0,t),this.trackManager.processPendingTracks()};this.handlePeerLeave=e=>{var i,r,a,o;let t=this.store.getPeerById(e.peer_id);this.store.removePeer(e.peer_id),d.d(this.TAG,"PEER_LEAVE",e.peer_id,`remainingPeers=${this.store.getPeers().length}`),t&&(t.audioTrack&&((i=this.listener)==null||i.onTrackUpdate(1,t.audioTrack,t)),t.videoTrack&&((r=this.listener)==null||r.onTrackUpdate(1,t.videoTrack,t)),(a=t.auxiliaryTracks)==null||a.forEach(n=>{var l;(l=this.listener)==null||l.onTrackUpdate(1,n,t)}),(o=this.listener)==null||o.onPeerUpdate(1,t))}}handleNotification(e,t){switch(e){case"on-peer-join":{let i=t;this.handlePeerJoin(i);break}case"on-peer-leave":{let i=t;this.handlePeerLeave(i);break}case"on-peer-update":this.handlePeerUpdate(t);break;default:break}}handlePeerUpdate(e){var a,o,n,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(a=this.listener)==null||a.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(o=this.listener)==null||o.onPeerUpdate(13,t);return}if(!t){d.d(this.TAG,`peer ${e.peer_id} not found`);return}if(t.role&&t.role.name!==e.role){let p=this.store.getPolicyForRole(e.role);t.updateRole(p),this.updateSimulcastLayersForPeer(t),(n=this.listener)==null||n.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(fe);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(S({peer:t},e.info))}handlePeerInfoUpdate({peer:e,name:t,data:i}){var r,a;e&&(t&&e.name!==t&&(e.updateName(t),(r=this.listener)==null||r.onPeerUpdate(10,e)),i&&e.metadata!==i&&(e.updateMetadata(i),(a=this.listener)==null||a.onPeerUpdate(11,e)))}makePeer(e){let t=this.store.getPeerById(e.peer_id);t||(t=Re(e,this.store),t.realtime=e.realtime,t.joinedAt=L(e.joined_at),t.fromRoomState=!!e.is_from_room_state,this.store.addPeer(t),d.d(this.TAG,"adding to the peerList",`${t}`));for(let i in e.tracks){let r=e.tracks[i];this.store.setTrackState({peerId:e.peer_id,trackInfo:r}),r.type==="video"&&this.trackManager.processTrackInfo(r,e.peer_id,!1)}return t}updateSimulcastLayersForPeer(e){this.store.getPeerTracks(e.peerId).forEach(t=>{if(t.type==="video"&&["regular","screen"].includes(t.source)){let i=t,r=this.store.getSimulcastDefinitionsForPeer(e,i.source);i.setSimulcastDefinitons(r)}})}};var xi=class{constructor(e,t){this.store=e;this.eventBus=t}handlePolicyChange(e){let t=this.store.getLocalPeer();if(t&&!t.role){let r=e.known_roles[e.name];t.updateRole(r)}this.store.setKnownRoles(e);let i=this.store.getRoom();i?i.templateId=e.template_id:d.w("[PolicyChangeManager]","on policy change - room not present"),this.updateLocalPeerRole(e),this.eventBus.policyChange.publish(e)}updateLocalPeerRole(e){var i;let t=this.store.getLocalPeer();if(t!=null&&t.role&&t.role.name!==e.name){let r=this.store.getPolicyForRole(e.name),a=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:a,newRole:r})}}};var Ui=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.TAG="[HMSWhiteboardInteractivityCenter]"}get isEnabled(){return this.transport.isFlagEnabled("whiteboardEnabled")}open(e){return c(this,null,function*(){var o;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e==null?void 0:e.id),i=t==null?void 0:t.id;if(t||(i=(yield this.transport.signal.createWhiteboard(this.getCreateOptionsWithDefaults(e))).id),!i)throw new Error(`Whiteboard ID: ${i} not found`);let r=yield this.transport.signal.getWhiteboard({id:i}),a=y(S({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,token:r.token,addr:r.addr,owner:r.owner,permissions:r.permissions||[],open:!0});this.store.setWhiteboard(a),(o=this.listener)==null||o.onWhiteboardUpdate(a)})}close(e){return c(this,null,function*(){var r;if(!this.isEnabled)return d.w(this.TAG,"Whiteboard is not enabled for customer");let t=this.store.getWhiteboard(e);if(!t)throw new Error(`Whiteboard ID: ${e} not found`);let i={id:t.id,title:t.title,open:!1};this.store.setWhiteboard(i),(r=this.listener)==null||r.onWhiteboardUpdate(i)})}setListener(e){this.listener=e}getCreateOptionsWithDefaults(e){var o;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],a=[];return t.forEach(n=>{var l,u,p;(l=n.permissions.whiteboard)!=null&&l.includes("read")&&i.push(n.name),(u=n.permissions.whiteboard)!=null&&u.includes("write")&&r.push(n.name),(p=n.permissions.whiteboard)!=null&&p.includes("admin")&&a.push(n.name)}),{title:(e==null?void 0:e.title)||`${(o=this.store.getRoom())==null?void 0:o.id} Whiteboard`,reader:(e==null?void 0:e.reader)||i,writer:(e==null?void 0:e.writer)||r,admin:(e==null?void 0:e.admin)||a}}};var wt=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Ui(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var o,n;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(y(S({},e),{mode:e.mode?t[e.mode]:void 0,poll_id:e.id,vote:e.rolesThatCanVote,responses:e.rolesThatCanViewResponses}));e.id||(e.id=i),Array.isArray(e.questions)&&(yield this.addQuestionsToPoll(e.id,e.questions));let r=yield this.transport.signal.getPollQuestions({poll_id:e.id,index:0,count:50}),a=Vi(y(S({},e),{poll_id:e.id,state:"created",created_by:(o=this.store.getLocalPeer())==null?void 0:o.peerId}));a.questions=r.questions.map(({question:l,options:u,answer:p})=>y(S({},l),{options:u,answer:p})),(n=this.listener)==null||n.onPollsUpdate(0,[a])})}startPoll(e){return c(this,null,function*(){typeof e=="string"?yield this.transport.signal.startPoll({poll_id:e}):(yield this.createPoll(e),yield this.transport.signal.startPoll({poll_id:e.id}))})}addQuestionsToPoll(e,t){return c(this,null,function*(){t.length>0&&(yield this.transport.signal.setPollQuestions({poll_id:e,questions:t.map((i,r)=>this.createQuestionSetParams(i,r))}))})}stopPoll(e){return c(this,null,function*(){yield this.transport.signal.stopPoll({poll_id:e})})}addResponsesToPoll(e,t){return c(this,null,function*(){let i=this.store.getPoll(e);if(!i)throw new Error("Invalid poll ID - Poll not found");let r=t.map(a=>{var n,l;let o=this.getQuestionInPoll(i,a.questionIndex);return o.type==="single-choice"?(a.option=a.option||((n=a.options)==null?void 0:n[0])||-1,delete a.text,delete a.options):o.type==="multiple-choice"?((l=a.options)==null||l.sort(),delete a.text,delete a.option):(delete a.option,delete a.options),a.skipped&&(delete a.option,delete a.options,delete a.text),S({duration:0,type:o.type,question:a.questionIndex},a)});yield this.transport.signal.setPollResponses({poll_id:e,responses:r})})}fetchLeaderboard(e,t,i){return c(this,null,function*(){var u,p;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let a=((p=(u=this.store.getLocalPeer())==null?void 0:u.role)==null?void 0:p.permissions.pollRead)||!1;if(r.anonymous||r.state!=="stopped"||!a)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),n={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctAnswers:o.correct_users};return{entries:o.questions.map(m=>({position:m.position,totalResponses:m.total_responses,correctResponses:m.correct_responses,duration:m.duration,peer:m.peer,score:m.score})),hasNext:!o.last,summary:n}})}getPolls(){return c(this,null,function*(){let e=yield this.transport.signal.getPollsList({count:50}),t=[];for(let i of e.polls){let r=yield this.transport.signal.getPollQuestions({poll_id:i.poll_id,index:0,count:50}),a=Vi(i);a.questions=r.questions.map(({question:o,options:n,answer:l})=>y(S({},o),{options:n,answer:l})),t.push(a),this.store.setPoll(a)}return t})}createQuestionSetParams(e,t){var o;let i=y(S({},e),{index:t+1}),r,a=e.answer||{hidden:!1};return Array.isArray(e.options)&&["single-choice","multiple-choice"].includes(e.type)?(r=(o=e.options)==null?void 0:o.map((n,l)=>({index:l+1,text:n.text,weight:n.weight})),a==null||delete a.text,e.type==="single-choice"?a.option=e.options.findIndex(n=>n.isCorrectAnswer)+1||void 0:a.options=e.options.map((n,l)=>n.isCorrectAnswer?l+1:void 0).filter(n=>!!n)):(a==null||delete a.options,a==null||delete a.option),{question:i,options:r,answer:a}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(a=>a.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},Vi=s=>{let e={userid:"customerID",peerid:"peerID",username:"userName"};return{id:s.poll_id,title:s.title,startedBy:s.started_by,createdBy:s.created_by,anonymous:s.anonymous,type:s.type,duration:s.duration,locked:s.locked,mode:s.mode?e[s.mode]:void 0,visibility:s.visibility,rolesThatCanVote:s.vote||[],rolesThatCanViewResponses:s.responses||[],state:s.state,stoppedBy:s.stopped_by,startedAt:L(s.started_at),stoppedAt:L(s.stopped_at),createdAt:L(s.created_at)}};var Bi=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-poll-start":{this.handlePollStart(t);break}case"on-poll-stop":{this.handlePollStop(t);break}case"on-poll-stats":this.handlePollStats(t);break;default:break}}handlePollStart(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){if(this.store.getPoll(r.poll_id))return;let a=yield this.transport.signal.getPollQuestions({poll_id:r.poll_id,index:0,count:50}),o=Vi(r);o.questions=a.questions.map(({question:n,options:l,answer:u})=>y(S({},n),{options:l,answer:u})),yield this.updatePollResponses(o,!0),t.push(o),this.store.setPoll(o)}(i=this.listener)==null||i.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let a=this.store.getPoll(r.poll_id);if(a){a.state="stopped",a.stoppedAt=L(r.stopped_at),a.stoppedBy=r.stopped_by;let o=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(a,o),t.push(a)}}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(2,t))})}handlePollStats(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let a=this.store.getPoll(r.poll_id);if(!a)return;this.updatePollResult(a,r),yield this.updatePollResponses(a,!1),t.push(a)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(3,t))})}updatePollResult(e,t){var i;e.result=S({},e.result),e.result.totalUsers=t.user_count,e.result.maxUsers=t.max_user,e.result.totalResponses=t.total_response,(i=t.questions)==null||i.forEach(r=>{var o,n;let a=(o=e.questions)==null?void 0:o.find(l=>l.index===r.question);a&&(a.result=S({},a.result),a.result.correctResponses=r.correct,a.result.skippedCount=r.skipped,a.result.totalResponses=r.total,(n=r.options)==null||n.forEach((l,u)=>{var m;let p=(m=a.options)==null?void 0:m[u];p&&p.voteCount!==l&&(p.voteCount=l)}))})}updatePollResponses(e,t){return c(this,null,function*(){var r;(r=(yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t})).responses)==null||r.forEach(({response:a,peer:o,final:n})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(m=>m.index===a.question);if(!l)return;let u={id:a.response_id,questionIndex:a.question,option:a.option,options:a.options,text:a.text,responseFinal:n,peer:{peerid:o.peerid,userHash:o.hash,userid:o.userid,username:o.username},skipped:a.skipped,type:a.type,update:a.update};Array.isArray(l.responses)&&l.responses.length>0?l.responses.find(({id:m})=>m===u.id)||l.responses.push(u):l.responses=[u]})})}};var Fi=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){switch(e){case"on-role-change-request":this.handleRoleChangeRequest(t);break;case"on-track-update-request":this.handleTrackUpdateRequest(t);break;case"on-change-track-mute-state-request":this.handleChangeTrackStateRequest(t);break;default:return}}handleRoleChangeRequest(e){var i;let t={requestedBy:e.requested_by?this.store.getPeerById(e.requested_by):void 0,role:this.store.getPolicyForRole(e.role),token:e.token};(i=this.listener)==null||i.onRoleChangeRequest(t)}handleTrackUpdateRequest(e){let{requested_by:t,track_id:i,mute:r}=e,a=t?this.store.getPeerById(t):void 0,o=this.store.getLocalPeerTracks().find(l=>l.publishedTrackId===i);if(!o)return;let n=()=>{var l;(l=this.listener)==null||l.onChangeTrackStateRequest({requestedBy:a,track:o,enabled:!r})};if(r){if(o.enabled===!r)return;o.setEnabled(!r).then(n)}else n()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:a}=e,o=a?this.store.getPeerById(a):void 0,n=!r,l=this.getTracksToBeUpdated({type:t,source:i,enabled:n});if(l.length!==0)if(n)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let m of l)p.push(m.setEnabled(!1));Promise.all(p).then(()=>{var m;(m=this.listener)==null||m.onChangeMultiTrackStateRequest({requestedBy:o,tracks:l,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let a=this.store.getLocalPeerTracks();return e&&(a=a.filter(o=>o.type===e)),t&&(a=a.filter(o=>o.source===t)),a.filter(o=>o.enabled!==i)}};var Gi=class{constructor(e,t){this.store=e;this.listener=t;this.TAG="[RoomUpdateManager]"}handleNotification(e,t){switch(e){case"peer-list":this.onRoomState(t.room);break;case"on-rtmp-update":this.updateRTMPStatus(t);break;case"on-record-update":this.updateRecordingStatus(t);break;case"room-state":this.handlePreviewRoomState(t);break;case"room-info":this.handleRoomInfo(t);break;case"session-info":this.handleSessionInfo(t);break;case"on-hls-update":this.updateHLSStatus(t);break;default:break}}handleRoomInfo(e){let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.description=e.description,t.large_room_optimization=e.large_room_optimization,t.max_size=e.max_size,t.name=e.name}handleSessionInfo(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on session info - room not present");return}t.sessionId=e.session_id,t.peerCount!==e.peer_count&&(t.peerCount=e.peer_count,(i=this.listener)==null||i.onRoomUpdate("ROOM_PEER_COUNT_UPDATED",t))}handlePreviewRoomState(e){let{room:t}=e;this.onRoomState(t)}onRoomState(e){var l,u,p,m;let{recording:t,streaming:i,session_id:r,started_at:a,name:o}=e,n=this.store.getRoom();if(!n){d.w(this.TAG,"on room state - room not present");return}n.name=o,n.rtmp.running=this.isStreamingRunning((l=i==null?void 0:i.rtmp)==null?void 0:l.state),n.rtmp.startedAt=L((u=i==null?void 0:i.rtmp)==null?void 0:u.started_at),n.rtmp.state=(p=i==null?void 0:i.rtmp)==null?void 0:p.state,n.recording.server=this.getPeerListSFURecording(t),n.recording.browser=this.getPeerListBrowserRecording(t),n.recording.hls=this.getPeerListHLSRecording(t),n.hls=this.convertHls(i==null?void 0:i.hls),n.sessionId=r,n.startedAt=L(a),(m=this.listener)==null||m.onRoomUpdate("RECORDING_STATE_UPDATED",n)}isRecordingRunning(e){return e?!["none","paused","stopped","failed"].includes(e):!1}isStreamingRunning(e){return e?!["none","stopped","failed"].includes(e):!1}initHLS(e){let t=this.store.getRoom(),i={running:!0,variants:[]};return t?(e!=null&&e.variants&&e.variants.forEach((r,a)=>{var o;i.variants.push({initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[a].initialised_at),url:""})}),i):(d.w(this.TAG,"on hls - room not present"),i)}updateHLSStatus(e){var r;let t=this.store.getRoom(),i=e.variants&&e.variants.length>0?this.isStreamingRunning(e.variants[0].state):!1;if(!t){d.w(this.TAG,"on hls - room not present");return}e.enabled=i,t.hls=this.convertHls(e),(r=this.listener)==null||r.onRoomUpdate("HLS_STREAMING_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants[0].state==="initialised":!1)return this.initHLS(e);let i={running:!!(e!=null&&e.enabled),variants:[],error:this.toSdkError(e==null?void 0:e.error)};return(r=e==null?void 0:e.variants)==null||r.forEach(a=>{i.variants.push({meetingURL:a==null?void 0:a.meeting_url,url:a==null?void 0:a.url,metadata:a==null?void 0:a.metadata,startedAt:L(a==null?void 0:a.started_at),initialisedAt:L(a==null?void 0:a.initialised_at),state:a.state})}),i}getHLSRecording(e){var r,a;let t={running:!1},i=this.isRecordingRunning(e==null?void 0:e.state);return(i||(e==null?void 0:e.state)==="paused")&&(t={running:i,singleFilePerLayer:!!((r=e==null?void 0:e.hls_recording)!=null&&r.single_file_per_layer),hlsVod:!!((a=e==null?void 0:e.hls_recording)!=null&&a.hls_vod),startedAt:L(e==null?void 0:e.started_at),initialisedAt:L(e==null?void 0:e.initialised_at),state:e==null?void 0:e.state,error:this.toSdkError(e==null?void 0:e.error)}),t}getPeerListHLSRecording(e){var r,a;let t=e==null?void 0:e.hls;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),initialisedAt:L(t==null?void 0:t.initialised_at),state:t==null?void 0:t.state,singleFilePerLayer:(r=t==null?void 0:t.config)==null?void 0:r.single_file_per_layer,hlsVod:(a=t==null?void 0:t.config)==null?void 0:a.hls_vod}}getPeerListBrowserRecording(e){let t=e==null?void 0:e.browser;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}getPeerListSFURecording(e){let t=e==null?void 0:e.sfu;return{running:this.isRecordingRunning(t==null?void 0:t.state),startedAt:L(t==null?void 0:t.started_at),state:t==null?void 0:t.state}}updateRecordingStatus(e){var a;let t=this.store.getRoom(),i=this.isRecordingRunning(e.state);if(!t){d.w(this.TAG,`set recording status running=${i} - room not present`);return}let r;e.type==="sfu"?(t.recording.server={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e.state},r="SERVER_RECORDING_STATE_UPDATED"):e.type==="HLS"?(t.recording.hls=this.getHLSRecording(e),r="RECORDING_STATE_UPDATED"):(t.recording.browser={running:i,startedAt:i?L(e.started_at):void 0,error:this.toSdkError(e.error),state:e==null?void 0:e.state},r="BROWSER_RECORDING_STATE_UPDATED"),(a=this.listener)==null||a.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,a;let t=this.store.getRoom(),i=this.isStreamingRunning(e.state);if(!t){d.w(this.TAG,"on policy change - room not present");return}if(!i){t.rtmp={running:i,state:e.state,error:this.toSdkError(e.error)},(r=this.listener)==null||r.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t);return}t.rtmp={running:i,startedAt:i?L(e.started_at):void 0,state:e.state,error:this.toSdkError(e.error)},(a=this.listener)==null||a.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new T(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var $i=class{constructor(e,t){this.store=e;this.listener=t}handleNotification(e,t){e==="on-metadata-change"&&this.handleMetadataChange(t)}handleMetadataChange(e){var i;let t=e.values.map(r=>({key:r.key,value:r.data,updatedAt:L(r.updated_at),updatedBy:r.updated_by?this.store.getPeerById(r.updated_by):void 0}));(i=this.listener)==null||i.onSessionStoreUpdate(t)}};var Wi=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){switch(e){case"on-whiteboard-update":{this.handleWhiteboardUpdate(t);break}default:break}}handleWhiteboardUpdate(e){return c(this,null,function*(){var n;let t=this.store.getLocalPeer(),i=this.store.getWhiteboard(e.id),r=e.owner===(t==null?void 0:t.peerId)||e.owner===(t==null?void 0:t.customerUserId),a=e.state==="open",o={id:e.id,title:e.title,attributes:e.attributes};if(o.open=r?i==null?void 0:i.open:a,o.owner=o.open?e.owner:void 0,!r&&o.open){let l=yield this.transport.signal.getWhiteboard({id:e.id});o.token=l.token,o.addr=l.addr,o.permissions=l.permissions}this.store.setWhiteboard(o),(n=this.listener)==null||n.onWhiteboardUpdate(o)})}};var Ki=class{constructor(e,t,i,r,a,o){this.store=e;this.transport=i;this.listener=r;this.audioListener=a;this.connectionQualityListener=o;this.TAG="[HMSNotificationManager]";this.hasConsistentRoomStateArrived=!1;this.ignoreNotification=e=>{if(e==="peer-list")this.hasConsistentRoomStateArrived=!0;else if(e==="room-state")return this.hasConsistentRoomStateArrived;return!1};this.handleTrackAdd=e=>{this.trackManager.handleTrackAdd(e)};this.handleTrackRemove=e=>{this.trackManager.handleTrackRemove(e)};this.updateLocalPeer=({name:e,metadata:t})=>{let i=this.store.getLocalPeer();this.peerManager.handlePeerInfoUpdate({peer:i,name:e,data:t})};let n=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=n?new _i(this.store,t,this.transport,this.listener):new ze(this.store,t,this.listener),this.peerManager=new Oi(this.store,this.trackManager,this.listener),this.peerListManager=new Ni(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new Di(this.listener),this.policyChangeManager=new xi(this.store,t),this.requestManager=new Fi(this.store,this.listener),this.activeSpeakerManager=new Li(this.store,this.listener,this.audioListener),this.connectionQualityManager=new wi(this.store,this.connectionQualityListener),this.roomUpdateManager=new Gi(this.store,this.listener),this.sessionMetadataManager=new $i(this.store,this.listener),this.pollsManager=new Bi(this.store,this.transport,this.listener),this.whiteboardManager=new Wi(this.store,this.transport,this.listener)}setListener(e){this.listener=e,this.trackManager.listener=e,this.peerManager.listener=e,this.peerListManager.listener=e,this.broadcastManager.listener=e,this.requestManager.listener=e,this.activeSpeakerManager.listener=e,this.roomUpdateManager.listener=e,this.sessionMetadataManager.listener=e,this.pollsManager.listener=e,this.whiteboardManager.listener=e}setAudioListener(e){this.audioListener=e,this.activeSpeakerManager.audioListener=e}setConnectionQualityListener(e){this.connectionQualityListener=e,this.connectionQualityManager.listener=e}handleNotification(e,t=!1){var a,o;let i=e.method,r=e.params;["active-speakers","sfu-stats","on-connection-quality-update",void 0].includes(i)||d.d(this.TAG,`Received notification - ${i}`,{notification:r}),i==="sfu-stats"&&(a=window.HMS)!=null&&a.ON_SFU_STATS&&typeof((o=window.HMS)==null?void 0:o.ON_SFU_STATS)=="function"&&window.HMS.ON_SFU_STATS(e.params),!this.ignoreNotification(i)&&(this.roomUpdateManager.handleNotification(i,r),this.peerManager.handleNotification(i,r),this.requestManager.handleNotification(i,r),this.peerListManager.handleNotification(i,r,t),this.broadcastManager.handleNotification(i,r),this.sessionMetadataManager.handleNotification(i,r),this.pollsManager.handleNotification(i,r),this.whiteboardManager.handleNotification(i,r),this.handleIsolatedMethods(i,r))}handleIsolatedMethods(e,t){switch(e){case"on-track-add":{this.trackManager.handleTrackMetadataAdd(t);break}case"on-track-update":{this.trackManager.handleTrackUpdate(t);break}case"on-track-remove":{if(!t.peer){d.d(this.TAG,`Ignoring sfu notification - ${e}`,{notification:t});return}this.trackManager.handleTrackRemovedPermanently(t);break}case"on-track-layer-update":{this.trackManager.handleTrackLayerUpdate(t);break}case"active-speakers":this.activeSpeakerManager.handleActiveSpeakers(t);break;case"on-connection-quality-update":this.connectionQualityManager.handleQualityUpdate(t);break;case"on-policy-change":this.policyChangeManager.handlePolicyChange(t);break;default:break}}};var qi=class{constructor(e){this.transport=e;this.observedKeys=new Set}get(e){return c(this,null,function*(){let{data:t,updated_at:i}=yield this.transport.signal.getSessionMetadata(e);return{value:t,updatedAt:L(i)}})}set(e,t){return c(this,null,function*(){let{data:i,updated_at:r}=yield this.transport.signal.setSessionMetadata({key:e,data:t}),a=L(r);return{value:i,updatedAt:a}})}observe(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(e.forEach(i=>this.observedKeys.add(i)),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}unobserve(e){return c(this,null,function*(){let t=new Set(this.observedKeys);if(this.observedKeys=new Set([...this.observedKeys].filter(i=>!e.includes(i))),this.observedKeys.size!==t.size)try{yield this.transport.signal.listenMetadataChange(Array.from(this.observedKeys))}catch(i){throw this.observedKeys=t,i}})}};var ji=class{constructor(e,t,i="",r="",a="https://prod-init.100ms.live/init",o=!1){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=a;this.autoSubscribeVideo=o}};var K=(a=>(a[a.ConnectFailed=0]="ConnectFailed",a[a.SignalDisconnect=1]="SignalDisconnect",a[a.JoinWSMessageFailed=2]="JoinWSMessageFailed",a[a.PublishIceConnectionFailed=3]="PublishIceConnectionFailed",a[a.SubscribeIceConnectionFailed=4]="SubscribeIceConnectionFailed",a))(K||{}),Ia={0:[],1:[],2:[1],3:[1],4:[1]};var Ji=(n=>(n.Disconnected="Disconnected",n.Connecting="Connecting",n.Joined="Joined",n.Preview="Preview",n.Failed="Failed",n.Reconnecting="Reconnecting",n.Leaving="Leaving",n))(Ji||{});var Qi=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var zi=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(n){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxFailedRetries:a=5,changeState:o=!0}){yield this.scheduleTask({category:e,error:t,changeState:o,task:i,originalState:r,maxFailedRetries:a})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(l){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:a,maxFailedRetries:o=5,failedRetryCount:n=0}){if(d.d(this.TAG,"schedule: ",{category:K[e],error:t}),n===0){let f=this.inProgress.get(e);if(f){d.d(this.TAG,`schedule: Already a task for ${K[e]} scheduled, waiting for its completion`),yield f.promise;return}let R=new Qi((b,G)=>{});this.inProgress.set(e,R),this.sendEvent(t,e)}let u=!1,p=Ia[e];for(let f in p){let R=p[parseInt(f)];try{let b=this.inProgress.get(R);b&&(d.d(this.TAG,`schedule: Suspending retry task of ${K[e]}, waiting for ${K[R]} to recover`),yield b.promise,d.d(this.TAG,`schedule: Resuming retry task ${K[e]} as it's dependency ${K[R]} is recovered`))}catch(b){d.d(this.TAG,`schedule: Stopping retry task of ${K[e]} as it's dependency ${K[R]} failed to recover`),u=!0;break}}if(n>=o||u){if(t.description+=`. [${K[e]}] Could not recover after ${n} tries`,u&&(t.description+=` Could not recover all of it's required dependencies - [${p.map(f=>K[f]).toString()}]`),t.isTerminal=!0,this.inProgress.delete(e),this.sendEvent(t,e),this.reset(),i)this.onStateChange("Failed",t);else throw t;return}i&&this.onStateChange("Reconnecting",t);let m=this.getDelayForRetryCount(e,n);d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Scheduling retry task in ${m}ms`);let g;try{g=yield this.setTimeoutPromise(r,m)}catch(f){g=!1,d.w(this.TAG,`[${K[e]}] Un-caught exception ${f.name} in retry-task, initiating retry`,f)}if(g){let f=this.inProgress.get(e);this.inProgress.delete(e),f==null||f.resolve(n),i&&this.inProgress.size===0&&this.onStateChange(a),d.d(this.TAG,`schedule: [${K[e]}] [failedRetryCount=${n}] Recovered \u267B\uFE0F`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:a,maxFailedRetries:o,failedRetryCount:n+1})})}getBaseDelayForTask(e,t){return e===2?2:Math.pow(2,t)}getDelayForRetryCount(e,t){let i=this.getBaseDelayForTask(e,t),r=e===2?Math.random()*2:Math.random();return Math.round(Math.min(i+r,60)*1e3)}setTimeoutPromise(e,t){return c(this,null,function*(){return new Promise((i,r)=>{let a=window.setTimeout(()=>c(this,null,function*(){try{let o=yield e();o&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(a),1),i(o)}catch(o){r(o)}}),t);this.retryTaskIds.push(a)})})}};var Yi=class extends Ae{constructor(){super(100);this.localStorage=new de("hms-analytics");this.localStorage.clear(),this.initLocalStorageQueue()}enqueue(t){super.enqueue(t),this.localStorage.set(this.storage)}dequeue(){let t=super.dequeue();return this.localStorage.set(this.storage),t}initLocalStorageQueue(){var t;(t=this.localStorage.get())==null||t.forEach(i=>{let r=new I(i);super.enqueue(r)})}};var Xi=class{constructor(){this.TAG="[AnalyticsTransport]"}sendEvent(e){try{this.sendSingleEvent(e),this.flushFailedEvents()}catch(t){d.w(this.TAG,"sendEvent failed",t)}}flushFailedEvents(e){var t;try{for(d.d(this.TAG,"Flushing failed events",this.failedEvents);this.failedEvents.size()>0;){let i=this.failedEvents.dequeue();i&&(((t=i.metadata)==null?void 0:t.peer.peer_id)===e||!i.metadata.peer.peer_id?this.sendSingleEvent(i):ve.sendEvent(i))}}catch(i){d.w(this.TAG,"flushFailedEvents failed",i)}}sendSingleEvent(e){try{this.transportProvider.sendEvent(e),d.d(this.TAG,"Sent event",e.name,e)}catch(t){throw d.w(this.TAG,`${this.transportProvider.TAG}.sendEvent failed, adding to local storage events`,{event:e,error:t}),this.failedEvents.enqueue(e),t}}};var Zi=class extends Xi{constructor(t){super();this.transportProvider=t;this.failedEvents=new Yi}};var Ye=class{constructor(e,t,i,r){this.store=e;this.eventBus=t;this.sampleWindowSize=i;this.pushInterval=r;this.shouldSendEvent=!1;this.sequenceNum=1;this.stop=()=>{this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1};this.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>d.e("[StatsAnanlytics]",e.message)))}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield X(this.pushInterval*1e3),this.sendEvent()})}},Xe=class{constructor({track:e,ssrc:t,rid:i,kind:r,sampleWindowSize:a}){this.samples=[];this.tempStats=[];this.track=e,this.ssrc=t,this.rid=i,this.kind=r,this.track_id=this.track.trackId,this.source=this.track.source,this.sampleWindowSize=a}push(e){this.tempStats.push(e),this.shouldCreateSample()&&(this.samples.push(this.createSample()),this.tempStats.length=0)}getLatestStat(){return this.tempStats[this.tempStats.length-1]}getFirstStat(){return this.tempStats[0]}calculateSum(e){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((i,r)=>i+(r[e]||0),0)}calculateAverage(e,t=!0){let i=this.calculateSum(e),r=i!==void 0?i/this.tempStats.length:void 0;return r?t?Math.round(r):r:void 0}calculateDifferenceForSample(e){let t=Number(this.tempStats[0][e])||0;return(Number(this.getLatestStat()[e])||0)-t}calculateInstancesOfHigh(e,t){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((r,a)=>r+((a[e]||0)>t?1:0),0)}},er=(s,e)=>s&&e&&(s.frameWidth!==e.frameWidth||s.frameHeight!==e.frameHeight),tr=(s,e)=>s&&e&&s.enabled!==e.enabled,_t=s=>Object.entries(s).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var Nt=class extends Ye{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,a;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.toAnalytics())}),{audio:t,video:i,joined_at:(a=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:a.getTime(),sequence_num:this.sequenceNum++,max_window_sec:30}}sendEvent(){this.eventBus.analytics.publish(M.publishStats(this.toAnalytics()))}handleStatsUpdate(t){let i=t.getLocalTrackStats();Object.keys(i).forEach(r=>{let a=i[r],o=this.store.getLocalPeerTracks().find(n=>n.getTrackIDBeingSent()===r);Object.keys(a).forEach(n=>{var p,m,g,f,R;let l=a[n],u=o&&this.getTrackIdentifier(o==null?void 0:o.trackId,l);if(u&&this.trackAnalytics.has(u))(g=this.trackAnalytics.get(u))==null||g.push(y(S({},l),{availableOutgoingBitrate:(m=(p=t.getLocalPeerStats())==null?void 0:p.publish)==null?void 0:m.availableOutgoingBitrate}));else if(o){let b=new as({track:o,sampleWindowSize:this.sampleWindowSize,rid:l.rid,ssrc:l.ssrc.toString(),kind:l.kind});b.push(y(S({},l),{availableOutgoingBitrate:(R=(f=t.getLocalPeerStats())==null?void 0:f.publish)==null?void 0:R.availableOutgoingBitrate})),this.trackAnalytics.set(this.getTrackIdentifier(o==null?void 0:o.trackId,l),b)}})})}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},as=class extends Xe{constructor(){super(...arguments);this.samples=[];this.createSample=()=>{let t=this.getLatestStat(),i=t.qualityLimitationDurations,r=i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other},a=t.frameHeight?{height_px:this.getLatestStat().frameHeight,width_px:this.getLatestStat().frameWidth}:void 0,o=this.calculateAverage("jitter",!1),n=o?Math.round(o*1e3):void 0,l=this.calculateAverage("roundTripTime",!1),u=l?Math.round(l*1e3):void 0;return _t({timestamp:Date.now(),avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:this.calculateDifferenceForSample("packetsLost"),total_packets_sent:this.calculateDifferenceForSample("packetsSent"),total_packet_sent_delay_sec:parseFloat(this.calculateDifferenceForSample("totalPacketSendDelay").toFixed(4)),total_fir_count:this.calculateDifferenceForSample("firCount"),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_ms:n,avg_round_trip_time_ms:u,total_quality_limitation:r,resolution:a})};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||tr(i,r)||i.kind==="video"&&er(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var Ot=class extends Ye{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,a;let t=[],i=[];return this.trackAnalytics.forEach(o=>{o.track.type==="audio"?t.push(o.toAnalytics()):o.track.type==="video"&&i.push(o.toAnalytics())}),{audio:t,video:i,joined_at:(a=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:a.getTime(),sequence_num:this.sequenceNum++,max_window_sec:10}}sendEvent(){this.eventBus.analytics.publish(M.subscribeStats(this.toAnalytics()))}handleStatsUpdate(t){let i=t.getAllRemoteTracksStats();Object.keys(i).forEach(r=>{var n;let a=i[r],o=this.store.getTrackById(r);if(this.trackAnalytics.has(r))(n=this.trackAnalytics.get(r))==null||n.push(S({},a));else if(o){let l=new ns({track:o,sampleWindowSize:this.sampleWindowSize,ssrc:a.ssrc.toString(),kind:a.kind});l.push(S({},a)),this.trackAnalytics.set(r,l)}})}},ns=class extends Xe{constructor(){super(...arguments);this.samples=[];this.createSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),fec_packets_discarded:this.calculateDifferenceForSample("fecPacketsDiscarded"),fec_packets_received:this.calculateDifferenceForSample("fecPacketsReceived"),total_samples_duration:this.calculateDifferenceForSample("totalSamplesDuration"),total_packets_received:this.calculateDifferenceForSample("packetsReceived"),total_packets_lost:this.calculateDifferenceForSample("packetsLost"),total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount")};if(t.kind==="video")return _t(r);{let a=(t.concealedSamples||0)-(t.silentConcealedSamples||0)-((i.concealedSamples||0)-(i.silentConcealedSamples||0));return _t(Object.assign(r,{audio_concealed_samples:a,audio_level:this.calculateInstancesOfHigh("audioLevel",.05),audio_total_samples_received:this.calculateDifferenceForSample("totalSamplesReceived"),audio_concealment_events:this.calculateDifferenceForSample("concealmentEvents")}))}};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===10||tr(i,r)||i.kind==="video"&&er(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}};var ir=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(ir||{});var xt=it(require("sdp-transform"));function Ca(s,e){var r;let t=xt.parse(s.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return s;let i=e?Array.from(e.values()):[];return t.media.forEach(a=>{var l,u,p;let o=(l=a.msid)==null?void 0:l.split(" ")[0],n=(u=i.find(m=>m.type===a.type&&m.stream_id===o))==null?void 0:u.track_id;n&&(a.msid=(p=a.msid)==null?void 0:p.replace(/\s(.+)/,` ${n}`))}),{type:s.type,sdp:xt.write(t)}}function La(s,e){var a;if(!(s!=null&&s.sdp)||!e)return;let i=xt.parse(s.sdp).media.find(o=>se(o.mid)&&parseInt(o.mid)===parseInt(e));return(a=i==null?void 0:i.msid)==null?void 0:a.split(" ")[1]}function Da(s){return s.sdp.includes("usedtx=1")?s:{type:s.type,sdp:s.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var Me="[HMSConnection]",Ne=class{constructor(e,t){this.candidates=new Array;this.role=e,this.signal=t}get iceConnectionState(){return this.nativeConnection.iceConnectionState}get connectionState(){return this.nativeConnection.connectionState}get action(){return this.role===0?"PUBLISH":"SUBSCRIBE"}addTransceiver(e,t){return this.nativeConnection.addTransceiver(e,t)}createOffer(e,t){return c(this,null,function*(){try{let i=yield this.nativeConnection.createOffer(t);return d.d(Me,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),Da(Ca(i,e))}catch(i){throw h.WebrtcErrors.CreateOfferFailed(this.action,i.message)}})}createAnswer(e=void 0){return c(this,null,function*(){try{let t=yield this.nativeConnection.createAnswer(e);return d.d(Me,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw h.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}setLocalDescription(e){return c(this,null,function*(){try{d.d(Me,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(t){throw h.WebrtcErrors.SetLocalDescriptionFailed(this.action,t.message)}})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(Me,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw h.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(Me,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(Me,`[role=${this.role}] addIceCandidate candidate=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.addIceCandidate(e)})}get remoteDescription(){return this.nativeConnection.remoteDescription}getSenders(){return this.nativeConnection.getSenders()}logSelectedIceCandidatePairs(){try{(this.role===0?this.getSenders():this.getReceivers()).forEach(t=>{var r;let i=(r=t.track)==null?void 0:r.kind;if(t.transport){let a=t.transport.iceTransport,o=()=>{typeof a.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=a.getSelectedCandidatePair(),d.d(Me,`${ir[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2)))};typeof a.onselectedcandidatepairchange=="function"&&(a.onselectedcandidatepairchange=o),o()}})}catch(e){d.w(Me,`Error in logging selected ice candidate pair for ${ir[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e){return c(this,null,function*(){let t=e.settings.maxBitrate,i=e instanceof U&&e.settings.maxFramerate,r=this.getSenders().find(a=>{var o;return((o=a==null?void 0:a.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(r){let a=r.getParameters();a.encodings.length===1&&(t&&(a.encodings[0].maxBitrate=t*1e3),i&&(a.encodings[0].maxFramerate=i)),yield r.setParameters(a)}else d.w(Me,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){return c(this,null,function*(){this.nativeConnection.close()})}getReceivers(){return this.nativeConnection.getReceivers()}};var Ut=class extends Ne{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(li,{protocol:"SCTP"}),this.channel.onerror=a=>d.e(this.TAG,`publish data channel onerror ${a}`,a),this.nativeConnection.onicecandidate=({candidate:a})=>{a&&t.trickle(this.role,a)},this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState),this.nativeConnection.sctp&&(this.nativeConnection.sctp.transport.onstatechange=()=>{var a;this.observer.onDTLSTransportStateChange((a=this.nativeConnection.sctp)==null?void 0:a.transport.state)},this.nativeConnection.sctp.transport.onerror=a=>{var o;this.observer.onDTLSTransportError(new Error((o=a==null?void 0:a.error)==null?void 0:o.errorDetail)||"DTLS Transport failed")})}}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var wa=it(require("eventemitter2")),_a=require("uuid");var Vt=class{constructor(e,t,i=""){this.TAG="[HMSDataChannel]";this.nativeChannel=e,this.observer=t,this.metadata=i,e.onmessage=r=>{this.observer.onMessage(r.data)}}get id(){return this.nativeChannel.id}get label(){return this.nativeChannel.label}get readyState(){return this.nativeChannel.readyState}send(e){d.d(this.TAG,`[${this.metadata}] Sending [size=${e.length}] message=${e}`),this.nativeChannel.send(e)}close(){this.nativeChannel.close()}};var Bt=class s extends Ne{constructor(t,i,r,a){super(1,t);this.isFlagEnabled=r;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.pendingMessageQueue=[];this.eventEmitter=new wa.default({maxListeners:60});this.handlePendingApiMessages=()=>{this.eventEmitter.emit("open",!0),this.pendingMessageQueue.length>0&&(d.d(this.TAG,"Found pending message queue, sending messages"),this.pendingMessageQueue.forEach(t=>this.sendOverApiDataChannel(t)),this.pendingMessageQueue.length=0)};this.sendMessage=(t,i)=>c(this,null,function*(){var a;((a=this.apiChannel)==null?void 0:a.readyState)!=="open"&&(yield this.eventEmitter.waitFor("open"));let r;for(let o=0;o<this.MAX_RETRIES;o++){this.apiChannel.send(t),r=yield this.waitForResponse(i);let n=r.error;if(n){if(n.code===404){d.d(this.TAG,`Track not found ${i}`,{request:t,try:o+1,error:n});break}if(d.d(this.TAG,`Failed sending ${i}`,{request:t,try:o+1,error:n}),!(n.code/100===5||n.code===429))throw Error(`code=${n.code}, message=${n.message}`);let u=(2+Math.random()*2)*1e3;yield ue(u)}else break}return r});this.waitForResponse=t=>c(this,null,function*(){let i=yield this.eventEmitter.waitFor("message",function(a){return a.includes(t)}),r=JSON.parse(i[0]);return d.d(this.TAG,`response for ${t} -`,JSON.stringify(r,null,2)),r});this.observer=a,this.nativeConnection=new RTCPeerConnection(i),this.initNativeConnectionCallbacks()}initNativeConnectionCallbacks(){this.nativeConnection.oniceconnectionstatechange=()=>{this.observer.onIceConnectionChange(this.nativeConnection.iceConnectionState)},this.nativeConnection.onconnectionstatechange=()=>{this.observer.onConnectionStateChange(this.nativeConnection.connectionState)},this.nativeConnection.ondatachannel=t=>{t.channel.label===li&&(this.apiChannel=new Vt(t.channel,{onMessage:i=>{this.eventEmitter.emit("message",i),this.observer.onApiChannelMessage(i)}},`role=${this.role}`),t.channel.onopen=this.handlePendingApiMessages)},this.nativeConnection.onicecandidate=t=>{t.candidate!==null&&this.signal.trickle(this.role,t.candidate)},this.nativeConnection.ontrack=t=>{var u;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let p=new me(i,this);this.remoteStreams.set(r,p)}i.addEventListener("removetrack",p=>{if(p.track.id!==t.track.id)return;let m=a.tracks.findIndex(g=>{var f;return g.nativeTrack.id===p.track.id&&t.transceiver.mid===((f=g.transceiver)==null?void 0:f.mid)});if(m>=0){let g=a.tracks[m];this.observer.onTrackRemove(g),a.tracks.splice(m,1),a.tracks.length===0&&this.remoteStreams.delete(r)}});let a=this.remoteStreams.get(r),o=t.track.kind==="audio"?te:_,n=new o(a,t.track);t.track.kind==="video"&&a.setVideoLayerLocally("none","addTrack","subscribeConnection"),n.transceiver=t.transceiver;let l=La(this.remoteDescription,(u=t.transceiver)==null?void 0:u.mid);l&&n.setSdpTrackId(l),a.tracks.push(n),this.observer.onTrackAdd(n)}}sendOverApiDataChannel(t){this.apiChannel&&this.apiChannel.readyState==="open"?this.apiChannel.send(t):(d.w(this.TAG,`API Data channel not ${this.apiChannel?"open":"present"}, queueing`,t),this.pendingMessageQueue.push(t))}sendOverApiDataChannelWithResponse(t,i){return c(this,null,function*(){let r=(0,_a.v4)();if(t.method==="prefer-video-track-state"&&this.isFlagEnabled("disableVideoTrackAutoUnsubscribe")&&t.params.max_spatial_layer==="none")return d.d(this.TAG,"video auto unsubscribe is disabled, request is ignored"),{id:r};let a=JSON.stringify(S({id:i||r,jsonrpc:"2.0"},t));return this.sendMessage(a,r)})}close(){return c(this,null,function*(){var t;yield q(s.prototype,this,"close").call(this),(t=this.apiChannel)==null||t.close()})}};var rr="[InitService]",Ft=class{static handleError(e,t){switch(e.status){case 404:throw h.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw h.APIErrors.ServerErrors(t.code||e.status,"INIT",t.message||(e==null?void 0:e.statusText))}}static fetchInitConfig(o){return c(this,arguments,function*({token:e,peerId:t,userAgent:i,initEndpoint:r="https://prod-init.100ms.live",region:a=""}){d.d(rr,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${a} `);let n=mc(r,t,i,a);try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`}});try{let u=yield l.clone().json();return this.handleError(l,u),d.d(rr,`config is ${JSON.stringify(u,null,2)}`),gc(u)}catch(u){let p=yield l.text();throw d.e(rr,"json error",u.message,p),h.APIErrors.ServerErrors(l.status,"INIT",p)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?h.APIErrors.EndpointUnreachable("INIT",u.message):u}})}};function mc(s,e,t,i){try{let r=new URL("/init",s);return i&&i.trim().length>0&&r.searchParams.set("region",i.trim()),r.searchParams.set("peer_id",e),r.searchParams.set("user_agent_v2",t),r.toString()}catch(r){let a=r;throw d.e(rr,a.name,a.message),a}}function gc(s){var e;return y(S({},s),{rtcConfiguration:y(S({},s.rtcConfiguration),{iceServers:(e=s.rtcConfiguration)==null?void 0:e.ice_servers})})}var Na=require("uuid");var Gt=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ae(5);this.isJoinCompleted=!1;this.pendingTrickle=[];this.socket=null;this.callbacks=new Map;this._isConnected=!1;this.id=0;this.onCloseHandler=()=>{};this.resolvePingOnAnyResponse=()=>{this.callbacks.forEach((e,t)=>{var i;((i=e.metadata)==null?void 0:i.method)==="ping"&&(e.resolve({timestamp:Date.now()}),this.callbacks.delete(t))})};this.offlineListener=()=>{d.d(this.TAG,"Window network offline"),this.setIsConnected(!1,"Window network offline")};this.onlineListener=()=>{d.d(this.TAG,"Window network online"),this.observer.onNetworkOnline()};this.observer=e,window.addEventListener("offline",this.offlineListener),window.addEventListener("online",this.onlineListener),this.onMessageHandler=this.onMessageHandler.bind(this)}get isConnected(){return this._isConnected}setIsConnected(e,t=""){d.d(this.TAG,`isConnected set id: ${this.id}, oldValue: ${this._isConnected}, newValue: ${e}`),this._isConnected!==e&&(this._isConnected&&!e?(this._isConnected=e,this.rejectPendingCalls(t),this.observer.onOffline(t)):!this._isConnected&&e&&(this._isConnected=e,this.observer.onOnline()))}getPongResponseTimes(){return this.pongResponseTimes.toList()}internalCall(e,t){return c(this,null,function*(){var a;let i=(0,Na.v4)(),r={method:e,params:t,id:i,jsonrpc:"2.0"};(a=this.socket)==null||a.send(JSON.stringify(r));try{return yield new Promise((n,l)=>{this.callbacks.set(i,{resolve:n,reject:l,metadata:{method:e}})})}catch(o){if(o instanceof T)throw o;let n=o;throw h.WebsocketMethodErrors.ServerErrors(Number(n.code),Pr(e),n.message)}})}notify(e,t){var r,a;let i={method:e,params:t};((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN&&((a=this.socket)==null||a.send(JSON.stringify(i)))}open(e){return new Promise((t,i)=>{let r=!1;this.socket&&(this.socket.close(),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)),this.socket=new WebSocket(e);let a=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(h.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=n=>{d.w(`Websocket closed code=${n.code}`),r?this.setIsConnected(!1,`code: ${n.code}${n.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(h.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${n.code}`)))},this.socket.addEventListener("error",a);let o=()=>{var n,l;r=!0,t(),this.setIsConnected(!0),this.id++,(n=this.socket)==null||n.removeEventListener("open",o),(l=this.socket)==null||l.removeEventListener("error",a),this.pingPongLoop(this.id)};this.socket.addEventListener("open",o),this.socket.addEventListener("close",this.onCloseHandler),this.socket.addEventListener("message",this.onMessageHandler)})}close(){return c(this,null,function*(){window.removeEventListener("offline",this.offlineListener),window.removeEventListener("online",this.onlineListener),this.socket?(this.socket.close(1e3,"Normal Close"),this.setIsConnected(!1,"code: 1000, normal websocket close"),this.socket.removeEventListener("close",this.onCloseHandler),this.socket.removeEventListener("message",this.onMessageHandler)):this.setIsConnected(!1,"websocket not connected yet")})}join(e,t,i,r,a,o,n){return c(this,null,function*(){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:n,server_sub_degrade:r,simulcast:a,onDemandTracks:o},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:m})=>this.trickle(p,m)),this.pendingTrickle.length=0,d.d(this.TAG,`join: response=${JSON.stringify(u,null,1)}`),u})}trickle(e,t){this.isJoinCompleted?this.notify("trickle",{target:e,candidate:t}):this.pendingTrickle.push({target:e,candidate:t})}offer(e,t){return c(this,null,function*(){return yield this.call("offer",{desc:e,tracks:Object.fromEntries(t)})})}answer(e){this.notify("answer",{desc:e})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(){this.notify("leave",{})}endRoom(e,t){return c(this,null,function*(){yield this.call("end-room",{lock:e,reason:t})})}sendEvent(e){if(!this.isConnected)throw Error(`${this.TAG} not connected. Could not send event ${e}`);this.notify("analytics",e.toSignalParams())}ping(e){let t=Date.now(),i=new Promise(a=>{setTimeout(()=>{a(Date.now()-t)},e+1)}),r=this.internalCall("ping",{timestamp:t}).then(()=>Date.now()-t).catch(()=>Date.now()-t);return Promise.race([i,r])}requestRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}requestBulkRoleChange(e){return c(this,null,function*(){yield this.call("role-change-request",e)})}acceptRoleChangeRequest(e){return c(this,null,function*(){yield this.call("role-change",e)})}requestTrackStateChange(e){return c(this,null,function*(){yield this.call("track-update-request",e)})}requestMultiTrackStateChange(e){return c(this,null,function*(){yield this.call("change-track-mute-state-request",e)})}removePeer(e){return c(this,null,function*(){yield this.call("peer-leave-request",e)})}startRTMPOrRecording(e){return c(this,null,function*(){yield this.call("rtmp-start",S({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",S({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",S({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",S({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",S({},e))})}getPeer(e){return c(this,null,function*(){yield this.call("get-peer",S({},e))})}joinGroup(e){return c(this,null,function*(){return yield this.call("group-join",{name:e})})}leaveGroup(e){return c(this,null,function*(){return yield this.call("group-leave",{name:e})})}addToGroup(e,t){return c(this,null,function*(){yield this.call("group-add",{name:t,peer_id:e})})}removeFromGroup(e,t){return c(this,null,function*(){yield this.call("group-remove",{name:t,peer_id:e})})}peerIterNext(e){return c(this,null,function*(){return yield this.call("peer-iter-next",e)})}findPeers(e){return c(this,null,function*(){return yield this.call("find-peer",e)})}setSessionMetadata(e){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",S({},e))}listenMetadataChange(e){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to observe session store key due to network disconnection");return this.call("listen-metadata-change",{keys:e})}getSessionMetadata(e){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("get-metadata",{key:e})}setPollInfo(e){return this.call("poll-info-set",S({},e))}getPollInfo(e){return this.call("poll-info-get",S({},e))}setPollQuestions(e){return this.call("poll-questions-set",S({},e))}startPoll(e){return this.call("poll-start",S({},e))}stopPoll(e){return this.call("poll-stop",S({},e))}getPollQuestions(e){return this.call("poll-questions-get",S({},e))}setPollResponses(e){return this.call("poll-response",S({},e))}getPollResponses(e){return this.call("poll-responses",S({},e))}getPollsList(e){return this.call("poll-list",S({},e))}getPollResult(e){return this.call("poll-result",S({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",S({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",S({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",S({},e))}validateConnection(){if(!this.isConnected)throw h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to send message due to network disconnection")}onMessageHandler(e){let t=e.data,i=JSON.parse(t);if(this.resolvePingOnAnyResponse(),i.id)this.handleResponseWithId(i);else if(i.method)this.handleResponseWithMethod(i);else throw Error(`WebSocket message has no 'method' or 'id' field, message=${i}`)}handleResponseWithId(e){let t=e,i=t.id;if(this.callbacks.has(i)){let r=this.callbacks.get(i);this.callbacks.delete(i),t.result?r.resolve(t.result):r.reject(t.error)}else this.observer.onNotification(t)}handleResponseWithMethod(e){switch(e.method){case"offer":this.observer.onOffer(e.params);break;case"trickle":this.observer.onTrickle(e.params);break;case"on-error":this.observer.onServerError(h.WebsocketMethodErrors.ServerErrors(Number(e.params.code),"on-error",e.params.message));break;case"on-warning":d.w(this.TAG,e.params);break;default:this.observer.onNotification(e);break}}rejectPendingCalls(e=""){this.callbacks.forEach((t,i)=>{var r,a,o,n;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(a=t.metadata)==null?void 0:a.method}, id=${i}`),t.reject(h.WebSocketConnectionErrors.WebSocketConnectionLost((o=t.metadata)!=null&&o.method?Pr((n=t.metadata)==null?void 0:n.method):"RECONNECT_SIGNAL",e)),this.callbacks.delete(i))})}pingPongLoop(e){return c(this,null,function*(){var i,r;let t=((i=window.HMS)==null?void 0:i.PING_TIMEOUT)||12e3;if(this.isConnected){let a=yield this.ping(t);this.pongResponseTimes.enqueue(a),a>t?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${Os()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>this.pingPongLoop(e),((r=window.HMS)==null?void 0:r.PING_INTERVAL)||3e3)}})}call(e,t){return c(this,null,function*(){let r=h.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`);this.validateConnection();let a;for(a=1;a<=3;a++)try{return d.d(this.TAG,`Try number ${a} sending ${e}`,t),yield this.internalCall(e,t)}catch(o){if(r=o,d.e(this.TAG,`Failed sending ${e} try: ${a}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429))break;let l=(2+Math.random()*2)*1e3;yield ue(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(a,3)} retries`,{method:e,params:t,error:r}),r})}};var Oa=()=>{if(!N||typeof navigator.connection=="undefined")return;let s=navigator.connection;return{downlink:s.downlink,downlinkMax:s.downlinkMax,effectiveType:s.effectiveType,rtt:s.rtt,saveData:s.saveData,type:s.type}};var P="[HMSTransport]:",$t=class{constructor(e,t,i,r,a,o){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=a;this.analyticsTimer=o;this.state="Disconnected";this.trackStates=new Map;this.publishConnection=null;this.subscribeConnection=null;this.maxSubscribeBitrate=0;this.joinRetryCount=0;this.callbacks=new Map;this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;yield this.subscribeConnection.setRemoteDescription(e),d.d(P,`[SUBSCRIBE] Adding ${this.subscribeConnection.candidates.length} ice-candidates`,this.subscribeConnection.candidates);for(let i of this.subscribeConnection.candidates)yield this.subscribeConnection.addIceCandidate(i);this.subscribeConnection.candidates.length=0;let t=yield this.subscribeConnection.createAnswer();yield this.subscribeConnection.setLocalDescription(t),this.signal.answer(t),d.d(P,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(P,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t),this.state="Failed";let i;t instanceof T?i=t:i=h.GenericErrors.Unknown("PUBLISH",t.message),this.observer.onFailure(i),this.eventBus.analytics.publish(M.subscribeFail(i))}}),onTrickle:e=>c(this,null,function*(){let t=e.target===0?this.publishConnection:this.subscribeConnection;t!=null&&t.remoteDescription?yield t.addIceCandidate(e.candidate):t==null||t.candidates.push(e.candidate)}),onNotification:e=>this.observer.onNotification(e),onServerError:e=>c(this,null,function*(){yield this.observer.onStateChange("Failed",e)}),onFailure:e=>{this.joinParameters&&this.retryScheduler.schedule({category:1,error:e,task:this.retrySignalDisconnectTask,originalState:this.state})},onOffline:e=>c(this,null,function*(){d.d(P,"socket offline",Ji[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:h.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(P,"socket online",Ji[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new Gt(this.signalObserver);this.analyticsSignalTransport=new Zi(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.publishConnectionObserver={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:e=>{var r,a,o;if((e==="failed"?d.w.bind(d):d.d.bind(d))(P,`Publisher on dtls transport state change: ${e}`),!e||this.lastPublishDtlsState===e||(this.lastPublishDtlsState=e,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),e!=="connecting"&&e!=="failed"))return;let i=(o=(a=(r=this.initConfig)==null?void 0:r.config)==null?void 0:a.dtlsStateTimeouts)==null?void 0:o[e];!i||i<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var l;let n=(l=this.publishConnection)==null?void 0:l.nativeConnection.connectionState;if(n&&e&&n===e){let u=h.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${e} timeout:${i}ms`,!0);this.eventBus.analytics.publish(M.disconnect(u)),this.observer.onFailure(u)}},i))},onDTLSTransportError:e=>{d.e(P,`onDTLSTransportError ${e.name} ${e.message}`,e),this.eventBus.analytics.publish(M.disconnect(e))},onIceConnectionChange:e=>c(this,null,function*(){(e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Publish ice connection state change: ${e}`)}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,a,o,n;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Publish connection state change: ${e}`),e==="connected"&&((i=this.publishConnection)==null||i.logSelectedIceCandidatePairs()),e==="disconnected"&&setTimeout(()=>{var l,u,p,m,g;((l=this.publishConnection)==null?void 0:l.connectionState)==="disconnected"&&this.handleIceConnectionFailure(0,h.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(p=(u=this.publishConnection)==null?void 0:u.selectedCandidatePair)==null?void 0:p.local.candidate}; remote candidate - ${(g=(m=this.publishConnection)==null?void 0:m.selectedCandidatePair)==null?void 0:g.remote.candidate}`))},5e3),e==="failed"&&(yield this.handleIceConnectionFailure(0,h.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(a=(r=this.publishConnection)==null?void 0:r.selectedCandidatePair)==null?void 0:a.local.candidate}; remote candidate - ${(n=(o=this.publishConnection)==null?void 0:o.selectedCandidatePair)==null?void 0:n.remote.candidate}`)))})};this.subscribeConnectionObserver={onApiChannelMessage:e=>{this.observer.onNotification(JSON.parse(e))},onTrackAdd:e=>{d.d(P,"[Subscribe] onTrackAdd",`${e}`),this.observer.onTrackAdd(e)},onTrackRemove:e=>{d.d(P,"[Subscribe] onTrackRemove",`${e}`),this.observer.onTrackRemove(e)},onIceConnectionChange:e=>c(this,null,function*(){if((e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Subscribe ice connection state change: ${e}`),e==="connected"){let i=this.callbacks.get(qe);this.callbacks.delete(qe),i&&i.promise.resolve(!0)}}),onConnectionStateChange:e=>c(this,null,function*(){var i,r,a,o;(e==="disconnected"?d.w.bind(d):d.d.bind(d))(P,`Subscribe connection state change: ${e}`),e==="failed"&&(yield this.handleIceConnectionFailure(1,h.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(r=(i=this.subscribeConnection)==null?void 0:i.selectedCandidatePair)==null?void 0:r.local.candidate}; remote candidate - ${(o=(a=this.subscribeConnection)==null?void 0:a.selectedCandidatePair)==null?void 0:o.remote.candidate}`))),e==="disconnected"&&setTimeout(()=>{var n,l,u,p,m;((n=this.subscribeConnection)==null?void 0:n.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,h.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local.candidate}; remote candidate - ${(m=(p=this.subscribeConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:m.remote.candidate}`))},5e3),e==="connected"&&this.handleSubscribeConnectionConnected()})};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(P,"Local peer role updated to webrtc role, creating PeerConnections and performing inital publish negotiation \u23F3"),this.createPeerConnections(),yield this.negotiateOnFirstPublish())});this.retryPublishIceFailedTask=()=>c(this,null,function*(){if(this.publishConnection){let e=new Promise((t,i)=>{this.callbacks.set(Ke,{promise:{resolve:t,reject:i},action:"RESTART_ICE",extra:{}})});yield this.performPublishRenegotiation({iceRestart:this.publishConnection.connectionState!=="connected"}),yield e}return!0});this.retrySubscribeIceFailedTask=()=>c(this,null,function*(){if(this.subscribeConnection&&this.subscribeConnection.connectionState!=="connected"){let e=new Promise((i,r)=>{this.callbacks.set(qe,{promise:{resolve:i,reject:r},action:"RESTART_ICE",extra:{}})}),t=new Promise(i=>{setTimeout(i,6e4,!1)});return Promise.race([e,t])}return!0});this.retrySignalDisconnectTask=()=>c(this,null,function*(){var t;d.d(P,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId));let e=(t=this.store.getRoom())!=null&&t.joinedAt?this.signal.isConnected&&(yield this.retryPublishIceFailedTask()):this.signal.isConnected;return this.signal.trackUpdate(this.trackStates),e});var l,u;this.webrtcInternals=new pi(this.store,this.eventBus,(l=this.publishConnection)==null?void 0:l.nativeConnection,(u=this.subscribeConnection)==null?void 0:u.nativeConnection);let n=(p,m)=>c(this,null,function*(){p!==this.state&&(this.state=p,yield this.observer.onStateChange(this.state,m))});this.retryScheduler=new zi(n,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(p=>{var g,f;let m=((f=(g=p.getLocalPeerStats())==null?void 0:g.subscribe)==null?void 0:f.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,m)}),this.eventBus.localAudioEnabled.subscribe(({track:p})=>this.trackUpdate(p)),this.eventBus.localVideoEnabled.subscribe(({track:p})=>this.trackUpdate(p))}getWebrtcInternals(){return this.webrtcInternals}isFlagEnabled(e){var r;let t=(r=this.initConfig)==null?void 0:r.config;return((t==null?void 0:t.enabledFlags)||[]).includes(e)}preview(e,t,i,r,a=!1){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,a);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,a=!1){return c(this,null,function*(){d.d(P,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,a)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,a),yield this.initRtcStatsMonitor(),d.d(P,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(P,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let n=o;throw n.isTerminal=n.isTerminal||n.code===500,yield this.observer.onStateChange(this.state,n),n}d.d(P,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,a=!1){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new ji(e,i,r.name,r.metaData,t,a);try{return yield this.internalConnect(e,t,i)}catch(o){if(o instanceof T&&([v.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,v.WebSocketConnectionErrors.FAILED_TO_CONNECT,v.WebSocketConnectionErrors.ABNORMAL_CLOSE,v.APIErrors.ENDPOINT_UNREACHABLE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429"))){let l=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:l,originalState:this.state,maxFailedRetries:5,changeState:!1})}else throw o}})}leave(e){return c(this,null,function*(){var t,i,r,a,o;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(P,"leaving in transport");try{if(this.state="Leaving",(t=this.publishStatsAnalytics)==null||t.stop(),(i=this.subscribeStatsAnalytics)==null||i.stop(),(r=this.webrtcInternals)==null||r.cleanup(),yield(a=this.publishConnection)==null?void 0:a.close(),yield(o=this.subscribeConnection)==null?void 0:o.close(),e)try{this.signal.leave(),d.d(P,"signal leave done")}catch(n){d.w(P,"failed to send leave on websocket to server",n)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(n){this.eventBus.analytics.publish(M.disconnect(n)),d.e(P,"leave: FAILED \u274C",n)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){for(let t of e)try{yield this.publishTrack(t)}catch(i){this.eventBus.analytics.publish(M.publish({devices:this.deviceManager.getDevices(),error:i}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}trackUpdate(e){let i=Array.from(this.trackStates.values()).find(r=>e.type===r.type&&e.source===r.source);if(i){let r=new Dt(y(S({},i),{mute:!e.enabled}));this.trackStates.set(i.track_id,r),d.d(P,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[i.track_id,r]]))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(P,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Dt(e));let t=new Promise((a,o)=>{this.callbacks.set(Ke,{promise:{resolve:a,reject:o},action:"PUBLISH",extra:{}})}),i=e.stream;i.setConnection(this.publishConnection);let r=this.store.getSimulcastLayers(e.source);i.addTransceiver(e,r),d.time(`publish-${e.trackId}-${e.type}`),yield t,d.timeEnd(`publish-${e.trackId}-${e.type}`),this.store.addTrack(e),yield i.setMaxBitrateAndFramerate(e).then(()=>{d.d(P,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof U?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(a=>d.w(P,"Failed setting maxBitrate and maxFramerate",a)),e.isPublished=!0,d.d(P,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(P,`\u23F3 unpublishTrack: trackId=${e.trackId}`,`${e}`),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId))this.trackStates.delete(e.publishedTrackId);else{let a=Array.from(this.trackStates.values()).find(o=>e.type===o.type&&e.source===o.source);a&&this.trackStates.delete(a.track_id)}let t=new Promise((r,a)=>{this.callbacks.set(Ke,{promise:{resolve:r,reject:a},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e),yield t,yield e.cleanup(),this.store.removeTrack(e),d.d(P,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}waitForLocalRoleAvailability(){if(!this.store.hasRoleDetailsArrived())return new Promise(e=>{this.eventBus.policyChange.subscribeOnce(()=>e())})}createConnectionsAndNegotiateJoin(e,t=!1){return c(this,null,function*(){let i=this.doesLocalPeerNeedWebRTC();i&&this.createPeerConnections(),this.analyticsTimer.start("join_response_time"),yield this.negotiateJoinWithRetry({name:e.name,data:e.metaData,autoSubscribeVideo:t,isWebRTC:i}),this.analyticsTimer.end("join_response_time")})}createPeerConnections(){this.initConfig&&(this.publishConnection||(this.publishConnection=new Ut(this.signal,this.initConfig.rtcConfiguration,this.publishConnectionObserver)),this.subscribeConnection||(this.subscribeConnection=new Bt(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),this.subscribeConnectionObserver)))}negotiateJoinWithRetry(a){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){try{yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})}catch(o){d.e(P,"Join negotiation failed \u274C",o);let n=o instanceof T?o:h.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${o.message}`),l=parseInt(`${n.code/100}`)===5||[v.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(n.code);if(n.code===410&&(n.isTerminal=!0),l){this.joinRetryCount=0,n.isTerminal=!1;let u=()=>c(this,null,function*(){return this.joinRetryCount++,yield this.negotiateJoin({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r})});yield this.retryScheduler.schedule({category:2,error:n,task:u,originalState:"Joined",maxFailedRetries:3,changeState:!1})}else throw o}})}negotiateJoin(a){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i,isWebRTC:r=!0}){return r?yield this.negotiateJoinWebRTC({name:e,data:t,autoSubscribeVideo:i}):yield this.negotiateJoinNonWebRTC({name:e,data:t,autoSubscribeVideo:i})})}negotiateJoinWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){if(d.d(P,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(P,"Publish peer connection not found, cannot negotiate"),!1;let a=yield this.publishConnection.createOffer();yield this.publishConnection.setLocalDescription(a);let o=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),l=this.isFlagEnabled("onDemandTracks"),u=yield this.signal.join(e,t,!i,o,n,l,a);yield this.publishConnection.setRemoteDescription(u);for(let p of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(p);return this.publishConnection.initAfterJoin(),!!u})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(P,"\u23F3 join: Negotiating Non-WebRTC");let a=this.isFlagEnabled("subscribeDegradation"),o=this.isFlagEnabled("simulcast"),n=this.isFlagEnabled("onDemandTracks");return!!(yield this.signal.join(e,t,!i,a,o,n))})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(P,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(P,"Publish peer connection not found, cannot negotiate"),!1;let e=yield this.publishConnection.createOffer(this.trackStates);yield this.publishConnection.setLocalDescription(e);let t=yield this.signal.offer(e,this.trackStates);yield this.publishConnection.setRemoteDescription(t);for(let i of this.publishConnection.candidates)yield this.publishConnection.addIceCandidate(i);return this.publishConnection.initAfterJoin(),!!t})}performPublishRenegotiation(e){return c(this,null,function*(){d.d(P,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(Ke);if(t){if(!this.publishConnection){d.e(P,"Publish peer connection not found, cannot renegotiate");return}try{let i=yield this.publishConnection.createOffer(this.trackStates,e);yield this.publishConnection.setLocalDescription(i),d.time("renegotiation-offer-exchange");let r=yield this.signal.offer(i,this.trackStates);this.callbacks.delete(Ke),d.timeEnd("renegotiation-offer-exchange"),yield this.publishConnection.setRemoteDescription(r),t.promise.resolve(!0),d.d(P,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(i){let r;i instanceof T?r=i:r=h.GenericErrors.Unknown("PUBLISH",i.message),t.promise.reject(r),d.d(P,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(0?3:4)||(e===0?this.retryScheduler.schedule({category:3,error:t,task:this.retryPublishIceFailedTask,originalState:"Joined"}):this.retryScheduler.schedule({category:4,error:t,task:this.retrySubscribeIceFailedTask,originalState:"Joined",maxFailedRetries:1}))})}internalConnect(e,t,i){return c(this,null,function*(){var a;d.d(P,"connect: started \u23F0");let r=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield Ft.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t});let o=this.store.getRoom();return o&&(o.effectsKey=(a=this.initConfig.config.vb)==null?void 0:a.effectsKey,o.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled")),this.analyticsTimer.end("init_response_time"),ve.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(P,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(o){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(M.connect(o,this.getAdditionalAnalyticsProperties(),r,new Date,t)),d.e(P,"\u274C internal connect: failed",o),o}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(P,"aborting join as transport state is disconnected"),h.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw h.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(P,"\u23F3 internal connect: connecting to ws endpoint",this.initConfig.endpoint);let i=new URL(this.initConfig.endpoint);i.searchParams.set("peer",t),i.searchParams.set("token",e),i.searchParams.set("user_agent_v2",this.store.getUserAgent()),i.searchParams.set("protocol_version",sa),i.searchParams.set("protocol_spec",aa),this.endpoint=i.toString(),this.analyticsTimer.start("ws_connect_time"),yield this.signal.open(this.endpoint),this.analyticsTimer.end("ws_connect_time"),this.analyticsTimer.start("on_policy_change_time"),this.analyticsTimer.start("room_state_time"),d.d(P,"\u2705 internal connect: connected to ws endpoint")})}initRtcStatsMonitor(){return c(this,null,function*(){var e,t,i;(i=this.webrtcInternals)==null||i.setPeerConnections({publish:(e=this.publishConnection)==null?void 0:e.nativeConnection,subscribe:(t=this.subscribeConnection)==null?void 0:t.nativeConnection}),this.initStatsAnalytics()})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new Nt(this.store,this.eventBus,this.getValueFromInitConfig("publishStats","maxSampleWindowSize",30),this.getValueFromInitConfig("publishStats","maxSamplePushInterval",300)),(e=this.getWebrtcInternals())==null||e.start()),this.isFlagEnabled("subscribeStats")&&(this.subscribeStatsAnalytics=new Ot(this.store,this.eventBus,this.getValueFromInitConfig("subscribeStats","maxSampleWindowSize",10),this.getValueFromInitConfig("subscribeStats","maxSamplePushInterval",60)),(t=this.getWebrtcInternals())==null||t.start())}getValueFromInitConfig(e,t,i){var r,a;return((a=(r=this.initConfig)==null?void 0:r.config[e])==null?void 0:a[t])||i}doesRoleNeedWebRTC(e){var r,a;if(!this.isFlagEnabled("nonWebRTCDisableOffer"))return!0;let t=!!(e.publishParams.allowed&&((r=e.publishParams.allowed)==null?void 0:r.length)>0),i=!!(e.subscribeParams.subscribeToRoles&&((a=e.subscribeParams.subscribeToRoles)==null?void 0:a.length)>0);return t||i}doesLocalPeerNeedWebRTC(){var t;let e=(t=this.store.getLocalPeer())==null?void 0:t.role;return e?this.doesRoleNeedWebRTC(e):!0}handleSubscribeConnectionConnected(){var t;(t=this.subscribeConnection)==null||t.logSelectedIceCandidatePairs();let e=this.callbacks.get(qe);this.callbacks.delete(qe),e&&e.promise.resolve(!0)}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw h.WebsocketMethodErrors.AlreadyJoined("JOIN",`Cannot join a meeting in ${this.state} state`);this.state==="Disconnected"&&(this.state="Connecting",this.observer.onStateChange(this.state))}sendErrorAnalyticsEvent(e,t){let i=this.getAdditionalAnalyticsProperties(),r;switch(t){case 0:r=M.connect(e,i);break;case 1:r=M.disconnect(e,i);break;case 2:r=M.join({error:e,time:this.analyticsTimer.getTimeTaken("join_time"),init_response_time:this.analyticsTimer.getTimeTaken("init_response_time"),ws_connect_time:this.analyticsTimer.getTimeTaken("ws_connect_time"),on_policy_change_time:this.analyticsTimer.getTimeTaken("on_policy_change_time"),local_audio_track_time:this.analyticsTimer.getTimeTaken("local_audio_track_time"),local_video_track_time:this.analyticsTimer.getTimeTaken("local_video_track_time"),retries_join:this.joinRetryCount});break;case 3:r=M.publish({error:e});break;case 4:r=M.subscribeFail(e);break}this.eventBus.analytics.publish(r)}getSubscribeConnection(){return this.subscribeConnection}getAdditionalAnalyticsProperties(){var o,n,l,u,p,m,g,f;let e=Oa(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(R=>R.degraded).length,r=(u=(l=(n=(o=this.getWebrtcInternals())==null?void 0:o.getCurrentStats())==null?void 0:n.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,a=(f=(g=(m=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:m.getLocalPeerStats())==null?void 0:g.subscribe)==null?void 0:f.bitrate;return{network_info:e,document_hidden:t,num_degraded_tracks:i,bitrate:{publish:r,subscribe:a},max_sub_bitrate:this.maxSubscribeBitrate,recent_pong_response_times:this.signal.getPongResponseTimes(),transport_state:this.state}}};var Ua=(s,e,t)=>c(void 0,null,function*(){let r=Error("something went wrong during fetch");for(let a=0;a<4;a++)try{let o=yield fetch(s,e),n=yield o.clone().json();if(t&&t.length&&!o.ok&&t.includes(n.code))throw h.APIErrors.ServerErrors(n.code,"GET_TOKEN",n.message,!1);return o}catch(o){r=o}throw["Failed to fetch","NetworkError"].some(a=>r.message.includes(a))?h.APIErrors.EndpointUnreachable("GET_TOKEN",r.message):r});function sr(s){if(!s||s.length===0)throw h.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=s.split(".");if(e.length!==3)throw h.APIErrors.InvalidTokenFormat("INIT","Expected 3 '.' separate fields - header, payload and signature respectively");let t=atob(e[1]);try{let i=JSON.parse(t);return{roomId:i.room_id,userId:i.user_id,role:i.role}}catch(i){throw h.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var Va={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},ar=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new ci;this.sdkState=S({},Va);this.playlistSettings={video:{bitrate:Ur},audio:{bitrate:Vr}};this.handleAutoplayError=e=>{var t,i;(i=(t=this.errorListener)==null?void 0:t.onError)==null||i.call(t,e)};this.observer={onNotification:e=>{var t;if(e.method==="on-peer-leave-request"){this.handlePeerLeaveRequest(e.params);return}switch(e.method){case"on-policy-change":this.analyticsTimer.end("on_policy_change_time");break;case"peer-list":this.analyticsTimer.end("peer_list_time"),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled);break;case"room-state":this.analyticsTimer.end("room_state_time");break;default:}(t=this.notificationManager)==null||t.handleNotification(e,this.sdkState.isReconnecting)},onConnected:()=>{this.initNotificationManager()},onTrackAdd:e=>{var t;(t=this.notificationManager)==null||t.handleTrackAdd(e)},onTrackRemove:e=>{var t;(t=this.notificationManager)==null||t.handleTrackRemove(e)},onFailure:e=>{var t;(t=this.errorListener)==null||t.onError(e)},onStateChange:(e,t)=>c(this,null,function*(){var r,a;let i=o=>c(this,null,function*(){var n,l;yield this.internalLeave(!0,o),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(n=this.errorListener)==null?void 0:n.onError)==null||l.call(n,o)),this.sdkState.isReconnecting=!1});switch(e){case"Preview":case"Joined":this.initNotificationManager(),this.transportState==="Reconnecting"&&((r=this.listener)==null||r.onReconnected());break;case"Failed":yield i(t);break;case"Reconnecting":this.sdkState.isReconnecting=!0,(a=this.listener)==null||a.onReconnecting(t);break}this.transportState=e,d.d(this.TAG,"Transport State Change",this.transportState)})};this.handlePeerLeaveRequest=e=>{var r;let t=e.requested_by?this.store.getPeerById(e.requested_by):void 0,i={roomEnded:e.room_end,reason:e.reason,requestedBy:t};(r=this.listener)==null||r.onRemovedFromRoom(i),this.internalLeave(!1)};this.handleDeviceChange=e=>{var t,i,r,a,o,n;if(d.d(this.TAG,"Device Change event",e),(i=(t=this.deviceChangeListener)==null?void 0:t.onDeviceChange)==null||i.call(t,e),e.error&&e.type){let l=e.type.includes("audio")?(r=this.localPeer)==null?void 0:r.audioTrack:(a=this.localPeer)==null?void 0:a.videoTrack;(o=this.errorListener)==null||o.onError(e.error),[v.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,v.TracksErrors.DEVICE_IN_USE,v.TracksErrors.DEVICE_NOT_AVAILABLE].includes(e.error.code)&&l&&(l.setEnabled(!1),(n=this.listener)==null||n.onTrackUpdate(2,l,this.localPeer))}};this.handleAudioPluginError=e=>{var t;d.e(this.TAG,"Audio Plugin Error event",e),(t=this.errorListener)==null||t.onError(e)};this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){var r;yield this.transport.handleLocalRoleUpdate({oldRole:e,newRole:t}),yield(r=this.roleChangeManager)==null?void 0:r.handleLocalPeerRoleUpdate({oldRole:e,newRole:t})});this.sendAudioPresenceFailed=()=>{let e=h.TracksErrors.NoAudioDetected("PREVIEW");d.w(this.TAG,"Audio Presence Failure",this.transportState,e)};this.sendJoinAnalyticsEvent=(e=!1,t)=>{this.eventBus.analytics.publish(M.join(y(S({error:t},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("join_time"),is_preview_called:e,retries_join:this.transport.joinRetryCount})))};this.sendPreviewAnalyticsEvent=e=>{this.eventBus.analytics.publish(M.preview(y(S({error:e},this.analyticsTimer.getTimes()),{time:this.analyticsTimer.getTimeTaken("preview_time")})))};this.sendAnalyticsEvent=e=>{this.analyticsEventsService.queue(e).flush()}}initNotificationManager(){this.notificationManager||(this.notificationManager=new Ki(this.store,this.eventBus,this.transport,this.listener,this.audioListener))}initStoreAndManagers(){var e;if(this.sdkState.isInitialised){(e=this.notificationManager)==null||e.setListener(this.listener),this.audioSinkManager.setListener(this.listener),this.interactivityCenter.setListener(this.listener);return}this.sdkState.isInitialised=!0,this.store=new It,this.eventBus=new Ci,this.wakeLockManager=new Ri,this.networkTestManager=new bi(this.eventBus,this.listener),this.playlistManager=new vt(this,this.eventBus),this.deviceManager=new Lt(this.store,this.eventBus),this.audioSinkManager=new Ct(this.store,this.deviceManager,this.eventBus),this.audioOutput=new Ii(this.deviceManager,this.audioSinkManager),this.audioSinkManager.setListener(this.listener),this.eventBus.autoplayError.subscribe(this.handleAutoplayError),this.localTrackManager=new Te(this.store,this.observer,this.deviceManager,this.eventBus,this.analyticsTimer),this.analyticsEventsService=new Hi(this.store),this.transport=new $t(this.observer,this.deviceManager,this.store,this.eventBus,this.analyticsEventsService,this.analyticsTimer),this.sessionStore=new qi(this.transport),this.interactivityCenter=new wt(this.transport,this.store,this.listener),this.eventBus.analytics.subscribe(this.sendAnalyticsEvent),this.eventBus.deviceChange.subscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.subscribe(this.handleAudioPluginError)}validateJoined(e){if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION",`Not connected - ${e}`)}sendHLSAnalytics(e){this.sendAnalyticsEvent(M.hlsPlayerError(e))}refreshDevices(){return c(this,null,function*(){this.validateJoined("refreshDevices"),yield this.deviceManager.init(!0)})}getWebrtcInternals(){var e;return(e=this.transport)==null?void 0:e.getWebrtcInternals()}getSessionStore(){return this.sessionStore}getPlaylistManager(){return this.playlistManager}getRecordingState(){var e;return(e=this.store.getRoom())==null?void 0:e.recording}getRTMPState(){var e;return(e=this.store.getRoom())==null?void 0:e.rtmp}getHLSState(){var e;return(e=this.store.getRoom())==null?void 0:e.hls}getTemplateAppData(){return this.store.getTemplateAppData()}getInteractivityCenter(){return this.interactivityCenter}getPeerListIterator(e){return new hi(this.transport,this.store,e)}updatePlaylistSettings(e){e.video&&Object.assign(this.playlistSettings.video,e.video),e.audio&&Object.assign(this.playlistSettings.audio,e.audio)}get localPeer(){var e;return(e=this.store)==null?void 0:e.getLocalPeer()}preview(e,t){return c(this,null,function*(){if(Rr(),br(),this.sdkState.isPreviewInProgress)return Promise.reject(h.GenericErrors.PreviewAlreadyInProgress("PREVIEW","Preview already called"));if(["Joined","Reconnecting"].includes(this.transportState))return this.midCallPreview(e.asRole,e.settings);this.analyticsTimer.start("preview_time"),this.setUpPreview(e,t),e.alwaysRequestPermissions&&this.localTrackManager.requestPermissions().then(()=>c(this,null,function*(){yield this.initDeviceManagers()}));let i=!1,r=!1,a=setTimeout(()=>{var o,n;(!i||!r)&&((n=(o=this.listener)==null?void 0:o.onNetworkQuality)==null||n.call(o,-1))},3e3);return new Promise((o,n)=>{let l=()=>c(this,null,function*(){var g;if(this.localPeer){let f=e.asRole&&this.store.getPolicyForRole(e.asRole);this.localPeer.asRole=f||this.localPeer.role}let p=yield this.localTrackManager.getTracksToPublish(e.settings);p.forEach(f=>this.setLocalPeerTrack(f)),(g=this.localPeer)!=null&&g.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),this.sdkState.isPreviewInProgress=!1,this.analyticsTimer.end("preview_time");let m=this.store.getRoom();m&&t.onPreview(m,p),this.sendPreviewAnalyticsEvent(),o()}),u=p=>{var m;this.analyticsTimer.end("preview_time"),p&&((m=this.errorListener)==null||m.onError(p)),this.sendPreviewAnalyticsEvent(p),this.sdkState.isPreviewInProgress=!1,n(p)};this.eventBus.policyChange.subscribeOnce(l),this.eventBus.leave.subscribeOnce(u),this.transport.preview(e.authToken,e.initEndpoint,this.localPeer.peerId,{name:e.userName,metaData:e.metaData||""},e.autoVideoSubscribe).then(p=>{var m;i=!0,clearTimeout(a),p&&e.captureNetworkQualityInPreview&&this.networkTestManager.start((m=p.config)==null?void 0:m.networkHealth).then(()=>{r=!0})}).catch(u)})})}midCallPreview(e,t){return c(this,null,function*(){var a,o;if(!this.localPeer||this.transportState!=="Joined")throw h.GenericErrors.NotConnected("VALIDATION","Not connected - midCallPreview");let i=e&&this.store.getPolicyForRole(e);if(!i)throw h.GenericErrors.InvalidRole("PREVIEW",`role ${e} does not exist in policy`);this.localPeer.asRole=i;let r=yield this.localTrackManager.getTracksToPublish(t);r.forEach(n=>this.setLocalPeerTrack(n)),(a=this.localPeer)!=null&&a.audioTrack&&this.initPreviewTrackAudioLevelMonitor(),yield this.initDeviceManagers(),(o=this.listener)==null||o.onPreview(this.store.getRoom(),r)})}cancelMidCallPreview(){return c(this,null,function*(){var e,t,i;if((!this.localPeer||!this.localPeer.isInPreview())&&d.w(this.TAG,"Cannot cancel mid call preview as preview is not in progress"),(e=this.localPeer)!=null&&e.asRole&&this.localPeer.role){let r=this.localPeer.asRole,a=this.localPeer.role;delete this.localPeer.asRole,yield(t=this.roleChangeManager)==null?void 0:t.diffRolesAndPublishTracks({oldRole:r,newRole:a}),(i=this.listener)==null||i.onPeerUpdate(8,this.localPeer)}})}join(e,t){return c(this,null,function*(){var l,u,p,m,g,f;if(Rr(),br(),this.sdkState.isPreviewInProgress)throw h.GenericErrors.NotReady("JOIN","Preview is in progress, can't join");this.analyticsTimer.start("join_time"),this.sdkState.isJoinInProgress=!0;let{roomId:i,userId:r,role:a}=sr(e.authToken),o=((u=(l=this.localPeer)==null?void 0:l.asRole)==null?void 0:u.name)||((m=(p=this.localPeer)==null?void 0:p.role)==null?void 0:m.name);(g=this.networkTestManager)==null||g.stop(),this.listener=t,this.commonSetup(e,i,t),this.removeDevicesFromConfig(e),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),Pe.resumeContext();let n=this.store.getConfig();n!=null&&n.autoManageWakeLock&&this.wakeLockManager.acquireLock(),this.localPeer?(this.localPeer.name=e.userName,this.localPeer.role=this.store.getPolicyForRole(a),this.localPeer.customerUserId=r,this.localPeer.metadata=e.metaData,delete this.localPeer.asRole):this.createAndAddLocalPeerToStore(e,a,r),this.roleChangeManager=new Ht(this.store,this.transport,this.deviceManager,this.getAndPublishTracks.bind(this),this.removeTrack.bind(this),this.listener),this.eventBus.localRoleUpdate.subscribe(this.handleLocalRoleUpdate),d.d(this.TAG,`\u23F3 Joining room ${i}`),d.time(`join-room-${i}`);try{yield this.transport.join(e.authToken,this.localPeer.peerId,{name:e.userName,metaData:e.metaData},e.initEndpoint,e.autoVideoSubscribe),d.d(this.TAG,`\u2705 Joined room ${i}`),this.analyticsTimer.start("peer_list_time"),yield this.notifyJoin(),this.sdkState.isJoinInProgress=!1,yield this.publish(e.settings,o)}catch(R){throw this.analyticsTimer.end("join_time"),this.sdkState.isJoinInProgress=!1,(f=this.listener)==null||f.onError(R),this.sendJoinAnalyticsEvent(this.sdkState.isPreviewCalled,R),d.e(this.TAG,"Unable to join room",R),R}d.timeEnd(`join-room-${i}`)})}stringifyMetadata(e){e.metaData&&typeof e.metaData!="string"?e.metaData=JSON.stringify(e.metaData):e.metaData||(e.metaData="")}cleanup(){var e,t,i;this.cleanDeviceManagers(),this.eventBus.analytics.unsubscribe(this.sendAnalyticsEvent),this.analyticsTimer.cleanup(),Q.cleanup(),this.playlistManager.cleanup(),(e=this.wakeLockManager)==null||e.cleanup(),Te.cleanup(),this.notificationManager=void 0,d.cleanup(),this.sdkState=S({},Va),this.localPeer&&((t=this.localPeer.audioTrack)==null||t.cleanup(),this.localPeer.audioTrack=void 0,(i=this.localPeer.videoTrack)==null||i.cleanup(),this.localPeer.videoTrack=void 0),this.store.cleanup(),this.listener=void 0,this.roleChangeManager&&this.eventBus.localRoleUpdate.unsubscribe(this.handleLocalRoleUpdate)}leave(e){return this.internalLeave(e)}internalLeave(e=!0,t){return c(this,null,function*(){var r,a,o;let i=(r=this.store)==null?void 0:r.getRoom();if(i){for(;(this.sdkState.isPreviewInProgress||this.sdkState.isJoinInProgress)&&!(t!=null&&t.isTerminal);)yield ue(100);let n=i.id;(a=this.networkTestManager)==null||a.stop(),this.eventBus.leave.publish(t),d.d(this.TAG,`\u23F3 Leaving room ${n}`),yield(o=this.transport)==null?void 0:o.leave(e),this.cleanup(),d.d(this.TAG,`\u2705 Left room ${n}`)}})}getAuthTokenByRoomCode(e,t){return c(this,null,function*(){let i=(t||{}).endpoint||"https://auth.100ms.live/v2/token";this.analyticsTimer.start("GET_TOKEN");let r=yield Ua(i,{method:"POST",body:JSON.stringify({code:e.roomCode,user_id:e.userId})},[429,500,501,502,503,504,505,506,507,508,509,510,511]),a=yield r.json();if(this.analyticsTimer.end("GET_TOKEN"),!r.ok)throw h.APIErrors.ServerErrors(a.code,"GET_TOKEN",a.message,!1);let{token:o}=a;if(!o)throw Error(a.message);return o})}getLocalPeer(){return this.store.getLocalPeer()}getPeers(){return this.store.getPeers()}getPeerMap(){return this.store.getPeerMap()}getAudioOutput(){return this.audioOutput}sendMessage(e,t){this.sendMessageInternal({message:t,type:e})}sendBroadcastMessage(e,t){return c(this,null,function*(){return yield this.sendMessageInternal({message:e,type:t})})}sendGroupMessage(e,t,i){return c(this,null,function*(){let r=this.store.getKnownRoles();if((t.filter(o=>r[o.name])||[]).length===0)throw h.GenericErrors.ValidationFailed("No valid role is present",t);return yield this.sendMessageInternal({message:e,recipientRoles:t,type:i})})}sendDirectMessage(e,t,i){return c(this,null,function*(){var o,n;if(((o=this.localPeer)==null?void 0:o.peerId)===t)throw h.GenericErrors.ValidationFailed("Cannot send message to self");let r=!!((n=this.store.getRoom())!=null&&n.large_room_optimization),a=this.store.getPeerById(t);if(!a)if(r){let{peers:l}=yield this.transport.signal.findPeers({peers:[t],limit:1});if(l.length===0)throw h.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);a=Re(l[0],this.store)}else throw h.GenericErrors.ValidationFailed("Invalid peer - peer not present in the room",t);return yield this.sendMessageInternal({message:e,recipientPeer:a,type:i})})}sendMessageInternal(a){return c(this,arguments,function*({recipientRoles:e,recipientPeer:t,type:i="chat",message:r}){if(r.replace(/\u200b/g," ").trim()==="")throw d.w(this.TAG,"sendMessage","Ignoring empty message send"),h.GenericErrors.ValidationFailed("Empty message not allowed");let o={info:{message:r,type:i}};return e!=null&&e.length&&(o.roles=e.map(n=>n.name)),t!=null&&t.peerId&&(o.peer_id=t.peerId),d.d(this.TAG,"Sending Message: ",o),yield this.transport.signal.broadcast(o)})}startScreenShare(e,t){return c(this,null,function*(){var n,l,u;let i=this.store.getPublishParams();if(!i)return;let{allowed:r}=i;if(!(r&&r.includes("screen"))){d.e(this.TAG,`Role ${(n=this.localPeer)==null?void 0:n.role} cannot share screen`);return}if((u=(l=this.localPeer)==null?void 0:l.auxiliaryTracks)!=null&&u.find(p=>p.source==="screen"))throw Error("Cannot share multiple screens");let o=yield this.getScreenshareTracks(e,t);if(!this.localPeer){d.d(this.TAG,"Screenshared when not connected"),o.forEach(p=>{p.cleanup()});return}yield this.transport.publish(o),o.forEach(p=>{var m,g,f;p.peerId=(m=this.localPeer)==null?void 0:m.peerId,(g=this.localPeer)==null||g.auxiliaryTracks.push(p),(f=this.listener)==null||f.onTrackUpdate(0,p,this.localPeer)})})}stopEndedScreenshare(e){return c(this,null,function*(){d.d(this.TAG,"\u2705 Screenshare ended natively"),yield this.stopScreenShare(),e()})}stopScreenShare(){return c(this,null,function*(){var t;d.d(this.TAG,"\u2705 Screenshare ended from app");let e=(t=this.localPeer)==null?void 0:t.auxiliaryTracks.filter(i=>i.source==="screen");if(e)for(let i of e)yield this.removeTrack(i.trackId)})}addTrack(e,t="regular"){return c(this,null,function*(){var u,p,m,g;if(!e){d.w(this.TAG,"Please pass a valid MediaStreamTrack");return}if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot addTrack");if(this.localPeer.auxiliaryTracks.find(f=>f.trackId===e.id))return;let r=e.kind,a=new MediaStream([e]),o=new we(a),n=r==="audio"?oe:U,l=new n(o,e,t,this.eventBus);this.setPlaylistSettings({track:e,hmsTrack:l,source:t}),yield(u=this.transport)==null?void 0:u.publish([l]),l.peerId=(p=this.localPeer)==null?void 0:p.peerId,(m=this.localPeer)==null||m.auxiliaryTracks.push(l),(g=this.listener)==null||g.onTrackUpdate(0,l,this.localPeer)})}removeTrack(e,t=!1){return c(this,null,function*(){var r;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot removeTrack");let i=this.localPeer.auxiliaryTracks.findIndex(a=>a.trackId===e);if(i>-1){let a=this.localPeer.auxiliaryTracks[i];a.isPublished?yield this.transport.unpublish([a]):yield a.cleanup(),t||this.stopPlaylist(a),this.localPeer.auxiliaryTracks.splice(i,1),(r=this.listener)==null||r.onTrackUpdate(1,a,this.localPeer)}else d.w(this.TAG,`No track found for ${e}`)})}setAnalyticsLevel(e){this.analyticsEventsService.level=e}setLogLevel(e){d.level=e}addAudioListener(e){var t;this.audioListener=e,(t=this.notificationManager)==null||t.setAudioListener(e)}addConnectionQualityListener(e){var t;(t=this.notificationManager)==null||t.setConnectionQualityListener(e)}changeRole(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeer(e,t,i=!1){return c(this,null,function*(){var r;yield(r=this.transport)==null?void 0:r.signal.requestRoleChange({requested_for:e,role:t,force:i})})}changeRoleOfPeersWithRoles(e,t){return c(this,null,function*(){var i;e.length<=0||!t||(yield(i=this.transport)==null?void 0:i.signal.requestBulkRoleChange({roles:e.map(r=>r.name),role:t,force:!0}))})}acceptChangeRole(e){return c(this,null,function*(){var t,i;yield(i=this.transport)==null?void 0:i.signal.acceptRoleChangeRequest({requested_by:(t=e.requestedBy)==null?void 0:t.peerId,role:e.role.name,token:e.token})})}endRoom(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot end room");yield(i=this.transport)==null?void 0:i.signal.endRoom(e,t),yield this.leave()})}removePeer(e,t){return c(this,null,function*(){var i;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot remove peer");yield(i=this.transport)==null?void 0:i.signal.removePeer({requested_for:e,reason:t})})}startRTMPOrRecording(e){return c(this,null,function*(){var i,r;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start streaming or recording");let t={meeting_url:e.meetingURL,record:e.record};(i=e.rtmpURLs)!=null&&i.length&&(t.rtmp_urls=e.rtmpURLs),e.resolution&&(t.resolution=e.resolution),yield(r=this.transport)==null?void 0:r.signal.startRTMPOrRecording(t)})}stopRTMPAndRecording(){return c(this,null,function*(){var e;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop streaming or recording");yield(e=this.transport)==null?void 0:e.signal.stopRTMPAndRecording()})}startHLSStreaming(e){return c(this,null,function*(){var i;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot start HLS streaming");let t={};e&&e.variants&&e.variants.length>0&&(t.variants=e.variants.map(r=>{let a={meeting_url:r.meetingURL};return r.metadata&&(a.metadata=r.metadata),a})),e!=null&&e.recording&&(t.hls_recording={single_file_per_layer:e.recording.singleFilePerLayer,hls_vod:e.recording.hlsVod}),yield(i=this.transport)==null?void 0:i.signal.startHLSStreaming(t)})}stopHLSStreaming(e){return c(this,null,function*(){var t,i,r;if(!this.localPeer)throw h.GenericErrors.NotConnected("VALIDATION","No local peer present, cannot stop HLS streaming");if(e){let a={variants:(t=e==null?void 0:e.variants)==null?void 0:t.map(o=>{let n={meeting_url:o.meetingURL};return o.metadata&&(n.metadata=o.metadata),n})};yield(i=this.transport)==null?void 0:i.signal.stopHLSStreaming(a)}yield(r=this.transport)==null?void 0:r.signal.stopHLSStreaming()})}sendHLSTimedMetadata(e){return c(this,null,function*(){var t;if(this.validateJoined("sendHLSTimedMetadata"),e.length>0){let i={metadata_objs:e};yield(t=this.transport)==null?void 0:t.signal.sendHLSTimedMetadata(i)}})}changeName(e){return c(this,null,function*(){var i,r;this.validateJoined("changeName");let t=this.store.getLocalPeer();t&&t.name!==e&&(yield(i=this.transport)==null?void 0:i.signal.updatePeer({name:e}),(r=this.notificationManager)==null||r.updateLocalPeer({name:e}))})}changeMetadata(e){return c(this,null,function*(){var t,i;this.validateJoined("changeMetadata"),yield(t=this.transport)==null?void 0:t.signal.updatePeer({data:e}),(i=this.notificationManager)==null||i.updateLocalPeer({metadata:e})})}setSessionMetadata(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.setSessionMetadata({key:"default",data:e})})}getSessionMetadata(){return c(this,null,function*(){var t;return(yield(t=this.transport)==null?void 0:t.signal.getSessionMetadata("default")).data})}getRoles(){return Object.values(this.store.getKnownRoles())}changeTrackState(e,t){return c(this,null,function*(){var r;if(e.type==="video"&&e.source!=="regular"){d.w(this.TAG,"Muting non-regular video tracks is currently not supported");return}if(e.enabled===t){d.w(this.TAG,`Aborting change track state, track already has enabled - ${t}`,e);return}if(!this.store.getTrackById(e.trackId))throw h.GenericErrors.ValidationFailed("No track found for change track state",e);let i=this.store.getPeerByTrackId(e.trackId);if(!i)throw h.GenericErrors.ValidationFailed("No peer found for change track state",e);yield(r=this.transport)==null?void 0:r.signal.requestTrackStateChange({requested_for:i.peerId,track_id:e.trackId,stream_id:e.stream.id,mute:!t})})}changeMultiTrackState(e){return c(this,null,function*(){var o;if(typeof e.enabled!="boolean")throw h.GenericErrors.ValidationFailed("Pass a boolean for enabled");let{enabled:t,roles:i,type:r,source:a}=e;yield(o=this.transport)==null?void 0:o.signal.requestMultiTrackStateChange({value:!t,type:r,source:a,roles:i==null?void 0:i.map(n=>n==null?void 0:n.name)})})}raiseLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("raiseLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.joinGroup(fe)})}lowerLocalPeerHand(){return c(this,null,function*(){var e;this.validateJoined("lowerLocalPeerHand"),yield(e=this.transport)==null?void 0:e.signal.leaveGroup(fe)})}raiseRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.addToGroup(e,fe)})}lowerRemotePeerHand(e){return c(this,null,function*(){var t;yield(t=this.transport)==null?void 0:t.signal.removeFromGroup(e,fe)})}setFrameworkInfo(e){this.frameworkInfo=S(S({},this.frameworkInfo),e)}attachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.attach(t):yield e.addSink(t)})}detachVideo(e,t){return c(this,null,function*(){let i=this.store.getConfig();i!=null&&i.autoManageVideo?e.detach(t):yield e.removeSink(t)})}publish(e,t){return c(this,null,function*(){var i,r,a;if([this.store.getPublishParams(),!this.sdkState.published,!Ce].every(o=>!!o)){let o=t&&t!==((r=(i=this.localPeer)==null?void 0:i.role)==null?void 0:r.name)?()=>{var n;return(n=this.roleChangeManager)==null?void 0:n.diffRolesAndPublishTracks({oldRole:this.store.getPolicyForRole(t),newRole:this.localPeer.role})}:()=>this.getAndPublishTracks(e);yield(a=o==null?void 0:o())==null?void 0:a.catch(n=>{var l;d.e(this.TAG,"Error in publish",n),(l=this.listener)==null||l.onError(n)})}})}getAndPublishTracks(e){return c(this,null,function*(){var i,r;let t=yield this.localTrackManager.getTracksToPublish(e);yield this.setAndPublishTracks(t),(r=(i=this.localPeer)==null?void 0:i.audioTrack)==null||r.initAudioLevelMonitor(),this.sdkState.published=!0})}setAndPublishTracks(e){return c(this,null,function*(){var t;for(let i of e)yield this.transport.publish([i]),this.setLocalPeerTrack(i),(t=this.listener)==null||t.onTrackUpdate(0,i,this.localPeer);yield this.initDeviceManagers()})}setLocalPeerTrack(e){var t;switch(e.peerId=(t=this.localPeer)==null?void 0:t.peerId,e.type){case"audio":this.localPeer.audioTrack=e;break;case"video":this.localPeer.videoTrack=e;break}}initDeviceManagers(){return c(this,null,function*(){var e,t,i,r,a;this.sdkState.deviceManagersInitialised||(this.sdkState.deviceManagersInitialised=!0,yield this.deviceManager.init(),(yield this.deviceManager.updateOutputDevice((t=(e=this.store.getConfig())==null?void 0:e.settings)==null?void 0:t.audioOutputDeviceId))||(yield this.deviceManager.updateOutputDevice((r=(i=Q.getSelection())==null?void 0:i.audioOutput)==null?void 0:r.deviceId)),this.audioSinkManager.init((a=this.store.getConfig())==null?void 0:a.audioSinkElementId))})}cleanDeviceManagers(){this.eventBus.deviceChange.unsubscribe(this.handleDeviceChange),this.eventBus.audioPluginFailed.unsubscribe(this.handleAudioPluginError),this.eventBus.autoplayError.unsubscribe(this.handleAutoplayError),this.deviceManager.cleanup(),this.audioSinkManager.cleanup()}initPreviewTrackAudioLevelMonitor(){var t;let e=(t=this.localPeer)==null?void 0:t.audioTrack;e==null||e.initAudioLevelMonitor(),this.eventBus.trackAudioLevelUpdate.subscribe(i=>{var a;let r=i&&i.track.trackId===(e==null?void 0:e.trackId)?[{audioLevel:i.audioLevel,peer:this.localPeer,track:e}]:[];this.store.updateSpeakers(r),(a=this.audioListener)==null||a.onAudioLevelUpdate(r)}),this.eventBus.localAudioSilence.subscribe(this.sendAudioPresenceFailed)}notifyJoin(){var i;let e=this.store.getLocalPeer(),t=this.store.getRoom();if(!t){d.w(this.TAG,"notify join - room not present");return}if(t.joinedAt=new Date,e&&(e.joinedAt=t.joinedAt),e!=null&&e.role){this.analyticsTimer.end("join_time"),(i=this.listener)==null||i.onJoin(t);return}return new Promise((r,a)=>{this.eventBus.policyChange.subscribeOnce(()=>{var o;this.analyticsTimer.end("join_time"),(o=this.listener)==null||o.onJoin(t),r()}),this.eventBus.leave.subscribeOnce(o=>{a(o)})})}setUpPreview(e,t){this.listener=t,this.sdkState.isPreviewCalled=!0,this.sdkState.isPreviewInProgress=!0;let{roomId:i,userId:r,role:a}=sr(e.authToken);this.commonSetup(e,i,t),this.store.setConfig(e),this.store.createAndSetUserAgent(this.frameworkInfo),this.createAndAddLocalPeerToStore(e,a,r,e.asRole)}setPlaylistSettings(r){return c(this,arguments,function*({track:e,hmsTrack:t,source:i}){var a,o;if(i==="videoplaylist"){let n={};if(e.kind==="audio")n.maxBitrate=((a=this.playlistSettings.audio)==null?void 0:a.bitrate)||Vr;else{n.maxBitrate=((o=this.playlistSettings.video)==null?void 0:o.bitrate)||Ur;let{width:l,height:u}=e.getSettings();n.width=l,n.height=u}yield t.setSettings(n)}else i==="audioplaylist"&&(yield t.setSettings({maxBitrate:64}))})}createAndAddLocalPeerToStore(e,t,i,r){let a=this.store.getPolicyForRole(t),o=r?this.store.getPolicyForRole(r):void 0,n=new Tt({name:e.userName||"",customerUserId:i,metadata:e.metaData||"",role:a,asRole:o||a});this.store.addPeer(n)}commonSetup(e,t,i){this.stringifyMetadata(e),e.initEndpoint||(e.initEndpoint="https://prod-init.100ms.live"),this.errorListener=i,this.deviceChangeListener=i,this.initStoreAndManagers(),this.store.setErrorListener(this.errorListener),this.store.getRoom()||this.store.setRoom(new Rt(t))}removeDevicesFromConfig(e){this.store.getConfig()&&e.settings&&(delete e.settings.audioOutputDeviceId,delete e.settings.videoDeviceId,delete e.settings.audioInputDeviceId)}getScreenshareTracks(e,t){return c(this,null,function*(){let[i,r]=yield this.localTrackManager.getLocalScreen(t),a=()=>{this.stopEndedScreenshare(e)},o=[];if(t!=null&&t.audioOnly){if(i.nativeTrack.stop(),!r)throw h.TracksErrors.NothingToReturn("TRACK","Select share audio when sharing screen","No audio found");o.push(r),r.nativeTrack.addEventListener("ended",a)}else o.push(i),i.nativeTrack.addEventListener("ended",a),r&&o.push(r);return o})}stopPlaylist(e){e.source==="audioplaylist"?this.playlistManager.stop("audio"):e.source==="videoplaylist"&&this.playlistManager.stop("video")}};var Oe=class s{constructor(e,t,i){this.getStats=()=>(this.stats||(this.stats=new Ze(this.store,this.sdk)),this.stats);e?this.store=e:this.store=s.createNewHMSStore(Ai("HMSStore"),rt),i?this.notifications=i:this.notifications=new vi(this.store),t?this.actions=t:(this.sdk=new ar,this.actions=new Pi(this.store,this.sdk,this.notifications)),this.actions.setFrameworkInfo({type:"js",sdkVersion:Hr().version}),this.initialTriggerOnSubscribe=!1,N&&(window.__hms=this)}triggerOnSubscribe(){this.initialTriggerOnSubscribe||(s.makeStoreTriggerOnSubscribe(this.store),this.initialTriggerOnSubscribe=!0)}getStore(){return this.store}getHMSActions(){return this.actions}getActions(){return this.actions}getNotifications(){return{onNotification:this.notifications.onNotification}}static createNewHMSStore(e,t){let i=(0,Ga.default)(()=>t()),r=i.setState;i.setState=n=>{let l=typeof n=="function"?(0,Ba.produce)(n):n;r(l)};let a=i.getState;i.getState=n=>n?n(a()):a(),s.compareWithShallowCheckInSubscribe(i);let o=s.setUpDevtools(i,e);return y(S({},i),{namedSetState:o})}static makeStoreTriggerOnSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,a)=>(i(e.getState(r),void 0),t(i,r,a))}static compareWithShallowCheckInSubscribe(e){let t=e.subscribe;e.subscribe=(i,r,a)=>(r||(r=o=>o),a=a||Fa.default,t(i,r,a))}static setUpDevtools(e,t){let i;try{i=window.__REDUX_DEVTOOLS_EXTENSION__||window.top.__REDUX_DEVTOOLS_EXTENSION__}catch(o){}if(!i)return o=>{e.setState(o)};let r=i.connect(s.devtoolsOptions(t));r.prefix=t?`${t} > `:"";let a=e.setState;return e.setState=o=>{a(o),r.send(`${r.prefix}setState`,e.getState())},r.subscribe(s.devtoolsSubscribe(r,e,a)),r.send("setUpStore",e.getState()),(o,n)=>{a(o);let l=n||`${r.prefix}action`;r.send(l,e.getState())}}static devtoolsOptions(e){return{name:e,actionsBlacklist:["audioLevel","playlistProgress","connectionQuality"]}}static devtoolsSubscribe(e,t,i){return r=>{var a,o,n,l;if(r.type==="DISPATCH"&&r.state)["JUMP_TO_ACTION","JUMP_TO_STATE"].includes(r.payload.type)?i(JSON.parse(r.state)):t.setState(JSON.parse(r.state));else if(r.type==="DISPATCH"&&((a=r.payload)==null?void 0:a.type)==="COMMIT")e.init(t.getState());else if(r.type==="DISPATCH"&&((o=r.payload)==null?void 0:o.type)==="IMPORT_STATE"){let u=(n=r.payload.nextLiftedState)==null?void 0:n.actionsById;(((l=r.payload.nextLiftedState)==null?void 0:l.computedStates)||[]).forEach(({state:m},g)=>{let f=u[g]||`${e.prefix}setState`;g===0?e.init(m):(i(m),e.send(f,t.getState()))})}}}};var Wa=(s,e,t)=>{let i;t.getState(J)==="Connected"&&(i=$a(s,e,t)),t.subscribe(r=>{["Connected","Reconnecting"].includes(r)?i||(i=$a(s,e,t)):["Disconnected","Failed"].includes(r)&&i&&(kc(e,r),i(),i=void 0)},J)},$a=(s,e,t)=>{var a,o;let i=Mc(t,e);(a=s.getWebrtcInternals())==null||a.start();let r=(o=s.getWebrtcInternals())==null?void 0:o.onStatsChange(n=>yc(e,n,t,s));return()=>{i(),r&&r()}},Mc=(s,e)=>{let t,i,r;return s.getState(ne)?e.namedSetState(a=>{a.localPeer.id=s.getState(ne)},"localpeer-id"):t=s.subscribe(a=>{a&&e.namedSetState(o=>{o.localPeer.id=a},"localpeer-id")},ne),s.getState($)?e.namedSetState(a=>{a.localPeer.videoTrack=s.getState($)},"localpeer-videotrack-id"):i=s.subscribe(a=>{a&&e.namedSetState(o=>{o.localPeer.videoTrack=a},"localpeer-videotrack-id")},$),s.getState(Y)?e.namedSetState(a=>{a.localPeer.audioTrack=s.getState(Y)},"localpeer-audiotrack-id"):r=s.subscribe(a=>{a&&e.namedSetState(o=>{o.localPeer.audioTrack=a},"localpeer-audiotrack-id")},Y),()=>{t==null||t(),i==null||i(),r==null||r()}},yc=(s,e,t,i)=>{let r=t.getState(D);s.namedSetState(a=>{let o=t.getState(ne),n={},l=Object.keys(r).filter(p=>r[p].peerId!==o);for(let p of l){let m=e.getRemoteTrackStats(p);m&&(n[p]=m)}es(a.remoteTrackStats,n);let u={[o]:e.getLocalPeerStats()};es(a.peerStats,u),Aa(a.localTrackStats,e.getLocalTrackStats(),i.store.getLocalPeerTracks())},"webrtc-stats")},kc=(s,e="resetState")=>{s.namedSetState(t=>{Object.assign(t,st())},e)};var Ze=class{constructor(e,t){this.hmsStore=e;this.sdk=t;this.store=Oe.createNewHMSStore(Ai("HMSStatsStore"),st),this.getState=this.store.getState,this.subscribe=this.store.subscribe,this.getPublishPeerConnection=()=>new Promise(i=>{var r,a;this.hmsStore.getState(J)==="Connected"?i((a=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:a.getPublishPeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getPublishPeerConnection())},J)}),this.getSubscribePeerConnection=()=>new Promise(i=>{var r,a;this.hmsStore.getState(J)==="Connected"?i((a=(r=this.sdk)==null?void 0:r.getWebrtcInternals())==null?void 0:a.getSubscribePeerConnection()):this.hmsStore.subscribe(o=>{var n,l;o==="Connected"&&i((l=(n=this.sdk)==null?void 0:n.getWebrtcInternals())==null?void 0:l.getSubscribePeerConnection())},J)}),this.sdk&&Wa(this.sdk,this.store,this.hmsStore)}};var B=require("reselect");var Ec=s=>s.localPeer.id,Pc=s=>s.localPeer.audioTrack,Ac=s=>s.localPeer.videoTrack,bc=(s,e)=>e,Ka=(s,e)=>e,Rc=s=>s.remoteTrackStats,qa=s=>s.peerStats,ds=s=>s.localTrackStats,ye=(0,B.createSelector)([qa,Ec],(s,e)=>s[e]),Hc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.packetsLost}),Ic=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.jitter}),Cc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.publish)==null?void 0:e.bitrate}),Lc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.bitrate}),Dc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.publish)==null?void 0:e.availableOutgoingBitrate}),wc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.availableIncomingBitrate}),_c=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.publish)==null?void 0:e.bytesSent}),Nc=(0,B.createSelector)(ye,s=>{var e;return(e=s==null?void 0:s.subscribe)==null?void 0:e.bytesReceived}),Oc=(0,B.createSelector)([qa,bc],(s,e)=>e?s[e]:void 0),xc=(0,B.createSelector)([Rc,Ka],(s,e)=>e?s[e]:void 0),ls=(0,B.createSelector)([ds,Ka],(s,e)=>e?s[e]:void 0),Uc=A(Oc),Vc=A(xc),Bc=(0,B.createSelector)([ds,Pc],(s,e)=>{var t;return e?(t=s[e])==null?void 0:t[0]:void 0}),Fc=A((0,B.createSelector)(ls,s=>s==null?void 0:s[0])),Gc=(0,B.createSelector)([ds,Ac],(s,e)=>{var t;return e?(t=s[e])==null?void 0:t[0]:void 0}),$c=A((0,B.createSelector)(ls,s=>s)),Wc=s=>A((0,B.createSelector)(ls,e=>{let t=Object.keys(be).find(i=>be[i]===s);return s&&(e==null?void 0:e.find(i=>i.rid===t))||(e==null?void 0:e[0])})),ja={localPeerStats:ye,packetsLost:Hc,jitter:Ic,publishBitrate:Cc,subscribeBitrate:Lc,availablePublishBitrate:Dc,availableSubscribeBitrate:wc,totalBytesSent:_c,totalBytesReceived:Nc,peerStatsByID:Uc,trackStatsByID:Vc,localAudioTrackStatsByID:Fc,localVideoTrackStatsByID:$c,localVideoTrackStatsByLayer:Wc,localAudioTrackStats:Bc,localVideoTrackStats:Gc};
83
83
  //# sourceMappingURL=index.cjs.js.map