@100mslive/hms-video-store 0.15.2-alpha.2 → 0.15.2-alpha.3

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 lo=Object.create;var bt=Object.defineProperty,uo=Object.defineProperties,po=Object.getOwnPropertyDescriptor,ho=Object.getOwnPropertyDescriptors,mo=Object.getOwnPropertyNames,gi=Object.getOwnPropertySymbols,ta=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty,ia=Object.prototype.propertyIsEnumerable,So=Reflect.get;var ra=Math.pow,ea=(a,e,t)=>e in a?bt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))Gr.call(e,t)&&ea(a,t,e[t]);if(gi)for(var t of gi(e))ia.call(e,t)&&ea(a,t,e[t]);return a},y=(a,e)=>uo(a,ho(e));var $r=(a,e)=>{var t={};for(var i in a)Gr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&gi)for(var i of gi(a))e.indexOf(i)<0&&ia.call(a,i)&&(t[i]=a[i]);return t};var go=(a,e)=>()=>{try{return e||a((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},To=(a,e)=>{for(var t in e)bt(a,t,{get:e[t],enumerable:!0})},sa=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mo(e))!Gr.call(a,r)&&r!==t&&bt(a,r,{get:()=>e[r],enumerable:!(i=po(e,r))||i.enumerable});return a};var We=(a,e,t)=>(t=a!=null?lo(ta(a)):{},sa(e||!a||!a.__esModule?bt(t,"default",{value:a,enumerable:!0}):t,a)),fo=a=>sa(bt({},"__esModule",{value:!0}),a);var me=(a,e,t)=>So(ta(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=l=>{try{o(t.next(l))}catch(u){r(u)}},n=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(s,n);o((t=t.apply(a,e)).next())});var Zr=go((hu,bo)=>{bo.exports={version:"0.15.2-alpha.2",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist"],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","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^2.0.6",uuid:"^11.1.1","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.39","@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:"5a301d4301bf3bf16809df84b3eb2ac994daa3da"}});var Il={};To(Il,{ConnectivityState:()=>On,DeviceType:()=>ls,Diagnostics:()=>gt,DomainCategory:()=>Qr,EventBus:()=>Tt,HLSPlaylistType:()=>ns,HLSStreamType:()=>os,HMSAudioDeviceCategory:()=>Ci,HMSAudioMode:()=>Hi,HMSAudioPluginType:()=>Ei,HMSLogLevel:()=>Kr,HMSMessageType:()=>aa,HMSNotificationSeverity:()=>Wr,HMSNotificationTypes:()=>fi,HMSPeerType:()=>Ri,HMSPlaylistType:()=>qr,HMSPluginUnsupportedTypes:()=>Pi,HMSReactiveStore:()=>tt,HMSRecordingState:()=>as,HMSRoomState:()=>Ti,HMSStats:()=>kt,HMSTrackExceptionTrackType:()=>zr,HMSTranscriptionMode:()=>ds,HMSTranscriptionState:()=>cs,HMSVideoPluginCanvasContextType:()=>xi,HMSVideoPluginType:()=>Oi,createDefaultStatsStore:()=>At,createDefaultStoreState:()=>It,getAudioDeviceCategory:()=>Li,parsedUserAgent:()=>Q,selectAppData:()=>Wc,selectAppDataByPath:()=>Kc,selectAudioPlaylist:()=>Ls,selectAudioPlaylistTrackByPeerID:()=>od,selectAudioTrackByID:()=>Qc,selectAudioTrackByPeerID:()=>Mn,selectAudioTrackVolume:()=>Bs,selectAudioVolumeByPeerID:()=>hd,selectAuxiliaryAudioByPeerID:()=>sd,selectAuxiliaryTracksByPeerID:()=>Zc,selectAvailableRoleNames:()=>vc,selectBroadcastMessages:()=>Pn,selectBroadcastMessagesUnreadCount:()=>fd,selectCameraStreamByPeerID:()=>Xc,selectConnectionQualities:()=>zo,selectConnectionQualityByPeerID:()=>rd,selectDegradedTracks:()=>hc,selectDevices:()=>Qo,selectDidIJoinWithin:()=>Gd,selectDominantSpeaker:()=>sc,selectEffectsKey:()=>Lc,selectErrors:()=>an,selectFullAppData:()=>Ki,selectHLSState:()=>Ec,selectHMSBroadcastMessages:()=>cn,selectHMSMessages:()=>mt,selectHMSMessagesCount:()=>mc,selectHMSStats:()=>co,selectHandRaisedPeers:()=>Nc,selectHasPeerHandRaised:()=>Id,selectIsAllowedToPreviewMedia:()=>_d,selectIsAllowedToPublish:()=>Dd,selectIsAllowedToSubscribe:()=>Mc,selectIsAudioLocallyMuted:()=>Us,selectIsConnectedToRoom:()=>Ce,selectIsEffectsEnabled:()=>Hc,selectIsInPreview:()=>bs,selectIsLargeRoom:()=>Rc,selectIsLocalAudioEnabled:()=>ac,selectIsLocalAudioInterrupted:()=>nc,selectIsLocalAudioPluginPresent:()=>Bd,selectIsLocalScreenShared:()=>Ji,selectIsLocalVideoDisplayEnabled:()=>Ps,selectIsLocalVideoEnabled:()=>ji,selectIsLocalVideoInterrupted:()=>oc,selectIsLocalVideoPluginPresent:()=>Ud,selectIsLocallyMutedByPeerID:()=>ud,selectIsPeerAudioEnabled:()=>dd,selectIsPeerVideoEnabled:()=>ld,selectIsRoleAllowedToPublish:()=>Nd,selectIsScreenShareLocallyMutedByPeerID:()=>pd,selectIsSomeoneScreenSharing:()=>cc,selectIsTranscriptionAllowedByMode:()=>Hd,selectIsTranscriptionEnabled:()=>fc,selectIsVBEnabled:()=>Cc,selectLocalAudioTrackID:()=>ue,selectLocalMediaSettings:()=>ks,selectLocalPeer:()=>X,selectLocalPeerID:()=>Ie,selectLocalPeerName:()=>ec,selectLocalPeerRole:()=>Ye,selectLocalPeerRoleName:()=>tc,selectLocalTrackIDs:()=>Es,selectLocalVideoTrackID:()=>ie,selectMessageByMessageID:()=>Rd,selectMessageIDsInOrder:()=>ys,selectMessagesByPeerID:()=>vd,selectMessagesByRole:()=>Md,selectMessagesMap:()=>$t,selectMessagesUnreadCountByPeerID:()=>kd,selectMessagesUnreadCountByRole:()=>yd,selectPeerAudioByID:()=>id,selectPeerByCondition:()=>Vd,selectPeerByID:()=>se,selectPeerCount:()=>Yo,selectPeerMetadata:()=>bd,selectPeerName:()=>Ad,selectPeerNameByID:()=>jc,selectPeerScreenSharing:()=>on,selectPeerSharingAudio:()=>dc,selectPeerSharingAudioPlaylist:()=>pc,selectPeerSharingVideoPlaylist:()=>uc,selectPeerTypeByID:()=>Jc,selectPeers:()=>Me,selectPeersByCondition:()=>Fd,selectPeersByRole:()=>Ed,selectPeersByRoles:()=>Pd,selectPeersMap:()=>Y,selectPeersScreenSharing:()=>lc,selectPeersWithAudioStatus:()=>Cd,selectPermissions:()=>As,selectPollByID:()=>Vs,selectPolls:()=>_c,selectPollsMap:()=>Rs,selectPreviewRole:()=>Is,selectPreviewRoleName:()=>dn,selectRTMPState:()=>kc,selectRecentError:()=>jo,selectRecordingState:()=>yc,selectRemotePeers:()=>rc,selectRoleByRoleName:()=>bn,selectRoleChangeRequest:()=>wd,selectRolesMap:()=>ye,selectRoom:()=>V,selectRoomID:()=>Jo,selectRoomStartTime:()=>Ac,selectRoomStarted:()=>Tc,selectRoomState:()=>oe,selectScreenAudioTrackByID:()=>zc,selectScreenShareAudioByPeerID:()=>xs,selectScreenShareByPeerID:()=>cd,selectScreenSharesByPeerId:()=>Os,selectScreenVideoTrackByID:()=>Yc,selectScreenshareAudioVolumeByPeerID:()=>md,selectSessionId:()=>Ic,selectSessionMetadata:()=>Dc,selectSessionStore:()=>qc,selectSimulcastLayerByTrack:()=>Sd,selectSpeakers:()=>nn,selectTemplateAppData:()=>wc,selectTrackAudioByID:()=>ed,selectTrackByID:()=>Kt,selectTracksMap:()=>_,selectTranscriptionsState:()=>Pc,selectTranslationState:()=>bc,selectUnreadHMSBroadcastMessagesCount:()=>gc,selectUnreadHMSMessagesCount:()=>Sc,selectVideoPlaylist:()=>ws,selectVideoPlaylistAudioTrackByPeerID:()=>nd,selectVideoPlaylistVideoTrackByPeerID:()=>ad,selectVideoTrackByID:()=>Ns,selectVideoTrackByPeerID:()=>vn,selectWhiteboard:()=>Oc,selectWhiteboards:()=>ln,simulcastMapping:()=>Ue});module.exports=fo(Il);var Ti=(o=>(o.Disconnected="Disconnected",o.Preview="Preview",o.Connecting="Connecting",o.Connected="Connected",o.Reconnecting="Reconnecting",o.Disconnecting="Disconnecting",o.Failed="Failed",o))(Ti||{});var It=()=>({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}),At=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var aa=(e=>(e.CHAT="chat",e))(aa||{});var Wr=(t=>(t.INFO="info",t.ERROR="error",t))(Wr||{}),fi=(D=>(D.PEER_JOINED="PEER_JOINED",D.PEER_LEFT="PEER_LEFT",D.PEER_LIST="PEER_LIST",D.NEW_MESSAGE="NEW_MESSAGE",D.ERROR="ERROR",D.RECONNECTING="RECONNECTING",D.RECONNECTED="RECONNECTED",D.TRACK_ADDED="TRACK_ADDED",D.TRACK_REMOVED="TRACK_REMOVED",D.TRACK_MUTED="TRACK_MUTED",D.TRACK_UNMUTED="TRACK_UNMUTED",D.TRACK_DEGRADED="TRACK_DEGRADED",D.TRACK_RESTORED="TRACK_RESTORED",D.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",D.ROLE_UPDATED="ROLE_UPDATED",D.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",D.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",D.ROOM_ENDED="ROOM_ENDED",D.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",D.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",D.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",D.NAME_UPDATED="NAME_UPDATED",D.METADATA_UPDATED="METADATA_UPDATED",D.POLL_CREATED="POLL_CREATED",D.POLL_STARTED="POLL_STARTED",D.POLL_STOPPED="POLL_STOPPED",D.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",D.POLLS_LIST="POLLS_LIST",D.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",D.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",D.TRACK_INTERRUPTION_START="TRACK_INTERRUPTION_START",D.TRACK_INTERRUPTION_END="TRACK_INTERRUPTION_END",D))(fi||{});var qr=(t=>(t.audio="audio",t.video="video",t))(qr||{});var I=require("reselect");function qe(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];vo(s)&&(i=Rt(s)?s:i,t=Ht(s)?s:t)}return{video:t,audio:i}}function Rt(a){return a&&a.type==="audio"}function Ht(a){return a&&a.type==="video"}function vo(a){return a&&a.source==="screen"}function vi(a){return a&&a.source==="audioplaylist"}function Ct(a){return a&&a.source==="videoplaylist"}function na(a){return a?!!(a!=null&&a.degraded):!1}function it(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function oa(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function Lt(a){var r;let e=!1,t=!1,i=!1;return(r=a==null?void 0:a.publishParams)!=null&&r.allowed&&(e=a.publishParams.allowed.includes("video"),t=a.publishParams.allowed.includes("audio"),i=a.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}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||{}),Mo=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 s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};d.level=Mo?7:0;var rt=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var Sa=require("ua-parser-js");var jr=new Sa.UAParser,wt=null,Jr=null,F=typeof window!="undefined";if(F)try{let a=jr.getResult(),e=a.withClientHints();e&&typeof e.then=="function"?(Jr=e,Jr.then(t=>{wt=t}).catch(()=>{wt=a})):(d.d("UAParser","Client Hints not supported, using standard UA parsing"),wt=e)}catch(a){wt=jr.getResult()}var _e=()=>wt||jr.getResult(),Q={getBrowser:()=>_e().browser,getOS:()=>_e().os,getDevice:()=>_e().device,getCPU:()=>_e().cpu,getEngine:()=>_e().engine,getUA:()=>_e().ua,getResult:_e,withClientHints:()=>Jr||Promise.resolve(_e())},ca,Ke=typeof window=="undefined"&&!((ca=Q.getBrowser().name)!=null&&ca.toLowerCase().includes("electron"));var yo=()=>!Ke,xl=yo(),ga=()=>Q.getDevice().type==="mobile",ko=()=>{var a;return typeof navigator!="undefined"&&navigator.maxTouchPoints>1&&!!((a=Q.getOS().name)!=null&&a.toLowerCase().includes("mac"))},Mi=()=>{let a=Q.getDevice().type;return a==="mobile"||a==="tablet"||ko()},Ta=()=>typeof document!="undefined"&&document.hidden,fa=()=>{var a;return((a=Q.getOS().name)==null?void 0:a.toLowerCase())==="ios"},da,la,va=(la=(da=Q.getBrowser())==null?void 0:da.name)==null?void 0:la.toLowerCase().includes("safari"),ua,pa,Ma=((pa=(ua=Q.getBrowser())==null?void 0:ua.name)==null?void 0:pa.toLowerCase())==="firefox",ha,ma,ya=((ma=(ha=Q.getEngine())==null?void 0:ha.name)==null?void 0:ma.toLowerCase())==="blink";var Ra=require("uuid");var Qr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Qr||{});function Eo(){if(F&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var st=Eo();var Ea=require("uuid");var E={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,NO_DATA:3015},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,PUBLISH_ANSWER_SUPERSEDED:4008},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 k=class a extends Error{constructor(t,i,r,s,n,o=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=n;this.isTerminal=o;Object.setPrototypeOf(this,a.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`{
1
+ "use strict";var lo=Object.create;var bt=Object.defineProperty,uo=Object.defineProperties,po=Object.getOwnPropertyDescriptor,ho=Object.getOwnPropertyDescriptors,mo=Object.getOwnPropertyNames,gi=Object.getOwnPropertySymbols,ta=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty,ia=Object.prototype.propertyIsEnumerable,So=Reflect.get;var ra=Math.pow,ea=(a,e,t)=>e in a?bt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))Gr.call(e,t)&&ea(a,t,e[t]);if(gi)for(var t of gi(e))ia.call(e,t)&&ea(a,t,e[t]);return a},y=(a,e)=>uo(a,ho(e));var $r=(a,e)=>{var t={};for(var i in a)Gr.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&gi)for(var i of gi(a))e.indexOf(i)<0&&ia.call(a,i)&&(t[i]=a[i]);return t};var go=(a,e)=>()=>{try{return e||a((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},To=(a,e)=>{for(var t in e)bt(a,t,{get:e[t],enumerable:!0})},sa=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mo(e))!Gr.call(a,r)&&r!==t&&bt(a,r,{get:()=>e[r],enumerable:!(i=po(e,r))||i.enumerable});return a};var We=(a,e,t)=>(t=a!=null?lo(ta(a)):{},sa(e||!a||!a.__esModule?bt(t,"default",{value:a,enumerable:!0}):t,a)),fo=a=>sa(bt({},"__esModule",{value:!0}),a);var me=(a,e,t)=>So(ta(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=l=>{try{o(t.next(l))}catch(u){r(u)}},n=l=>{try{o(t.throw(l))}catch(u){r(u)}},o=l=>l.done?i(l.value):Promise.resolve(l.value).then(s,n);o((t=t.apply(a,e)).next())});var Zr=go((hu,bo)=>{bo.exports={version:"0.15.2-alpha.3",license:"MIT",repository:{type:"git",url:"https://github.com/100mslive/web-sdks.git",directory:"packages/hms-video-store"},main:"dist/index.cjs.js",module:"dist/index.js",typings:"dist/index.d.ts",files:["dist"],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","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^2.0.6",uuid:"^11.1.1","webrtc-adapter":"^8.0.0",zustand:"3.5.7"},devDependencies:{"@types/dom-screen-wake-lock":"^1.0.1","@types/lodash.isequal":"^4.5.8","@types/sdp-transform":"^2.4.4","@types/ua-parser-js":"^0.7.39","@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:"131a2b6700ed4ef58ad1a2d2591b06c04e39232b"}});var Il={};To(Il,{ConnectivityState:()=>On,DeviceType:()=>ls,Diagnostics:()=>gt,DomainCategory:()=>Qr,EventBus:()=>Tt,HLSPlaylistType:()=>ns,HLSStreamType:()=>os,HMSAudioDeviceCategory:()=>Ci,HMSAudioMode:()=>Hi,HMSAudioPluginType:()=>Ei,HMSLogLevel:()=>Kr,HMSMessageType:()=>aa,HMSNotificationSeverity:()=>Wr,HMSNotificationTypes:()=>fi,HMSPeerType:()=>Ri,HMSPlaylistType:()=>qr,HMSPluginUnsupportedTypes:()=>Pi,HMSReactiveStore:()=>tt,HMSRecordingState:()=>as,HMSRoomState:()=>Ti,HMSStats:()=>kt,HMSTrackExceptionTrackType:()=>zr,HMSTranscriptionMode:()=>ds,HMSTranscriptionState:()=>cs,HMSVideoPluginCanvasContextType:()=>xi,HMSVideoPluginType:()=>Oi,createDefaultStatsStore:()=>At,createDefaultStoreState:()=>It,getAudioDeviceCategory:()=>Li,parsedUserAgent:()=>Q,selectAppData:()=>Wc,selectAppDataByPath:()=>Kc,selectAudioPlaylist:()=>Ls,selectAudioPlaylistTrackByPeerID:()=>od,selectAudioTrackByID:()=>Qc,selectAudioTrackByPeerID:()=>Mn,selectAudioTrackVolume:()=>Bs,selectAudioVolumeByPeerID:()=>hd,selectAuxiliaryAudioByPeerID:()=>sd,selectAuxiliaryTracksByPeerID:()=>Zc,selectAvailableRoleNames:()=>vc,selectBroadcastMessages:()=>Pn,selectBroadcastMessagesUnreadCount:()=>fd,selectCameraStreamByPeerID:()=>Xc,selectConnectionQualities:()=>zo,selectConnectionQualityByPeerID:()=>rd,selectDegradedTracks:()=>hc,selectDevices:()=>Qo,selectDidIJoinWithin:()=>Gd,selectDominantSpeaker:()=>sc,selectEffectsKey:()=>Lc,selectErrors:()=>an,selectFullAppData:()=>Ki,selectHLSState:()=>Ec,selectHMSBroadcastMessages:()=>cn,selectHMSMessages:()=>mt,selectHMSMessagesCount:()=>mc,selectHMSStats:()=>co,selectHandRaisedPeers:()=>Nc,selectHasPeerHandRaised:()=>Id,selectIsAllowedToPreviewMedia:()=>_d,selectIsAllowedToPublish:()=>Dd,selectIsAllowedToSubscribe:()=>Mc,selectIsAudioLocallyMuted:()=>Us,selectIsConnectedToRoom:()=>Ce,selectIsEffectsEnabled:()=>Hc,selectIsInPreview:()=>bs,selectIsLargeRoom:()=>Rc,selectIsLocalAudioEnabled:()=>ac,selectIsLocalAudioInterrupted:()=>nc,selectIsLocalAudioPluginPresent:()=>Bd,selectIsLocalScreenShared:()=>Ji,selectIsLocalVideoDisplayEnabled:()=>Ps,selectIsLocalVideoEnabled:()=>ji,selectIsLocalVideoInterrupted:()=>oc,selectIsLocalVideoPluginPresent:()=>Ud,selectIsLocallyMutedByPeerID:()=>ud,selectIsPeerAudioEnabled:()=>dd,selectIsPeerVideoEnabled:()=>ld,selectIsRoleAllowedToPublish:()=>Nd,selectIsScreenShareLocallyMutedByPeerID:()=>pd,selectIsSomeoneScreenSharing:()=>cc,selectIsTranscriptionAllowedByMode:()=>Hd,selectIsTranscriptionEnabled:()=>fc,selectIsVBEnabled:()=>Cc,selectLocalAudioTrackID:()=>ue,selectLocalMediaSettings:()=>ks,selectLocalPeer:()=>X,selectLocalPeerID:()=>Ie,selectLocalPeerName:()=>ec,selectLocalPeerRole:()=>Ye,selectLocalPeerRoleName:()=>tc,selectLocalTrackIDs:()=>Es,selectLocalVideoTrackID:()=>ie,selectMessageByMessageID:()=>Rd,selectMessageIDsInOrder:()=>ys,selectMessagesByPeerID:()=>vd,selectMessagesByRole:()=>Md,selectMessagesMap:()=>$t,selectMessagesUnreadCountByPeerID:()=>kd,selectMessagesUnreadCountByRole:()=>yd,selectPeerAudioByID:()=>id,selectPeerByCondition:()=>Vd,selectPeerByID:()=>se,selectPeerCount:()=>Yo,selectPeerMetadata:()=>bd,selectPeerName:()=>Ad,selectPeerNameByID:()=>jc,selectPeerScreenSharing:()=>on,selectPeerSharingAudio:()=>dc,selectPeerSharingAudioPlaylist:()=>pc,selectPeerSharingVideoPlaylist:()=>uc,selectPeerTypeByID:()=>Jc,selectPeers:()=>Me,selectPeersByCondition:()=>Fd,selectPeersByRole:()=>Ed,selectPeersByRoles:()=>Pd,selectPeersMap:()=>Y,selectPeersScreenSharing:()=>lc,selectPeersWithAudioStatus:()=>Cd,selectPermissions:()=>As,selectPollByID:()=>Vs,selectPolls:()=>_c,selectPollsMap:()=>Rs,selectPreviewRole:()=>Is,selectPreviewRoleName:()=>dn,selectRTMPState:()=>kc,selectRecentError:()=>jo,selectRecordingState:()=>yc,selectRemotePeers:()=>rc,selectRoleByRoleName:()=>bn,selectRoleChangeRequest:()=>wd,selectRolesMap:()=>ye,selectRoom:()=>V,selectRoomID:()=>Jo,selectRoomStartTime:()=>Ac,selectRoomStarted:()=>Tc,selectRoomState:()=>oe,selectScreenAudioTrackByID:()=>zc,selectScreenShareAudioByPeerID:()=>xs,selectScreenShareByPeerID:()=>cd,selectScreenSharesByPeerId:()=>Os,selectScreenVideoTrackByID:()=>Yc,selectScreenshareAudioVolumeByPeerID:()=>md,selectSessionId:()=>Ic,selectSessionMetadata:()=>Dc,selectSessionStore:()=>qc,selectSimulcastLayerByTrack:()=>Sd,selectSpeakers:()=>nn,selectTemplateAppData:()=>wc,selectTrackAudioByID:()=>ed,selectTrackByID:()=>Kt,selectTracksMap:()=>_,selectTranscriptionsState:()=>Pc,selectTranslationState:()=>bc,selectUnreadHMSBroadcastMessagesCount:()=>gc,selectUnreadHMSMessagesCount:()=>Sc,selectVideoPlaylist:()=>ws,selectVideoPlaylistAudioTrackByPeerID:()=>nd,selectVideoPlaylistVideoTrackByPeerID:()=>ad,selectVideoTrackByID:()=>Ns,selectVideoTrackByPeerID:()=>vn,selectWhiteboard:()=>Oc,selectWhiteboards:()=>ln,simulcastMapping:()=>Ue});module.exports=fo(Il);var Ti=(o=>(o.Disconnected="Disconnected",o.Preview="Preview",o.Connecting="Connecting",o.Connected="Connected",o.Reconnecting="Reconnecting",o.Disconnecting="Disconnecting",o.Failed="Failed",o))(Ti||{});var It=()=>({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}),At=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var aa=(e=>(e.CHAT="chat",e))(aa||{});var Wr=(t=>(t.INFO="info",t.ERROR="error",t))(Wr||{}),fi=(D=>(D.PEER_JOINED="PEER_JOINED",D.PEER_LEFT="PEER_LEFT",D.PEER_LIST="PEER_LIST",D.NEW_MESSAGE="NEW_MESSAGE",D.ERROR="ERROR",D.RECONNECTING="RECONNECTING",D.RECONNECTED="RECONNECTED",D.TRACK_ADDED="TRACK_ADDED",D.TRACK_REMOVED="TRACK_REMOVED",D.TRACK_MUTED="TRACK_MUTED",D.TRACK_UNMUTED="TRACK_UNMUTED",D.TRACK_DEGRADED="TRACK_DEGRADED",D.TRACK_RESTORED="TRACK_RESTORED",D.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",D.ROLE_UPDATED="ROLE_UPDATED",D.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",D.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",D.ROOM_ENDED="ROOM_ENDED",D.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",D.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",D.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",D.NAME_UPDATED="NAME_UPDATED",D.METADATA_UPDATED="METADATA_UPDATED",D.POLL_CREATED="POLL_CREATED",D.POLL_STARTED="POLL_STARTED",D.POLL_STOPPED="POLL_STOPPED",D.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",D.POLLS_LIST="POLLS_LIST",D.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",D.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",D.TRACK_INTERRUPTION_START="TRACK_INTERRUPTION_START",D.TRACK_INTERRUPTION_END="TRACK_INTERRUPTION_END",D))(fi||{});var qr=(t=>(t.audio="audio",t.video="video",t))(qr||{});var I=require("reselect");function qe(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];vo(s)&&(i=Rt(s)?s:i,t=Ht(s)?s:t)}return{video:t,audio:i}}function Rt(a){return a&&a.type==="audio"}function Ht(a){return a&&a.type==="video"}function vo(a){return a&&a.source==="screen"}function vi(a){return a&&a.source==="audioplaylist"}function Ct(a){return a&&a.source==="videoplaylist"}function na(a){return a?!!(a!=null&&a.degraded):!1}function it(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function oa(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function Lt(a){var r;let e=!1,t=!1,i=!1;return(r=a==null?void 0:a.publishParams)!=null&&r.allowed&&(e=a.publishParams.allowed.includes("video"),t=a.publishParams.allowed.includes("audio"),i=a.publishParams.allowed.includes("screen")),{video:e,audio:t,screen:i}}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||{}),Mo=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 s=performance.measure(r,r);this.log(1,t,r,s==null?void 0:s.duration),performance.clearMarks(r),performance.clearMeasures(r)}catch(s){this.log(1,t,r,s)}break}}}};d.level=Mo?7:0;var rt=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};var Sa=require("ua-parser-js");var jr=new Sa.UAParser,wt=null,Jr=null,F=typeof window!="undefined";if(F)try{let a=jr.getResult(),e=a.withClientHints();e&&typeof e.then=="function"?(Jr=e,Jr.then(t=>{wt=t}).catch(()=>{wt=a})):(d.d("UAParser","Client Hints not supported, using standard UA parsing"),wt=e)}catch(a){wt=jr.getResult()}var _e=()=>wt||jr.getResult(),Q={getBrowser:()=>_e().browser,getOS:()=>_e().os,getDevice:()=>_e().device,getCPU:()=>_e().cpu,getEngine:()=>_e().engine,getUA:()=>_e().ua,getResult:_e,withClientHints:()=>Jr||Promise.resolve(_e())},ca,Ke=typeof window=="undefined"&&!((ca=Q.getBrowser().name)!=null&&ca.toLowerCase().includes("electron"));var yo=()=>!Ke,xl=yo(),ga=()=>Q.getDevice().type==="mobile",ko=()=>{var a;return typeof navigator!="undefined"&&navigator.maxTouchPoints>1&&!!((a=Q.getOS().name)!=null&&a.toLowerCase().includes("mac"))},Mi=()=>{let a=Q.getDevice().type;return a==="mobile"||a==="tablet"||ko()},Ta=()=>typeof document!="undefined"&&document.hidden,fa=()=>{var a;return((a=Q.getOS().name)==null?void 0:a.toLowerCase())==="ios"},da,la,va=(la=(da=Q.getBrowser())==null?void 0:da.name)==null?void 0:la.toLowerCase().includes("safari"),ua,pa,Ma=((pa=(ua=Q.getBrowser())==null?void 0:ua.name)==null?void 0:pa.toLowerCase())==="firefox",ha,ma,ya=((ma=(ha=Q.getEngine())==null?void 0:ha.name)==null?void 0:ma.toLowerCase())==="blink";var Ra=require("uuid");var Qr=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Qr||{});function Eo(){if(F&&window){let a=window.location.hostname;return a==="localhost"||a==="127.0.0.1"?"LOCAL":a.includes("app.100ms.live")?"HMS":"CUSTOM"}return"CUSTOM"}var st=Eo();var Ea=require("uuid");var E={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,NO_DATA:3015},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,PUBLISH_ANSWER_SUPERSEDED:4008},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 k=class a extends Error{constructor(t,i,r,s,n,o=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=n;this.isTerminal=o;Object.setPrototypeOf(this,a.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`{
2
2
  code: ${this.code};
3
3
  name: ${this.name};
4
4
  action: ${this.action};
@@ -100,7 +100,7 @@
100
100
  requested: ${e};
101
101
  applied: ${t==null?void 0:t.label};
102
102
  appliedId: ${t==null?void 0:t.deviceId};
103
- }`),t)try{yield this.unblockAutoplay()}catch(i){d.w("[AudioOutputManager]","unblockAutoplay failed after setDevice",i)}return t})}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield ne.resumeContext()})}};var ii=class{static handleError(e){if(e.status===404)throw S.APIErrors.EndpointUnreachable("FEEDBACK",e.statusText);if(e.status>=400)throw S.APIErrors.ServerErrors(e.status,"FEEDBACK",e==null?void 0:e.statusText)}static sendFeedback(s){return c(this,arguments,function*({token:e,eventEndpoint:t="https://event.100ms.live",info:i,feedback:r}){d.d(this.TAG,`sendFeedback: feedbackEndpoint=${t} peerId=${i.peer.peer_id} session=${i.peer.session_id} `);let n=new URL("v2/client/feedback",t),o=y(m({},i),{payload:r});try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`},body:JSON.stringify(o),method:"POST"});try{this.handleError(l);return}catch(u){throw d.e(this.TAG,"error",u.message,l.status),u instanceof k?u:S.APIErrors.ServerErrors(l.status,"FEEDBACK",u.message)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?S.APIErrors.EndpointUnreachable("FEEDBACK",u.message):u}})}};ii.TAG="[FeedbackService]";var Fn=require("eventemitter2");var U=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 Tt=class{constructor(){this.eventEmitter=new Fn.EventEmitter2;this.analytics=new U(G.ANALYTICS,this.eventEmitter);this.deviceChange=new U(G.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new U(G.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new U(G.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.localVideoUnmutedNatively=new U(G.LOCAL_VIDEO_UNMUTED_NATIVELY,this.eventEmitter);this.localAudioUnmutedNatively=new U(G.LOCAL_AUDIO_UNMUTED_NATIVELY,this.eventEmitter);this.statsUpdate=new U(G.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new U(G.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new U(G.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new U(G.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new U(G.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new U(G.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.trackInterruption=new U(G.TRACK_INTERRUPTION,this.eventEmitter);this.policyChange=new U(G.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new U(G.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new U(G.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new U(G.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new U(G.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new U(G.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new U(G.LEAVE,this.eventEmitter);this.error=new U(G.ERROR,this.eventEmitter)}};var hr=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var s,n,o;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)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(n=this.listener)==null||n.onPeerUpdate(4,l)}else(o=this.listener)==null||o.onPeerUpdate(5,null)}};var mr=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 Sr=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(s=>{let n=this.store.getPeerById(s.peer_id);return n&&n.updateNetworkQuality(s.downlink_score),{peerID:s.peer_id,downlinkQuality:s.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var ft=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 permanently",e),Object.keys(e.tracks).forEach(i=>{var o;let r=this.store.getTrackState(i);if(!r)return;let s=this.store.getTrackById(i);if(!s){d.d(this.TAG,"Track not found in store");return}s.type==="audio"&&this.eventBus.audioTrackRemoved.publish(s),this.store.removeTrack(s);let n=this.store.getPeerById(r.peerId);n&&(this.removePeerTracks(n,s),(o=this.listener)==null||o.onTrackUpdate(1,s,n))})};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 x&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var s,n;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=be(r,this.store),this.store.addPeer(i));for(let o in e.tracks){let l=Object.assign({},(s=this.store.getTrackState(o))==null?void 0:s.trackInfo),u=e.tracks[o],p=this.store.getTrackById(o);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:m(m({},l),u)}),!p||this.tracksToProcess.has(o))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{this.logIfRejected(p.setEnabled(!u.mute),p);let h=this.processTrackUpdate(p,l,u);h&&((n=this.listener)==null||n.onTrackUpdate(h,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var s;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,this.logIfRejected(t.setEnabled(!i.trackInfo.mute),t),this.addAudioTrack(r,t),this.addVideoTrack(r,t),t.type==="audio"?this.eventBus.audioTrackAdded.publish({track:t,peer:r}):(s=this.listener)==null||s.onTrackUpdate(0,t,r),this.tracksToProcess.delete(t.trackId)})}}logIfRejected(e,t){e.catch(i=>d.e(this.TAG,"could not apply mute state",`${t}`,i))}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 s;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 n=this.store.getPeerById(i.peerId);if(!n)return;this.removePeerTracks(n,e),(s=this.listener)==null||s.onTrackUpdate(1,e,n),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var s,n;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(s=this.listener)==null||s.onTrackUpdate(5,e,i):(n=this.listener)==null||n.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 s=e.auxiliaryTracks.findIndex(n=>n.trackId===i.trackId);s===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[s].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[s]))}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 gr=class extends ft{constructor(t,i,r,s){super(t,i,s);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u,p;if(t.type!=="video")return;let s=this.store.getPeerById(i);if(!s||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let n=new Re(new MediaStream,this.transport.getSubscribeConnection()),o=Te.getEmptyVideoTrack();o.enabled=!t.mute;let l=new x(n,o,t.source,(u=this.store.getRoom())==null?void 0:u.disableNoneLayerRequest);l.setTrackId(t.track_id),l.peerId=s.peerId,l.logIdentifier=s.name,this.addVideoTrack(s,l),r&&((p=this.listener)==null||p.onTrackUpdate(0,s.videoTrack,s))}}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&&ve(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,n,o,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(n=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:n.subscribeToRoles)==null?void 0:l.includes((o=r.role)==null?void 0:o.name))}};var Tr=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(n=>!e[n.peerId]);r.length>0&&d.d(this.TAG,`${r}`),r.forEach(n=>{var l;let o={peer_id:n.peerId,role:((l=n.role)==null?void 0:l.name)||"",info:{name:n.name,data:n.metadata||"",user_id:n.customerUserId||"",type:n.type},tracks:{},groups:[],realtime:n.realtime};this.peerManager.handlePeerLeave(o)});let s=[];i.forEach(n=>{let o=this.store.getPeerById(n.peer_id),l=Object.values(n.tracks);o&&(this.store.getPeerTracks(o.peerId).forEach(p=>{var h;n.tracks[p.trackId]||(this.removePeerTrack(o,p.trackId),(h=this.listener)==null||h.onTrackUpdate(1,p,o))}),l.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:o.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:n,tracks:n.tracks},!1),this.peerManager.handlePeerUpdate(n)),s.push(n)}),s.length>0&&this.peerManager.handlePeerList(s)}}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 s=e.auxiliaryTracks.findIndex(n=>n.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var fr=class{constructor(e,t,i){this.store=e;this.trackManager=t;this.listener=i;this.TAG="[PeerManager]";this.handlePeerList=e=>{var r,s;if(e.length===0){(r=this.listener)==null||r.onPeerUpdate(9,[]);return}let t=[],i=new Set(e.map(n=>n.peer_id));this.store.getRemotePeers().forEach(({peerId:n,fromRoomState:o})=>{!i.has(n)&&o&&this.store.removePeer(n)});for(let n of e)t.push(this.makePeer(n));(s=this.listener)==null||s.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,s,n;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)),(s=t.auxiliaryTracks)==null||s.forEach(o=>{var l;(l=this.listener)==null||l.onTrackUpdate(1,o,t)}),(n=this.listener)==null||n.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 s,n,o,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(s=this.listener)==null||s.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(n=this.listener)==null||n.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),(o=this.listener)==null||o.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(He);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(m({peer:t},e.info))}handlePeerInfoUpdate({peer:e,name:t,data:i}){var r,s;e&&(t&&e.name!==t&&(e.updateName(t),(r=this.listener)==null||r.onPeerUpdate(10,e)),i&&e.metadata!==i&&(e.updateMetadata(i),(s=this.listener)==null||s.onPeerUpdate(11,e)))}makePeer(e){let t=this.store.getPeerById(e.peer_id);t||(t=be(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 vr=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),s=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:s,newRole:r})}}};var Ks=(f=>(f.FLAG_SERVER_SUB_DEGRADATION="subscribeDegradation",f.FLAG_SERVER_SIMULCAST="simulcast",f.FLAG_NON_WEBRTC_DISABLE_OFFER="nonWebRTCDisableOffer",f.FLAG_PUBLISH_STATS="publishStats",f.FLAG_SUBSCRIBE_STATS="subscribeStats",f.FLAG_ON_DEMAND_TRACKS="onDemandTracks",f.FLAG_DISABLE_VIDEO_TRACK_AUTO_UNSUBSCRIBE="disableVideoTrackAutoUnsubscribe",f.FLAG_WHITEBOARD_ENABLED="whiteboardEnabled",f.FLAG_EFFECTS_SDK_ENABLED="effectsSDKEnabled",f.FLAG_VB_ENABLED="vb",f.FLAG_HIPAA_ENABLED="hipaa",f.FLAG_NOISE_CANCELLATION="noiseCancellation",f.FLAG_SCALE_SCREENSHARE_BASED_ON_PIXELS="scaleScreenshareBasedOnPixels",f.FLAG_DISABLE_NONE_LAYER_REQUEST="disableNoneLayerRequest",f))(Ks||{});var ri=(a,e,t)=>{let i=t==="qa"?_a:Da,r=new URL(i);return r.searchParams.set("endpoint",`https://${e}`),r.searchParams.set("token",a),r.toString()};var Mr=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 n;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}),s=y(m({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,url:ri(r.token,r.addr,this.store.getEnv()),token:r.token,addr:r.addr,owner:r.owner,permissions:r.permissions||[],open:!0});this.store.setWhiteboard(s),(n=this.listener)==null||n.onWhiteboardUpdate(s)})}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}handleLocalRoleUpdate(){return c(this,null,function*(){var t,i,r;let e=this.store.getWhiteboards();for(let s of e.values())if(s.url){let n=yield this.transport.signal.getWhiteboard({id:s.id}),o=this.store.getLocalPeer(),u=(o==null?void 0:o.customerUserId)===n.owner?(i=(t=o.role)==null?void 0:t.permissions.whiteboard)==null?void 0:i.includes("admin"):n.permissions.length>0,p=y(m({},s),{id:n.id,url:ri(n.token,n.addr,this.store.getEnv()),token:n.token,addr:n.addr,owner:n.owner,permissions:n.permissions,open:u});this.store.setWhiteboard(p),(r=this.listener)==null||r.onWhiteboardUpdate(p)}})}getCreateOptionsWithDefaults(e){var n;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(o=>{var l,u,p;(l=o.permissions.whiteboard)!=null&&l.includes("read")&&i.push(o.name),(u=o.permissions.whiteboard)!=null&&u.includes("write")&&r.push(o.name),(p=o.permissions.whiteboard)!=null&&p.includes("admin")&&s.push(o.name)}),{title:(e==null?void 0:e.title)||`${(n=this.store.getRoom())==null?void 0:n.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)||s}}};var si=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Mr(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var n,o;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(y(m({},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}),s=yr(y(m({},e),{poll_id:e.id,state:"created",created_by:(n=this.store.getLocalPeer())==null?void 0:n.peerId}));s.questions=r.questions.map(({question:l,options:u,answer:p})=>y(m({},l),{options:u,answer:p})),(o=this.listener)==null||o.onPollsUpdate(0,[s])})}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(s=>{var o,l;let n=this.getQuestionInPoll(i,s.questionIndex);return n.type==="single-choice"?(s.option=s.option||((o=s.options)==null?void 0:o[0])||-1,delete s.text,delete s.options):n.type==="multiple-choice"?((l=s.options)==null||l.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),m({duration:0,type:n.type,question:s.questionIndex},s)});yield this.transport.signal.setPollResponses({poll_id:e,responses:r})})}fetchLeaderboard(e,t,i){return c(this,null,function*(){var p,h;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=(h=(p=this.store.getLocalPeer())==null?void 0:p.role)==null?void 0:h.permissions,n=!!(s!=null&&s.pollRead||s!=null&&s.pollWrite);if(r.anonymous||r.state!=="stopped"||!n)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),l={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctUsers:o.correct_users};return{entries:o.questions.map(T=>({position:T.position,totalResponses:T.total_responses,correctResponses:T.correct_responses,duration:T.duration,peer:T.peer,score:T.score})),hasNext:!o.last,summary:l}})}getPollResponses(e,t){return c(this,null,function*(){var s,n;let i=yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t}),r=JSON.parse(JSON.stringify(e));(s=i.responses)==null||s.forEach(({response:o,peer:l,final:u})=>{var h,T;let p=(h=e==null?void 0:e.questions)==null?void 0:h.find(g=>g.index===o.question);if(p){let g={id:o.response_id,questionIndex:o.question,option:o.option,options:o.options,text:o.text,responseFinal:u,peer:{peerid:l.peerid,userHash:l.hash,userid:l.userid,username:l.username},skipped:o.skipped,type:o.type,update:o.update},f=p.responses&&!t?[...p.responses]:[];(T=r.questions)!=null&&T[o.question-1]&&(r.questions[o.question-1].responses=[...f,g])}}),this.store.setPoll(r),(n=this.listener)==null||n.onPollsUpdate(4,[r])})}getPolls(){return c(this,null,function*(){var s,n,o;let e=yield this.transport.signal.getPollsList({count:50,state:"started"}),t=[],i=(n=(s=this.store.getLocalPeer())==null?void 0:s.role)==null?void 0:n.permissions.pollWrite,r=[...e.polls];if(i){let l=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...l.polls,...r,...u.polls]}for(let l of r){let u=yield this.transport.signal.getPollQuestions({poll_id:l.poll_id,index:0,count:50}),p=yr(l),h=this.store.getPoll(l.poll_id);p.questions=u.questions.map(({question:T,options:g,answer:f},P)=>{var M,R;return y(m({},T),{options:g,answer:f,responses:(R=(M=h==null?void 0:h.questions)==null?void 0:M[P])==null?void 0:R.responses})}),t.push(p),this.store.setPoll(p)}return(o=this.listener)==null||o.onPollsUpdate(3,t),t})}createQuestionSetParams(e,t){var n,o;if(e.index){let l=(n=e.options)==null?void 0:n.map((u,p)=>y(m({},u),{index:p+1}));return{question:y(m({},e),{index:t+1}),options:l,answer:e.answer}}let i=y(m({},e),{index:t+1}),r,s=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((l,u)=>({index:u+1,text:l.text,weight:l.weight})),e.type==="single-choice"?s.option=e.options.findIndex(l=>l.isCorrectAnswer)+1||void 0:s.options=e.options.map((l,u)=>l.isCorrectAnswer?u+1:void 0).filter(l=>!!l)):(s==null||delete s.options,s==null||delete s.option),{question:i,options:r,answer:s}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(s=>s.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},yr=a=>{let e={userid:"customerID",peerid:"peerID",username:"userName"};return{id:a.poll_id,title:a.title,startedBy:a.started_by,createdBy:a.created_by,anonymous:a.anonymous,type:a.type,duration:a.duration,locked:a.locked,mode:a.mode?e[a.mode]:void 0,visibility:a.visibility,rolesThatCanVote:a.vote||[],rolesThatCanViewResponses:a.responses||[],state:a.state,stoppedBy:a.stopped_by,startedAt:L(a.started_at),stoppedAt:L(a.stopped_at),createdAt:L(a.created_at)}};var kr=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,r;let t=[];for(let s of e.polls){let n=this.store.getPoll(s.poll_id);if(n&&n.state==="started"){(i=this.listener)==null||i.onPollsUpdate(1,[n]);return}let o=yield this.transport.signal.getPollQuestions({poll_id:s.poll_id,index:0,count:50}),l=yr(s);l.questions=o.questions.map(({question:u,options:p,answer:h})=>y(m({},u),{options:p,answer:h})),yield this.updatePollResponses(l,!0),t.push(l),this.store.setPoll(l)}(r=this.listener)==null||r.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(s){s.state="stopped",s.stoppedAt=L(r.stopped_at),s.stoppedBy=r.stopped_by;let n=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(s,n),t.push(s)}}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 s=this.store.getPoll(r.poll_id);if(!s)return;this.updatePollResult(s,r),t.push(s)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(4,t))})}updatePollResult(e,t){var i;e.result=m({},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 n,o;let s=(n=e.questions)==null?void 0:n.find(l=>l.index===r.question);s&&(s.result=m({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(o=r.options)==null||o.forEach((l,u)=>{var h;let p=(h=s.options)==null?void 0:h[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:s,peer:n,final:o})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(h=>h.index===s.question);if(!l)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal:o,peer:{peerid:n.peerid,userHash:n.hash,userid:n.userid,username:n.username},skipped:s.skipped,type:s.type,update:s.update};Array.isArray(l.responses)&&l.responses.length>0?l.responses.find(({id:h})=>h===u.id)||l.responses.push(u):l.responses=[u]})})}};var Er=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,s=t?this.store.getPeerById(t):void 0,n=this.store.getLocalPeerTracks().find(l=>l.publishedTrackId===i);if(!n)return;let o=()=>{var l;(l=this.listener)==null||l.onChangeTrackStateRequest({requestedBy:s,track:n,enabled:!r})};if(r){if(n.enabled===!r)return;n.setEnabled(!r).then(o)}else o()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:s}=e,n=s?this.store.getPeerById(s):void 0,o=!r,l=this.getTracksToBeUpdated({type:t,source:i,enabled:o});if(l.length!==0)if(o)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let h of l)p.push(h.setEnabled(!1));Promise.all(p).then(()=>{var h;(h=this.listener)==null||h.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let s=this.store.getLocalPeerTracks();return e&&(s=s.filter(n=>n.type===e)),t&&(s=s.filter(n=>n.source===t)),s.filter(n=>n.enabled!==i)}};var Pr=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;case"on-transcription-update":this.handleTranscriptionStatus([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 u,p,h,T;let{recording:t,streaming:i,transcriptions:r,session_id:s,started_at:n,name:o}=e,l=this.store.getRoom();if(!l){d.w(this.TAG,"on room state - room not present");return}l.name=o,l.rtmp.running=this.isStreamingRunning((u=i==null?void 0:i.rtmp)==null?void 0:u.state),l.rtmp.startedAt=L((p=i==null?void 0:i.rtmp)==null?void 0:p.started_at),l.rtmp.state=(h=i==null?void 0:i.rtmp)==null?void 0:h.state,l.recording.server=this.getPeerListSFURecording(t),l.recording.browser=this.getPeerListBrowserRecording(t),l.recording.hls=this.getPeerListHLSRecording(t),l.hls=this.convertHls(i==null?void 0:i.hls),l.transcriptions=this.addTranscriptionDetail(r),l.sessionId=s,l.startedAt=L(n),(T=this.listener)==null||T.onRoomUpdate("RECORDING_STATE_UPDATED",l)}addTranscriptionDetail(e){return e?e.map(t=>({state:t.state,mode:t.mode,initialised_at:L(t.initialised_at),started_at:L(t.started_at),stopped_at:L(t.stopped_at),updated_at:L(t.updated_at),error:this.toSdkError(t==null?void 0:t.error),translation:t.translation})):[]}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,s)=>{var n,o,l;r.state!=="initialised"?i.variants.push({meetingURL:r==null?void 0:r.meetingURL,url:r==null?void 0:r.url,metadata:r==null?void 0:r.metadata,playlist_type:r==null?void 0:r.playlist_type,startedAt:L((n=e==null?void 0:e.variants)==null?void 0:n[s].started_at),initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[s].initialised_at),state:r.state,stream_type:r==null?void 0:r.stream_type}):i.variants.push({initialisedAt:L((l=e==null?void 0:e.variants)==null?void 0:l[s].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?e.variants.some(s=>this.isStreamingRunning(s.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)}handleTranscriptionStatus(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on transcription - room not present");return}t.transcriptions=this.addTranscriptionDetail(e)||[],(i=this.listener)==null||i.onRoomUpdate("TRANSCRIPTION_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants.some(s=>s.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(s=>{i.variants.push({meetingURL:s==null?void 0:s.meeting_url,url:s==null?void 0:s.url,metadata:s==null?void 0:s.metadata,playlist_type:s==null?void 0:s.playlist_type,startedAt:L(s==null?void 0:s.started_at),initialisedAt:L(s==null?void 0:s.initialised_at),state:s.state,stream_type:s==null?void 0:s.stream_type})}),i}getHLSRecording(e){var r,s;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:!!((s=e==null?void 0:e.hls_recording)!=null&&s.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,s;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:(s=t==null?void 0:t.config)==null?void 0:s.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 s;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"),(s=this.listener)==null||s.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,s;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)},(s=this.listener)==null||s.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new k(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var br=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 Ir=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){e==="on-whiteboard-update"&&this.handleWhiteboardUpdate(t)}handleWhiteboardUpdate(e){return c(this,null,function*(){var o;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),s=e.state==="open",n={id:e.id,title:e.title,attributes:e.attributes};if(n.open=r?i==null?void 0:i.open:s,n.owner=n.open?e.owner:void 0,n.open)if(r)n.url=i==null?void 0:i.url,n.token=i==null?void 0:i.token,n.addr=i==null?void 0:i.addr,n.permissions=i==null?void 0:i.permissions;else{let l=yield this.transport.signal.getWhiteboard({id:e.id});n.url=ri(l.token,l.addr,this.store.getEnv()),n.token=l.token,n.addr=l.addr,n.permissions=l.permissions,n.open=l.permissions.length>0}this.store.setWhiteboard(n),(o=this.listener)==null||o.onWhiteboardUpdate(n)})}};var Ar=class{constructor(e,t,i,r,s,n){this.store=e;this.transport=i;this.listener=r;this.audioListener=s;this.connectionQualityListener=n;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 o=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=o?new gr(this.store,t,this.transport,this.listener):new ft(this.store,t,this.listener),this.peerManager=new fr(this.store,this.trackManager,this.listener),this.peerListManager=new Tr(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new mr(this.listener),this.policyChangeManager=new vr(this.store,t),this.requestManager=new Er(this.store,this.listener),this.activeSpeakerManager=new hr(this.store,this.listener,this.audioListener),this.connectionQualityManager=new Sr(this.store,this.connectionQualityListener),this.roomUpdateManager=new Pr(this.store,this.listener),this.sessionMetadataManager=new br(this.store,this.listener),this.pollsManager=new kr(this.store,this.transport,this.listener),this.whiteboardManager=new Ir(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 s,n;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"&&(s=window.HMS)!=null&&s.ON_SFU_STATS&&typeof((n=window.HMS)==null?void 0:n.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;case"node-info":this.transport.setSFUNodeId(t.sfu_node_id);break;default:break}}};var Rr=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}),s=L(r);return{value:i,updatedAt:s}})}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 Hr=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",n=!1,o){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=n;this.iceServers=o}};var Z=(s=>(s[s.ConnectFailed=0]="ConnectFailed",s[s.SignalDisconnect=1]="SignalDisconnect",s[s.JoinWSMessageFailed=2]="JoinWSMessageFailed",s[s.PublishIceConnectionFailed=3]="PublishIceConnectionFailed",s[s.SubscribeIceConnectionFailed=4]="SubscribeIceConnectionFailed",s))(Z||{}),Gn={0:[],1:[],2:[1],3:[1],4:[1]};var ai=(o=>(o.Disconnected="Disconnected",o.Connecting="Connecting",o.Joined="Joined",o.Preview="Preview",o.Failed="Failed",o.Reconnecting="Reconnecting",o.Leaving="Leaving",o))(ai||{});var Cr=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Lr=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(o){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxRetryTime:s=6e4,changeState:n=!0}){yield this.scheduleTask({category:e,error:t,changeState:n,task:i,originalState:r,maxRetryTime:s,failedAt:Date.now()})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(u){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:s,failedAt:n,maxRetryTime:o=6e4,failedRetryCount:l=0}){if(d.d(this.TAG,"schedule: ",{category:Z[e],error:t}),l===0){let M=this.inProgress.get(e);if(M){d.d(this.TAG,`schedule: Already a task for ${Z[e]} scheduled, waiting for its completion`),yield M.promise;return}let R=new Cr(($,ce)=>{});this.inProgress.set(e,R),this.sendEvent(t,e)}let p=!1,h=Gn[e];for(let M in h){let R=h[parseInt(M)];try{let $=this.inProgress.get(R);$&&(d.d(this.TAG,`schedule: Suspending retry task of ${Z[e]}, waiting for ${Z[R]} to recover`),yield $.promise,d.d(this.TAG,`schedule: Resuming retry task ${Z[e]} as it's dependency ${Z[R]} is recovered`))}catch($){d.d(this.TAG,`schedule: Stopping retry task of ${Z[e]} as it's dependency ${Z[R]} failed to recover`),p=!0;break}}let T=M=>{if(this.inProgress.delete(e),this.sendEvent(M,e),this.reset(),i)this.onStateChange("Failed",M);else throw M},g=Date.now()-n;if(g>=o||p)return t.description+=`. [${Z[e]}] Could not recover after ${g} milliseconds`,p&&(t.description+=` Could not recover all of it's required dependencies - [${h.map(M=>Z[M]).toString()}]`),t.isTerminal=!0,T(t);i&&this.onStateChange("Reconnecting",t);let f=this.getDelayForRetryCount(e,l);d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Scheduling retry task in ${f}ms`);let P;try{P=yield this.setTimeoutPromise(r,f)}catch(M){P=!1;let R=M;if(R.isTerminal)return d.e(this.TAG,`[${Z[e]}] Un-caught terminal exception ${R.name} in retry-task`,M),T(R);d.w(this.TAG,`[${Z[e]}] Un-caught exception ${R.name} in retry-task, initiating retry`,M)}if(P){let M=this.inProgress.get(e);this.inProgress.delete(e),M==null||M.resolve(l),i&&this.inProgress.size===0&&this.onStateChange(s),d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Recovered \u267B\uFE0F after ${g}ms`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxRetryTime:o,failedAt:n,failedRetryCount:l+1})})}getDelayForRetryCount(e,t=0){let i=e===2?Math.random()*2:Math.random(),r=0;return e===2?r=2+i:e===1?r=1:e===3&&t>0&&(r=Math.min(ra(2,t-1),4)+i),r*1e3}setTimeoutPromise(e,t){return c(this,null,function*(){return new Promise((i,r)=>{let s=window.setTimeout(()=>c(this,null,function*(){try{let n=yield e();n&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(s),1),i(n)}catch(n){r(n)}}),t);this.retryTaskIds.push(s)})})}};var wr=class extends Ve{constructor(){super(100);this.localStorage=new Ee("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 H(i);super.enqueue(r)})}};var Dr=class{constructor(){this.TAG="[AnalyticsTransport]";this.eventCount=0;this.lastResetTime=Date.now();this.MAX_EVENTS_PER_MINUTE=200;this.RESET_INTERVAL_MS=6e4}checkRateLimit(){let e=Date.now();if(e-this.lastResetTime>=this.RESET_INTERVAL_MS&&(this.eventCount=0,this.lastResetTime=e),this.eventCount>=this.MAX_EVENTS_PER_MINUTE)throw new Error("Too many events being sent, please check the implementation.");this.eventCount++}sendEvent(e){try{this.checkRateLimit()}catch(t){throw d.w(this.TAG,"Rate limit exceeded",t),t}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):Le.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 _r=class extends Dr{constructor(t){super();this.transportProvider=t;this.failedEvents=new wr}};var vt=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.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>d.e("[StatsAnalytics]",e.message)))}stop(){this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield te(this.pushInterval*1e3),this.sendEvent()})}sendEvent(){this.trackAnalytics.forEach(e=>{e.clearSamples()})}cleanTrackAnalyticsAndCreateSample(e){this.trackAnalytics.forEach(t=>{!this.store.hasTrack(t.track)&&!(t.samples.length>0)&&this.trackAnalytics.delete(t.track_id)}),e&&this.trackAnalytics.forEach(t=>{t.createSample()})}},Mt=class{constructor({track:e,ssrc:t,rid:i,kind:r,sampleWindowSize:s}){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=s}pushTempStat(e){this.tempStats.push(e)}createSample(){this.tempStats.length!==0&&(this.samples.push(this.collateSample()),this.prevLatestStat=this.getLatestStat(),this.tempStats.length=0)}clearSamples(){this.samples.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!==void 0?t?Math.round(r):r:void 0}calculateDifferenceForSample(e){var r;let t=Number((r=this.prevLatestStat)==null?void 0:r[e])||0;return(Number(this.getLatestStat()[e])||0)-t}calculateDifferenceAverage(e,t=!0){let i=this.calculateDifferenceForSample(e)/this.tempStats.length;return t?Math.round(i):i}calculateInstancesOfHigh(e,t){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((r,s)=>r+((s[e]||0)>t?1:0),0)}},Nr=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),Or=(a,e)=>a&&e&&a.enabled!==e.enabled,ni=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var xr=class{constructor(){this.worstState=void 0;this.TAG="[CPUPressureMonitor]";this.stateRanking={nominal:0,fair:1,serious:2,critical:3};this.init()}init(){return c(this,null,function*(){if(!("PressureObserver"in window)){d.d(this.TAG,"PressureObserver API not available");return}try{this.observer=new PressureObserver(e=>{if(e.length>0){let t=e[e.length-1].state;this.updateWorstState(t)}}),yield this.observer.observe("cpu",{sampleInterval:1e4}),this.worstState="nominal",d.d(this.TAG,"CPU pressure monitoring started")}catch(e){d.e(this.TAG,"Failed to initialize CPU pressure monitoring",e)}})}updateWorstState(e){if(this.worstState===void 0){this.worstState=e;return}this.stateRanking[e]>this.stateRanking[this.worstState]&&(this.worstState=e,d.d(this.TAG,`New worst CPU state: ${this.worstState}`))}getWorstState(){return this.worstState}resetWorstState(){this.worstState!==void 0&&(this.worstState="nominal",d.d(this.TAG,"CPU worst state reset to nominal"))}stop(){if(this.observer)try{this.observer.disconnect(),d.d(this.TAG,"CPU pressure monitoring stopped")}catch(e){d.e(this.TAG,"Error stopping CPU pressure monitoring",e)}}};var oi=class extends vt{constructor(t,i,r,s){super(t,i,r,s);this.trackAnalytics=new Map;this.cpuPressureMonitor=new xr}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:30}}sendEvent(){this.eventBus.analytics.publish(v.publishStats(this.toAnalytics())),super.sendEvent()}stop(){var t;super.stop(),(t=this.cpuPressureMonitor)==null||t.stop()}handleStatsUpdate(t){let i=!1,r=t.getLocalTrackStats();Object.keys(r).forEach(s=>{let n=r[s],o=this.store.getLocalPeerTracks().find(l=>l.getTrackIDBeingSent()===s);Object.keys(n).forEach(l=>{var g,f,P;let u=n[l];if(!o)return;let p=this.getTrackIdentifier(o.trackId,u),h=y(m({},u),{availableOutgoingBitrate:(f=(g=t.getLocalPeerStats())==null?void 0:g.publish)==null?void 0:f.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(P=this.trackAnalytics.get(p))==null||P.pushTempStat(h);else if(o){let M=new js({track:o,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind,cpuPressureMonitor:this.cpuPressureMonitor});M.pushTempStat(h),this.trackAnalytics.set(this.getTrackIdentifier(o.trackId,u),M)}let T=this.trackAnalytics.get(p);T!=null&&T.shouldCreateSample()&&(i=!0)})}),this.cleanTrackAnalyticsAndCreateSample(i)}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},js=class extends Mt{constructor(t){super(t);this.samples=[];this.getQualityLimitation=t=>{let i=t.qualityLimitationDurations;return i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other}};this.getSourceStats=t=>{if(!t.sourceStatsAvailable)return{};let i=t.sourceFrameHeight?{height_px:t.sourceFrameHeight,width_px:t.sourceFrameWidth}:void 0,r=this.calculateDifferenceForSample("sourceFrames"),s=this.calculateDifferenceForSample("framesEncoded"),n=r&&s?Math.max(0,r-s):void 0;return{source_resolution:i,source_avg_fps:this.calculateAverage("sourceFramesPerSecond"),source_total_frames:r,source_total_frames_dropped:n}};this.collateSample=()=>{var p,h,T,g,f,P;let t=this.getFirstStat(),i=this.getLatestStat(),r=i.frameHeight?{height_px:i.frameHeight,width_px:i.frameWidth}:void 0,s=this.calculateAverage("jitter",!1),n=this.calculateAverage("roundTripTime",!1),o=(p=this.cpuPressureMonitor)==null?void 0:p.getWorstState();(h=this.cpuPressureMonitor)==null||h.resetWorstState();let l=(g=(T=this.track).getMediaTrackSettings)==null?void 0:g.call(T),u=(P=(f=this.track).getPluginsMetrics)==null?void 0:P.call(f);return ni(m({timestamp:Date.now(),sample_start_ts:t.timestamp,sample_end_ts:i.timestamp,sample_duration_ms:i.timestamp-t.timestamp,avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:i.packetsLost,total_packets_sent:i.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:s?Math.round(s*1e3):void 0,avg_round_trip_time_ms:n?Math.round(n*1e3):void 0,total_quality_limitation:this.getQualityLimitation(i),resolution:r,cpu_pressure_state:o,track_settings:l,effects_metrics:u&&Object.keys(u).length>0?u:void 0},this.getSourceStats(i)))};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples});this.cpuPressureMonitor=t.cpuPressureMonitor}};var ci=class extends vt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:10}}sendEvent(){this.eventBus.analytics.publish(v.subscribeStats(this.toAnalytics())),super.sendEvent()}handleStatsUpdate(t){let i=t.getAllRemoteTracksStats(),r=!1;Object.keys(i).forEach(s=>{var f,P;let n=this.store.getTrackById(s),o=i[s],l=(f=this.trackAnalytics.get(s))==null?void 0:f.getLatestStat(),p=((M,R)=>{let $=(R==null?void 0:R.jitterBufferDelay)||0,ce=(R==null?void 0:R.jitterBufferEmittedCount)||0,B=((M==null?void 0:M.jitterBufferDelay)||0)-$,de=((M==null?void 0:M.jitterBufferEmittedCount)||0)-ce;return de>0?B*1e3/de:(R==null?void 0:R.calculatedJitterBufferDelay)||0})(o,l),h=this.calculateAvSyncForStat(o,t),T=y(m({},o),{calculatedJitterBufferDelay:p,avSync:h});if(o.kind==="video"){let M=n.getPreferredLayerDefinition();T.expectedFrameHeight=M==null?void 0:M.resolution.height,T.expectedFrameWidth=M==null?void 0:M.resolution.width}if(this.trackAnalytics.has(s))(P=this.trackAnalytics.get(s))==null||P.pushTempStat(T);else if(n){let M=new Qs({track:n,sampleWindowSize:this.sampleWindowSize,ssrc:o.ssrc.toString(),kind:o.kind});M.pushTempStat(T),this.trackAnalytics.set(s,M)}let g=this.trackAnalytics.get(s);g!=null&&g.shouldCreateSample()&&(r=!0)}),this.cleanTrackAnalyticsAndCreateSample(r)}calculateAvSyncForStat(t,i){if(!t.peerID||!t.estimatedPlayoutTimestamp||t.kind!=="video")return;let r=this.store.getPeerById(t.peerID),s=r==null?void 0:r.audioTrack,n=r==null?void 0:r.videoTrack;if(!(s&&n&&s.enabled&&n.enabled))return Ot;let l=i.getRemoteTrackStats(s.trackId);if(!l)return Ot;if(l.estimatedPlayoutTimestamp)return l.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},Qs=class extends Mt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),sample_start_ts:i.timestamp,sample_end_ts:t.timestamp,sample_duration_ms:t.timestamp-i.timestamp,total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_buffer_delay:this.calculateAverage("calculatedJitterBufferDelay",!1),avg_bitrate_bps:this.calculateAverage("bitrate")};if(t.kind==="video")return ni(y(m({},r),{avg_av_sync_ms:this.calculateAvgAvSyncForSample(),avg_frames_received_per_sec:this.calculateDifferenceAverage("framesReceived"),avg_frames_dropped_per_sec:this.calculateDifferenceAverage("framesDropped"),avg_frames_decoded_per_sec:this.calculateDifferenceAverage("framesDecoded"),frame_width:this.calculateAverage("frameWidth"),frame_height:this.calculateAverage("frameHeight"),expected_frame_width:this.calculateAverage("expectedFrameWidth"),expected_frame_height:this.calculateAverage("expectedFrameHeight"),pause_count:this.calculateDifferenceForSample("pauseCount"),pause_duration_seconds:this.calculateDifferenceForSample("totalPausesDuration"),freeze_count:this.calculateDifferenceForSample("freezeCount"),freeze_duration_seconds:this.calculateDifferenceForSample("totalFreezesDuration")}));{let s=(t.concealedSamples||0)-(t.silentConcealedSamples||0)-((i.concealedSamples||0)-(i.silentConcealedSamples||0));return ni(y(m({},r),{audio_level:this.calculateInstancesOfHigh("audioLevel",.05),audio_concealed_samples:s,audio_total_samples_received:this.calculateDifferenceForSample("totalSamplesReceived"),audio_concealment_events:this.calculateDifferenceForSample("concealmentEvents"),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")}))}};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===10||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}calculateAvgAvSyncForSample(){let i=this.tempStats.map(r=>r.avSync).filter(r=>r!==void 0&&r!==Ot);return i.length===0?Ot:i.reduce((r,s)=>r+s,0)/i.length}};var yt=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(yt||{});var di=We(require("sdp-transform"));function $n(a,e){var r;let t=di.parse(a.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return a;let i=e?Array.from(e.values()):[];return t.media.forEach(s=>{var l,u,p;let n=(l=s.msid)==null?void 0:l.split(" ")[0],o=(u=i.find(h=>h.type===s.type&&h.stream_id===n))==null?void 0:u.track_id;o&&(s.msid=(p=s.msid)==null?void 0:p.replace(/\s(.+)/,` ${o}`))}),{type:a.type,sdp:di.write(t)}}function Wn(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=di.parse(a.sdp).media.find(n=>W(n.mid)&&parseInt(n.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function qn(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var we="[HMSConnection]",et=class{constructor(e,t){this.candidates=new Array;this.localDescriptionEpoch=0;this.role=e,this.signal=t}get iceConnectionState(){return this.nativeConnection.iceConnectionState}get connectionState(){return this.nativeConnection.connectionState}get signalingState(){return this.nativeConnection.signalingState}get action(){return this.role===0?"PUBLISH":"SUBSCRIBE"}setSfuNodeId(e){this.sfuNodeId=e}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(we,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),qn($n(i,e))}catch(i){throw S.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(we,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw S.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}isStagingLocalDescription(e){return this.localDescriptionEpoch===e}setLocalDescription(e){return c(this,null,function*(){let t=++this.localDescriptionEpoch;try{d.d(we,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(i){throw S.WebrtcErrors.SetLocalDescriptionFailed(this.action,i.message)}return t})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(we,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw S.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(we,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(we,`[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()}handleSelectedIceCandidatePairs(){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 s=t.transport.iceTransport,n=()=>{typeof s.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=s.getSelectedCandidatePair(),this.selectedCandidatePair&&(this.observer.onSelectedCandidatePairChange(this.selectedCandidatePair),d.d(we,`${yt[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2))))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=n),n()}})}catch(e){d.w(we,`Error in logging selected ice candidate pair for ${yt[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e,t){return c(this,null,function*(){let i=(t==null?void 0:t.maxBitrate)||e.settings.maxBitrate,r=e instanceof q&&e.settings.maxFramerate,s=this.getSenders().find(n=>{var o;return((o=n==null?void 0:n.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(s){let n=s.getParameters();n.encodings.length===1&&(i&&(n.encodings[0].maxBitrate=i*1e3),r&&(n.encodings[0].maxFramerate=r)),yield s.setParameters(n)}else d.w(we,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){this.nativeConnection.close()}getReceivers(){return this.nativeConnection.getReceivers()}};var li=class extends et{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(Ii,{protocol:"SCTP"}),this.channel.onerror=s=>d.e(this.TAG,`publish data channel onerror ${s}`,s),this.nativeConnection.onicecandidate=({candidate:s})=>{s&&(this.observer.onIceCandidate(s),t.trickle(this.role,s))},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 s;this.observer.onDTLSTransportStateChange((s=this.nativeConnection.sctp)==null?void 0:s.transport.state)},this.nativeConnection.sctp.transport.onerror=s=>{var n;this.observer.onDTLSTransportError(new Error((n=s==null?void 0:s.error)==null?void 0:n.errorDetail)||"DTLS Transport failed")})}}close(){super.close(),this.channel.close()}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var jn=We(require("eventemitter2")),Jn=require("uuid");var ui=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 Kn=(a,e)=>`${a}:${e}`,pi=class extends et{constructor(t,i,r,s,n){super(1,t);this.isFlagEnabled=r;this.eventBus=n;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.RESPONSE_TIMEOUT=1e4;this.UNPROVEN_CHANNEL_TIMEOUT=500;this.channelProven=!1;this.pendingMessageQueue=[];this.latestRequestPerState=new Map;this.closed=!1;this.pendingAborts=new Set;this.eventEmitter=new jn.default({maxListeners:60});this.abortOnClose=t=>c(this,null,function*(){if(this.closed)throw t.catch(()=>{}),t.cancel("connection closed"),Error("Subscribe connection closed");let i,r=new Promise((s,n)=>{i=n});this.pendingAborts.add(i);try{return yield Promise.race([t,r])}finally{this.pendingAborts.delete(i),t.cancel("request settled")}});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,r)=>c(this,null,function*(){let s=()=>this.latestRequestPerState.get(r)!==i,n=()=>(d.d(this.TAG,`Dropping ${i} - ${this.closed?"closed":"superseded"}`,t),{id:i,dropped:!0}),o,l,u=!1;for(let p=0;p<this.MAX_RETRIES;p++){o=void 0;let h=!1,T=!1;if(s())return n();try{if(yield this.waitForChannelOpen(),s())return n();this.apiChannel.send(t),h=!0;let f=!u;u=!0,T=f&&!this.channelProven,o=yield this.waitForResponse(i,f)}catch(f){if(l=f,d.w(this.TAG,`Attempt failed for ${i}`,{request:t,try:p+1,error:f}),this.closed)break;s()||this.publishRequestEvent(v.subscribeRequestRetry,r,{attempt:p,unproven:T,sent:h});continue}let g=o.error;if(g){if(g.code===404)return d.d(this.TAG,`Track not found ${i}`,{request:t,try:p+1,error:g}),o;if(d.d(this.TAG,`Failed sending ${i}`,{request:t,try:p+1,error:g}),!(Math.floor(g.code/100)===5||g.code===429)){if(s())return n();throw Error(`code=${g.code}, message=${g.message} - ${i} not retried`)}if(p<this.MAX_RETRIES-1){let P=(2+Math.random()*2)*1e3;yield Fe(P)}}else break}if(o!=null&&o.error){if(s())return n();throw Error(`code=${o.error.code}, message=${o.error.message} - ${i} after ${this.MAX_RETRIES} tries`)}if(o)return o;if(s()||this.closed)return n();throw this.publishRequestEvent(v.subscribeRequestUnanswered,r,{attempts:this.MAX_RETRIES}),Error(`No response from SFU for ${i} after ${this.MAX_RETRIES} tries - ${t}`,{cause:l})});this.waitForChannelOpen=()=>c(this,null,function*(){var t;((t=this.apiChannel)==null?void 0:t.readyState)!=="open"&&(yield this.abortOnClose(this.eventEmitter.waitFor("open",{timeout:this.RESPONSE_TIMEOUT})))});this.waitForResponse=(t,i)=>c(this,null,function*(){let r=i&&!this.channelProven,s=yield this.abortOnClose(this.eventEmitter.waitFor("message",{filter:o=>o.includes(t),timeout:r?this.UNPROVEN_CHANNEL_TIMEOUT:this.RESPONSE_TIMEOUT})),n=JSON.parse(s[0]);return d.d(this.TAG,`response for ${t} -`,JSON.stringify(n,null,2)),n});this.observer=s,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===Ii&&(this.channelProven=!1,this.apiChannel=new ui(t.channel,{onMessage:i=>{this.channelProven=!0,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.observer.onIceCandidate(t.candidate),this.signal.trickle(this.role,t.candidate))},this.nativeConnection.ontrack=t=>{var p;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let h=new Re(i,this);this.remoteStreams.set(r,h)}i.addEventListener("removetrack",h=>{if(h.track.id!==t.track.id)return;let T=s.tracks.findIndex(g=>{var f;return g.nativeTrack.id===h.track.id&&t.transceiver.mid===((f=g.transceiver)==null?void 0:f.mid)});if(T>=0){let g=s.tracks[T];this.observer.onTrackRemove(g),s.tracks.splice(T,1),s.tracks.length===0&&this.remoteStreams.delete(r)}});let s=this.remoteStreams.get(r),n=t.track.kind==="audio",o=n?le:x,l=n?new o(s,t.track):new o(s,t.track,void 0,this.isFlagEnabled("disableNoneLayerRequest"));t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),l.transceiver=t.transceiver;let u=Wn(this.remoteDescription,(p=t.transceiver)==null?void 0:p.mid);u&&l.setSdpTrackId(u),s.tracks.push(l),this.observer.onTrackAdd(l)}}cancelPendingRequest(t,i){this.latestRequestPerState.delete(Kn(t,i))}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){return c(this,null,function*(){let i=(0,Jn.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:i,dropped:!0};let r=JSON.stringify(m({id:i,jsonrpc:"2.0"},t)),s=Kn(t.method,t.params.track_id);this.latestRequestPerState.set(s,i);try{return yield this.sendMessage(r,i,s)}finally{this.latestRequestPerState.get(s)===i&&this.latestRequestPerState.delete(s)}})}close(){var t;this.closed=!0,super.close(),(t=this.apiChannel)==null||t.close(),this.pendingAborts.forEach(i=>i(Error("Subscribe connection closed"))),this.pendingAborts.clear()}publishRequestEvent(t,i,r){var n;let s=i.indexOf(":");(n=this.eventBus)==null||n.analytics.publish(t(y(m({},r),{method:i.slice(0,s),trackId:i.slice(s+1)})))}};var Qn=(a,e)=>!e||e.length===0?a:e.map(i=>({urls:i.urls,credentialType:"password",credential:i.password,username:i.userName}));var Br="[InitService]",hi=class{static handleError(e,t){switch(e.status){case 404:throw S.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw S.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:s="",iceServers:n}){d.d(Br,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let l=jd(r,t,i,s);try{let u=yield fetch(l,{headers:{Authorization:`Bearer ${e}`}});try{let p=yield u.clone().json();return this.handleError(u,p),d.d(Br,`config is ${JSON.stringify(p,null,2)}`),Jd(p,n)}catch(p){let h=yield u.text();throw d.e(Br,"json error",p.message,h),p instanceof k?p:S.APIErrors.ServerErrors(u.status,"INIT",p.message)}}catch(u){let p=u;throw["Failed to fetch","NetworkError","ECONNRESET"].some(h=>p.message.includes(h))?S.APIErrors.EndpointUnreachable("INIT",p.message):p}})}};function jd(a,e,t,i){try{let r=new URL("/init",a);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 s=r;throw d.e(Br,s.name,s.message),s}}function Jd(a,e){var t;return y(m({},a),{rtcConfiguration:y(m({},a.rtcConfiguration),{iceServers:Qn((t=a.rtcConfiguration)==null?void 0:t.ice_servers,e)})})}var zn=require("uuid");var mi=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ve(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}setSfuNodeId(e){this.sfuNodeId=e}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 s;let i=(0,zn.v4)(),r={method:e,params:t,id:i,jsonrpc:"2.0"};(s=this.socket)==null||s.send(JSON.stringify(r));try{return yield new Promise((o,l)=>{this.callbacks.set(i,{resolve:o,reject:l,metadata:{method:e}})})}catch(n){if(n instanceof k)throw n;let o=n;throw S.WebsocketMethodErrors.ServerErrors(Number(o.code),Yr(e),o.message)}})}notify(e,t){var r,s;let i={method:e,params:t};((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN&&((s=this.socket)==null||s.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 s=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(S.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=o=>{d.w(`Websocket closed code=${o.code}`),r?this.setIsConnected(!1,`code: ${o.code}${o.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(S.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${o.code}`)))},this.socket.addEventListener("error",s);let n=()=>{var o,l;r=!0,t(),this.setIsConnected(!0),this.id++,(o=this.socket)==null||o.removeEventListener("open",n),(l=this.socket)==null||l.removeEventListener("error",s),this.pingPongLoop(this.id)};this.socket.addEventListener("open",n),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,s,n,o){return c(this,null,function*(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:o,server_sub_degrade:r,simulcast:s,onDemandTracks:n},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:h})=>this.trickle(p,h)),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,sfu_node_id:this.sfuNodeId}):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),sfu_node_id:this.sfuNodeId})})}answer(e){this.notify("answer",{desc:e,sfu_node_id:this.sfuNodeId})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(e){this.notify("leave",{client_reason:e})}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(s=>{setTimeout(()=>{s(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",m({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",m({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",m({},e))})}startTranscription(e){return c(this,null,function*(){yield this.call("transcription-start",m({},e))})}stopTranscription(e){return c(this,null,function*(){yield this.call("transcription-stop",m({},e))})}updateTranscriptionConfig(e){return c(this,null,function*(){yield this.call("transcription-config-update",m({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",m({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",m({},e))})}getPeer(e){return c(this,null,function*(){return yield this.call("get-peer",m({},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)})}findPeerByName(e){return c(this,null,function*(){return yield this.call("peer-name-search",e)})}setSessionMetadata(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",m({},e))}listenMetadataChange(e){if(!this.isConnected)throw S.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 S.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",m({},e))}getPollInfo(e){return this.call("poll-info-get",m({},e))}setPollQuestions(e){return this.call("poll-questions-set",m({},e))}startPoll(e){return this.call("poll-start",m({},e))}stopPoll(e){return this.call("poll-stop",m({},e))}getPollQuestions(e){return this.call("poll-questions-get",m({},e))}setPollResponses(e){return this.call("poll-response",m({},e))}getPollResponses(e){return this.call("poll-responses",m({},e))}getPollsList(e){return this.call("poll-list",m({},e))}getPollResult(e){return this.call("poll-result",m({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",m({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",m({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",m({},e))}validateConnection(){if(!this.isConnected)throw S.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(S.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,s,n,o;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(S.WebSocketConnectionErrors.WebSocketConnectionLost((n=t.metadata)!=null&&n.method?Yr((o=t.metadata)==null?void 0:o.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 s=yield this.ping(t);this.pongResponseTimes.enqueue(s),s>t?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${Ta()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>{this.id===e&&this.pingPongLoop(e)},((r=window.HMS)==null?void 0:r.PING_INTERVAL)||3e3)}})}call(e,t){return c(this,null,function*(){let r=S.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`),s;for(s=1;s<=3;s++)try{return this.validateConnection(),d.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(n){if(r=n,d.e(this.TAG,`Failed sending ${e} try: ${s}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429||r.code===1003))break;let l=(2+Math.random()*2)*1e3;yield Fe(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var Yn=()=>{if(!F||typeof navigator.connection=="undefined")return;let a=navigator.connection;return{downlink:a.downlink,downlinkMax:a.downlinkMax,effectiveType:a.effectiveType,rtt:a.rtt,saveData:a.saveData,type:a.type}};var A="[HMSTransport]:",Zn=a=>a instanceof k&&a.code===E.WebrtcErrors.PUBLISH_ANSWER_SUPERSEDED,Si=class{constructor(e,t,i,r,s,n,o){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=s;this.analyticsTimer=n;this.pluginUsageTracker=o;this.state="Disconnected";this.trackStates=new Map;this.publishConnection=null;this.subscribeConnection=null;this.maxSubscribeBitrate=0;this.joinRetryCount=0;this.publishDisconnectTimer=0;this.onScreenshareStop=()=>{};this.screenStream=new Set;this.callbacks=new Map;this.setListener=e=>{this.listener=e};this.setOnScreenshareStop=e=>{this.onScreenshareStop=e};this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;if(e.sfu_node_id&&this.subscribeConnection.sfuNodeId&&this.subscribeConnection.sfuNodeId!==e.sfu_node_id){d.d(A,"ignoring old offer");return}yield this.subscribeConnection.setRemoteDescription(e),d.d(A,`[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(A,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(A,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t);let i;t instanceof k?i=t:i=S.GenericErrors.Unknown("SUBSCRIBE",t.message),yield this.observer.onStateChange("Failed",i),this.eventBus.analytics.publish(v.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(A,"socket offline",ai[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(A,"socket online",ai[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new mi(this.signalObserver);this.analyticsSignalTransport=new _r(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(A,"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(je,{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(at,{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 e;if(!this.joinParameters||this.state==="Leaving")return!1;d.d(A,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId,this.joinParameters.iceServers));try{return(e=this.store.getRoom())!=null&&e.joinedAt?this.signal.isConnected&&(yield this.retryPublishIceFailedTask()):this.signal.isConnected}finally{this.signal.trackUpdate(this.trackStates)}});this.webrtcInternals=new Fi(this.store,this.eventBus);let l=(u,p)=>c(this,null,function*(){u!==this.state&&(this.state=u,yield this.observer.onStateChange(this.state,p))});this.retryScheduler=new Lr(l,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(u=>{var h,T;let p=((T=(h=u.getLocalPeerStats())==null?void 0:h.subscribe)==null?void 0:T.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,p)}),this.eventBus.localAudioEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p)),this.eventBus.localVideoEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p))}getWebsocketEndpoint(){if(this.initConfig)return this.initConfig.endpoint}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)}setConnectivityListener(e){this.connectivityListener=e}preview(e,t,i,r,s=!1,n){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,s,n);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,s=!1,n){return c(this,null,function*(){d.d(A,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s,n)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),this.initStatsAnalytics(),d.d(A,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(A,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let l=o;throw l.isTerminal=l.isTerminal||l.code===500,yield this.observer.onStateChange(this.state,l),l}d.d(A,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1,n){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Hr(e,i,r.name,r.metaData,t,s,n);try{return yield this.internalConnect(e,t,i,n)}catch(o){if(!(o instanceof k))throw o;if([E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,E.WebSocketConnectionErrors.FAILED_TO_CONNECT,E.WebSocketConnectionErrors.ABNORMAL_CLOSE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429")||o.code===E.APIErrors.ENDPOINT_UNREACHABLE&&!navigator.onLine){let u=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i,n),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:u,originalState:this.state,changeState:!1})}else throw o}})}leave(i){return c(this,arguments,function*(e,t="user request"){var r,s,n;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(A,"leaving in transport");try{let o=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(o&&this.eventBus.analytics.publish(v.getKrispUsage(o)),this.state="Leaving",(r=this.publishStatsAnalytics)==null||r.stop(),(s=this.subscribeStatsAnalytics)==null||s.stop(),(n=this.webrtcInternals)==null||n.cleanup(),this.clearPeerConnections(),e)try{this.signal.leave(t),d.d(A,"signal leave done")}catch(l){d.w(A,"failed to send leave on websocket to server",l)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(o){this.eventBus.analytics.publish(v.disconnect(o)),d.e(A,"leave: FAILED \u274C",o)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){var t;for(let i of e)try{yield this.publishTrack(i),(t=this.connectivityListener)==null||t.onMediaPublished(i)}catch(r){this.eventBus.analytics.publish(v.publish({devices:this.deviceManager.getDevices(),error:r}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}setSFUNodeId(e){var t,i;this.signal.setSfuNodeId(e),this.sfuNodeId?e&&this.sfuNodeId!==e&&(this.sfuNodeId=e,this.handleSFUMigration()):(this.sfuNodeId=e,(t=this.publishConnection)==null||t.setSfuNodeId(e),(i=this.subscribeConnection)==null||i.setSfuNodeId(e))}republishOnMigration(e){return c(this,null,function*(){try{yield this.publishTrack(e)}catch(t){d.w(A,`republish after migration failed for ${e.trackId}`,t),this.eventBus.analytics.publish(v.publish({error:t})),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId)&&(this.store.addTrack(e),e.isPublished=!0)}})}handleSFUMigration(){return c(this,null,function*(){var s,n;d.time("sfu migration"),this.clearPeerConnections();let e=this.store.getPeerMap();this.store.removeRemoteTracks();for(let o in e){let l=e[o];l.isLocal||(l.audioTrack=void 0,l.videoTrack=void 0,l.auxiliaryTracks=[])}let t=this.store.getLocalPeer();if(!t)return;this.createPeerConnections(),this.trackStates.clear(),yield this.negotiateOnFirstPublish();let i=new Map;if(t.audioTrack){let o=t.audioTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream));let l=t.audioTrack.clone(i.get(o.id));this.store.removeTrack(t.audioTrack),t.audioTrack.cleanup(),t.audioTrack=l,yield this.republishOnMigration(l)}if(t.videoTrack){let o=t.videoTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream)),this.store.removeTrack(t.videoTrack);let l=t.videoTrack.clone(i.get(o.id));t.videoTrack.cleanup(),t.videoTrack=l,yield this.republishOnMigration(l)}let r=[];for(;t.auxiliaryTracks.length>0;){let o=t.auxiliaryTracks.shift();if(o){let l=o.stream;i.get(l.id)||i.set(l.id,new fe(o.source==="screen"?l.nativeStream.clone():new MediaStream)),this.store.removeTrack(o);let u=o.clone(i.get(l.id));u.type==="video"&&u.source==="screen"&&(this.screenStream.add(l.nativeStream),this.screenStream.add(u.stream.nativeStream),u.nativeTrack.addEventListener("ended",this.onScreenshareStop)),o.cleanup(),r.push(u),yield this.republishOnMigration(u)}}t.auxiliaryTracks=r,i.clear(),(n=(s=this.listener)==null?void 0:s.onSFUMigration)==null||n.call(s),d.timeEnd("sfu migration")})}trackUpdate(e,t){var s;let r=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);if(r){let n=new Xt(y(m({},r),{mute:!t}));this.trackStates.set(r.track_id,n),d.d(A,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[r.track_id,n]]));let o=this.store.getLocalPeer();o&&t===e.enabled&&((s=this.listener)==null||s.onTrackUpdate(t?3:2,e,o))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(A,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Xt(e));let t=new Promise((s,n)=>{this.callbacks.set(je,{promise:{resolve:s,reject:n},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(A,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof q?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>d.w(A,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,d.d(A,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(A,`\u23F3 unpublishTrack: trackId=${e.trackId}`,`${e}`),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId))this.trackStates.delete(e.publishedTrackId);else{let s=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);s&&this.trackStates.delete(s.track_id)}let t=new Promise((r,s)=>{this.callbacks.set(je,{promise:{resolve:r,reject:s},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e);try{yield t}catch(r){if(!Zn(r))throw r;d.w(A,"unpublishTrack: renegotiation superseded, tearing down anyway",r)}finally{yield this.teardownUnpublishedTrack(e)}d.d(A,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}teardownUnpublishedTrack(e){return c(this,null,function*(){try{yield e.cleanup()}catch(t){d.w(A,`unpublishTrack: cleanup failed for ${e.trackId}`,t)}e.source==="screen"&&this.screenStream&&this.screenStream.forEach(t=>{t.getTracks().forEach(i=>{i.stop()}),this.screenStream.delete(t)}),this.store.removeTrack(e)})}clearPeerConnections(){return c(this,null,function*(){var e,t;clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0,clearTimeout(this.publishDisconnectTimer),this.publishDisconnectTimer=0,this.lastPublishDtlsState="new",(e=this.publishConnection)==null||e.close(),(t=this.subscribeConnection)==null||t.close(),this.publishConnection=null,this.subscribeConnection=null})}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(){var t,i,r;let e=(s,n,o=!1)=>{(["disconnected","failed"].includes(n)?d.w.bind(d):d.d.bind(d))(A,`${yt[s]} ${o?"ice":""} connection state change: ${n}`)};if(this.initConfig){let s={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:o=>{var p,h,T;if((o==="failed"?d.w.bind(d):d.d.bind(d))(A,`Publisher on dtls transport state change: ${o}`),!o||this.lastPublishDtlsState===o||(this.lastPublishDtlsState=o,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),o!=="connecting"&&o!=="failed"))return;let u=(T=(h=(p=this.initConfig)==null?void 0:p.config)==null?void 0:h.dtlsStateTimeouts)==null?void 0:T[o];!u||u<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var f;let g=(f=this.publishConnection)==null?void 0:f.nativeConnection.connectionState;if(g&&o&&g===o){let P=S.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${o} timeout:${u}ms`,!0);this.eventBus.analytics.publish(v.disconnect(P)),this.observer.onFailure(P)}},u))},onDTLSTransportError:o=>{d.e(A,`onDTLSTransportError ${o.name} ${o.message}`,o),this.eventBus.analytics.publish(v.disconnect(o))},onIceConnectionChange:o=>c(this,null,function*(){e(0,o,!0)}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f,P;e(0,o,!1),o!=="new"&&(o==="connected"?((l=this.connectivityListener)==null||l.onICESuccess(!0),(u=this.publishConnection)==null||u.handleSelectedIceCandidatePairs()):o==="failed"?yield this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(T=(h=(p=this.publishConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:h.local)==null?void 0:T.candidate}; remote candidate - ${(P=(f=(g=this.publishConnection)==null?void 0:g.selectedCandidatePair)==null?void 0:f.remote)==null?void 0:P.candidate}`)):this.publishDisconnectTimer=window.setTimeout(()=>{var M,R,$,ce,B,de,De;((M=this.publishConnection)==null?void 0:M.connectionState)!=="connected"&&this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(ce=($=(R=this.publishConnection)==null?void 0:R.selectedCandidatePair)==null?void 0:$.local)==null?void 0:ce.candidate}; remote candidate - ${(De=(de=(B=this.publishConnection)==null?void 0:B.selectedCandidatePair)==null?void 0:de.remote)==null?void 0:De.candidate}`))},5e3))}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!0)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!0)}},n={onApiChannelMessage:o=>{this.observer.onNotification(JSON.parse(o))},onTrackAdd:o=>{d.d(A,"[Subscribe] onTrackAdd",`${o}`),this.observer.onTrackAdd(o)},onTrackRemove:o=>{d.d(A,"[Subscribe] onTrackRemove",`${o}`),this.observer.onTrackRemove(o)},onIceConnectionChange:o=>c(this,null,function*(){var l;if(e(1,o,!0),o==="connected"){let u=this.callbacks.get(at);this.callbacks.delete(at),(l=this.connectivityListener)==null||l.onICESuccess(!1),u&&u.promise.resolve(!0)}}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f;if(e(1,o,!1),o==="failed")yield this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(p=(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local)==null?void 0:p.candidate}; remote candidate - ${(g=(T=(h=this.subscribeConnection)==null?void 0:h.selectedCandidatePair)==null?void 0:T.remote)==null?void 0:g.candidate}`));else if(o==="disconnected")setTimeout(()=>{var P,M,R,$,ce,B,de;((P=this.subscribeConnection)==null?void 0:P.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${($=(R=(M=this.subscribeConnection)==null?void 0:M.selectedCandidatePair)==null?void 0:R.local)==null?void 0:$.candidate}; remote candidate - ${(de=(B=(ce=this.subscribeConnection)==null?void 0:ce.selectedCandidatePair)==null?void 0:B.remote)==null?void 0:de.candidate}`))},5e3);else if(o==="connected"){(f=this.subscribeConnection)==null||f.handleSelectedIceCandidatePairs();let P=this.callbacks.get(at);this.callbacks.delete(at),P&&P.promise.resolve(!0)}}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!1)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!1)}};this.publishConnection||(this.publishConnection=new li(this.signal,this.initConfig.rtcConfiguration,s)),this.subscribeConnection||(this.subscribeConnection=new pi(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),n,this.eventBus))}(r=this.webrtcInternals)==null||r.setPeerConnections({publish:(t=this.publishConnection)==null?void 0:t.nativeConnection,subscribe:(i=this.subscribeConnection)==null?void 0:i.nativeConnection})}negotiateJoinWithRetry(s){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(n){d.e(A,"Join negotiation failed \u274C",n);let o=n instanceof k?n:S.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${n.message}`),l=parseInt(`${o.code/100}`)===5||[E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(o.code);if(o.code===410&&(o.isTerminal=!0),l){this.joinRetryCount=0,o.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:o,task:u,originalState:"Joined",changeState:!1})}else throw n}})}negotiateJoin(s){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(A,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(A,"Publish peer connection not found, cannot negotiate"),!1;let s=this.publishConnection,n=yield s.createOffer(),o=yield s.setLocalDescription(n),l=this.isFlagEnabled("subscribeDegradation"),u=this.isFlagEnabled("simulcast"),p=this.isFlagEnabled("onDemandTracks"),h=yield this.signal.join(e,t,!i,l,u,p,n);this.setSFUNodeId(h==null?void 0:h.sfu_node_id),this.assertPublishAnswerApplicable(s,o,"JOIN"),yield s.setRemoteDescription(h);for(let T of s.candidates)yield s.addIceCandidate(T);return s.initAfterJoin(),!!h})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(A,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),o=this.isFlagEnabled("onDemandTracks"),l=yield this.signal.join(e,t,!i,s,n,o);return this.setSFUNodeId(l==null?void 0:l.sfu_node_id),!!l})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(A,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(A,"Publish peer connection not found, cannot negotiate"),!1;let e=this.publishConnection;try{let t=yield e.createOffer(this.trackStates),i=yield e.setLocalDescription(t),r=yield this.signal.offer(t,this.trackStates);this.assertPublishAnswerApplicable(e,i,"PUBLISH"),yield e.setRemoteDescription(r);for(let s of e.candidates)yield e.addIceCandidate(s);return e.initAfterJoin(),!!r}catch(t){return this.handleFirstPublishNegotiationError(t)}})}handleFirstPublishNegotiationError(e){var t;if(!(e instanceof k))throw e;if(e.code===421)return!0;if(Zn(e))return(t=this.publishConnection)==null||t.initAfterJoin(),!1;throw e}assertPublishAnswerApplicable(e,t,i){let r;if(e!==this.publishConnection?r="connection_replaced":e.isStagingLocalDescription(t)?e.signalingState!=="have-local-offer"&&(r="unexpected_state"):r="superseded_offer",!!r)throw d.w(A,`[role=PUBLISH] discarding answer reason=${r} state=${e.signalingState}`),this.eventBus.analytics.publish(v.publishAnswerDiscarded({reason:r,action:i.toString(),signaling_state:e.signalingState,transport_state:ai[this.state],epoch:t})),i==="JOIN"?S.WebrtcErrors.SetRemoteDescriptionFailed(i,`${r} epoch=${t}`):S.WebrtcErrors.PublishAnswerSuperseded(i,`${r} epoch=${t}`)}releaseRenegotiationCallback(e){this.callbacks.get(je)===e&&this.callbacks.delete(je)}performPublishRenegotiation(e){return c(this,null,function*(){d.d(A,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(je);if(!t){d.w(A,"no callback found for renegotiation");return}let i=this.publishConnection;if(!i){d.e(A,"Publish peer connection not found, cannot renegotiate"),t.promise.reject(S.WebrtcErrors.PublishAnswerSuperseded(t.action,"publish connection is gone")),this.releaseRenegotiationCallback(t);return}try{let r=yield i.createOffer(this.trackStates,e),s=yield i.setLocalDescription(r);d.time("renegotiation-offer-exchange");let n=yield this.signal.offer(r,this.trackStates);d.timeEnd("renegotiation-offer-exchange"),this.assertPublishAnswerApplicable(i,s,t.action),yield i.setRemoteDescription(n),t.promise.resolve(!0),d.d(A,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(r){let s;r instanceof k?s=r:s=S.GenericErrors.Unknown("PUBLISH",r.message),s.code===421?t.promise.resolve(!0):t.promise.reject(s),d.d(A,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}finally{this.releaseRenegotiationCallback(t)}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(e===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"}))})}internalConnect(e,t,i,r){return c(this,null,function*(){var n,o,l;d.d(A,"connect: started \u23F0");let s=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield hi.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t,iceServers:r}),(n=this.connectivityListener)==null||n.onInitSuccess(this.initConfig.endpoint);let u=this.store.getRoom();return u&&(u.effectsKey=(o=this.initConfig.config.vb)==null?void 0:o.effectsKey,u.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),u.disableNoneLayerRequest=this.isFlagEnabled("disableNoneLayerRequest"),u.isVBEnabled=this.isFlagEnabled("vb"),u.isHipaaEnabled=this.isFlagEnabled("hipaa"),u.isNoiseCancellationEnabledFromInit=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),Le.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),(l=this.connectivityListener)==null||l.onSignallingSuccess(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(A,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(u){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(v.connect(u,this.getAdditionalAnalyticsProperties(),s,new Date,t)),d.e(A,"\u274C internal connect: failed",u),u}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(A,"aborting join as transport state is disconnected"),S.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw S.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(A,"\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",La),i.searchParams.set("protocol_spec",wa),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(A,"\u2705 internal connect: connected to ws endpoint")})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new oi(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 ci(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,s;return((s=(r=this.initConfig)==null?void 0:r.config[e])==null?void 0:s[t])||i}doesRoleNeedWebRTC(e){var r,s;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&&((s=e.subscribeParams.subscribeToRoles)==null?void 0:s.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}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw S.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=v.connect(e,i);break;case 1:r=v.disconnect(e,i);break;case 2:r=v.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=v.publish({error:e});break;case 4:r=v.subscribeFail(e);break}this.eventBus.analytics.publish(r)}getSubscribeConnection(){return this.subscribeConnection}getAdditionalAnalyticsProperties(){var n,o,l,u,p,h,T,g;let e=Yn(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(f=>f.degraded).length,r=(u=(l=(o=(n=this.getWebrtcInternals())==null?void 0:n.getCurrentStats())==null?void 0:o.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,s=(g=(T=(h=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:h.getLocalPeerStats())==null?void 0:T.subscribe)==null?void 0:g.bitrate;return{network_info:e,document_hidden:t,num_degraded_tracks:i,bitrate:{publish:r,subscribe:s},max_sub_bitrate:this.maxSubscribeBitrate,recent_pong_response_times:this.signal.getPongResponseTimes(),transport_state:this.state}}};function Vr(a){if(!a||a.length===0)throw S.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=a.split(".");if(e.length!==3)throw S.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 S.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var eo={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},Fr=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new Ai;this.sdkState=m({},eo);this.isDiagnostics=!1;this.playlistSettings={video:{bitrate:is},audio:{bitrate:rs}};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,s;let i=n=>c(this,null,function*(){var o,l;yield this.internalLeave(!0,n),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(o=this.errorListener)==null?void 0:o.onError)==null||l.call(o,n)),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,(s=this.listener)==null||s.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.handlePreviewError=e=>{var t;this.analyticsTimer.end("preview_time"),e&&((t=this.errorListener)==null||t.onError(e)),this.sendPreviewAnalyticsEvent(e),this.sdkState.isPreviewInProgress=!1};this.handleTrackInterruption=e=>{var t,i;d.d(this.TAG,"Track interruption",`{
103
+ }`),t)try{yield this.unblockAutoplay()}catch(i){d.w("[AudioOutputManager]","unblockAutoplay failed after setDevice",i)}return t})}unblockAutoplay(){return c(this,null,function*(){yield this.audioSinkManager.unblockAutoplay(),yield ne.resumeContext()})}};var ii=class{static handleError(e){if(e.status===404)throw S.APIErrors.EndpointUnreachable("FEEDBACK",e.statusText);if(e.status>=400)throw S.APIErrors.ServerErrors(e.status,"FEEDBACK",e==null?void 0:e.statusText)}static sendFeedback(s){return c(this,arguments,function*({token:e,eventEndpoint:t="https://event.100ms.live",info:i,feedback:r}){d.d(this.TAG,`sendFeedback: feedbackEndpoint=${t} peerId=${i.peer.peer_id} session=${i.peer.session_id} `);let n=new URL("v2/client/feedback",t),o=y(m({},i),{payload:r});try{let l=yield fetch(n,{headers:{Authorization:`Bearer ${e}`},body:JSON.stringify(o),method:"POST"});try{this.handleError(l);return}catch(u){throw d.e(this.TAG,"error",u.message,l.status),u instanceof k?u:S.APIErrors.ServerErrors(l.status,"FEEDBACK",u.message)}}catch(l){let u=l;throw["Failed to fetch","NetworkError","ECONNRESET"].some(p=>u.message.includes(p))?S.APIErrors.EndpointUnreachable("FEEDBACK",u.message):u}})}};ii.TAG="[FeedbackService]";var Fn=require("eventemitter2");var U=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 Tt=class{constructor(){this.eventEmitter=new Fn.EventEmitter2;this.analytics=new U(G.ANALYTICS,this.eventEmitter);this.deviceChange=new U(G.DEVICE_CHANGE,this.eventEmitter);this.localAudioEnabled=new U(G.LOCAL_AUDIO_ENABLED,this.eventEmitter);this.localVideoEnabled=new U(G.LOCAL_VIDEO_ENABLED,this.eventEmitter);this.localVideoUnmutedNatively=new U(G.LOCAL_VIDEO_UNMUTED_NATIVELY,this.eventEmitter);this.localAudioUnmutedNatively=new U(G.LOCAL_AUDIO_UNMUTED_NATIVELY,this.eventEmitter);this.statsUpdate=new U(G.STATS_UPDATE,this.eventEmitter);this.trackDegraded=new U(G.TRACK_DEGRADED,this.eventEmitter);this.trackRestored=new U(G.TRACK_RESTORED,this.eventEmitter);this.trackAudioLevelUpdate=new U(G.TRACK_AUDIO_LEVEL_UPDATE,this.eventEmitter);this.audioPluginFailed=new U(G.AUDIO_PLUGIN_FAILED,this.eventEmitter);this.localAudioSilence=new U(G.LOCAL_AUDIO_SILENCE,this.eventEmitter);this.trackInterruption=new U(G.TRACK_INTERRUPTION,this.eventEmitter);this.policyChange=new U(G.POLICY_CHANGE,this.eventEmitter);this.localRoleUpdate=new U(G.LOCAL_ROLE_UPDATE,this.eventEmitter);this.audioTrackUpdate=new U(G.AUDIO_TRACK_UPDATE,this.eventEmitter);this.audioTrackAdded=new U(G.AUDIO_TRACK_ADDED,this.eventEmitter);this.audioTrackRemoved=new U(G.AUDIO_TRACK_REMOVED,this.eventEmitter);this.autoplayError=new U(G.AUTOPLAY_ERROR,this.eventEmitter);this.leave=new U(G.LEAVE,this.eventEmitter);this.error=new U(G.ERROR,this.eventEmitter)}};var hr=class{constructor(e,t,i){this.store=e;this.listener=t;this.audioListener=i}handleActiveSpeakers(e){var s,n,o;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)}));(s=this.audioListener)==null||s.onAudioLevelUpdate(i),this.store.updateSpeakers(i);let r=t[0];if(r){let l=this.store.getPeerById(r.peer_id);(n=this.listener)==null||n.onPeerUpdate(4,l)}else(o=this.listener)==null||o.onPeerUpdate(5,null)}};var mr=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 Sr=class{constructor(e,t){this.store=e;this.listener=t}handleQualityUpdate(e){var r;let i=e.peers.map(s=>{let n=this.store.getPeerById(s.peer_id);return n&&n.updateNetworkQuality(s.downlink_score),{peerID:s.peer_id,downlinkQuality:s.downlink_score}});(r=this.listener)==null||r.onConnectionQualityUpdate(i)}};var ft=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 permanently",e),Object.keys(e.tracks).forEach(i=>{var o;let r=this.store.getTrackState(i);if(!r)return;let s=this.store.getTrackById(i);if(!s){d.d(this.TAG,"Track not found in store");return}s.type==="audio"&&this.eventBus.audioTrackRemoved.publish(s),this.store.removeTrack(s);let n=this.store.getPeerById(r.peerId);n&&(this.removePeerTracks(n,s),(o=this.listener)==null||o.onTrackUpdate(1,s,n))})};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 x&&this.setLayer(r,i)}};this.handleTrackUpdate=(e,t=!0)=>{var s,n;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=be(r,this.store),this.store.addPeer(i));for(let o in e.tracks){let l=Object.assign({},(s=this.store.getTrackState(o))==null?void 0:s.trackInfo),u=e.tracks[o],p=this.store.getTrackById(o);if(this.store.setTrackState({peerId:e.peer.peer_id,trackInfo:m(m({},l),u)}),!p||this.tracksToProcess.has(o))this.processTrackInfo(u,e.peer.peer_id,t),this.processPendingTracks();else{this.logIfRejected(p.setEnabled(!u.mute),p);let h=this.processTrackUpdate(p,l,u);h&&((n=this.listener)==null||n.onTrackUpdate(h,p,i))}}};this.processTrackInfo=(e,t,i)=>{};this.processPendingTracks=()=>{new Map(this.tracksToProcess).forEach(t=>{var s;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,this.logIfRejected(t.setEnabled(!i.trackInfo.mute),t),this.addAudioTrack(r,t),this.addVideoTrack(r,t),t.type==="audio"?this.eventBus.audioTrackAdded.publish({track:t,peer:r}):(s=this.listener)==null||s.onTrackUpdate(0,t,r),this.tracksToProcess.delete(t.trackId)})}}logIfRejected(e,t){e.catch(i=>d.e(this.TAG,"could not apply mute state",`${t}`,i))}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 s;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 n=this.store.getPeerById(i.peerId);if(!n)return;this.removePeerTracks(n,e),(s=this.listener)==null||s.onTrackUpdate(1,e,n),e.type==="audio"&&this.eventBus.audioTrackRemoved.publish(e)}}setLayer(e,t){var s,n;let i=this.store.getPeerByTrackId(e.trackId);if(!i)return;e.setLayerFromServer(t)?(s=this.listener)==null||s.onTrackUpdate(5,e,i):(n=this.listener)==null||n.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 s=e.auxiliaryTracks.findIndex(n=>n.trackId===i.trackId);s===-1?(e.auxiliaryTracks.push(i),this.store.addTrack(i)):(e.auxiliaryTracks[s].replaceTrack(i),this.store.addTrack(e.auxiliaryTracks[s]))}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 gr=class extends ft{constructor(t,i,r,s){super(t,i,s);this.transport=r;this.TAG="[OnDemandTrackManager]";this.processTrackInfo=(t,i,r=!0)=>{var u,p;if(t.type!=="video")return;let s=this.store.getPeerById(i);if(!s||!this.isPeerRoleSubscribed(i)){d.d(this.TAG,`no peer in store for peerId: ${i}`);return}let n=new Re(new MediaStream,this.transport.getSubscribeConnection()),o=Te.getEmptyVideoTrack();o.enabled=!t.mute;let l=new x(n,o,t.source,(u=this.store.getRoom())==null?void 0:u.disableNoneLayerRequest);l.setTrackId(t.track_id),l.peerId=s.peerId,l.logIdentifier=s.name,this.addVideoTrack(s,l),r&&((p=this.listener)==null||p.onTrackUpdate(0,s.videoTrack,s))}}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&&ve(t.videoTrack.nativeTrack)}isPeerRoleSubscribed(t){var s,n,o,l;if(!t)return!0;let i=this.store.getLocalPeer(),r=this.store.getPeerById(t);return r&&((l=(n=(s=i==null?void 0:i.role)==null?void 0:s.subscribeParams)==null?void 0:n.subscribeToRoles)==null?void 0:l.includes((o=r.role)==null?void 0:o.name))}};var Tr=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(n=>!e[n.peerId]);r.length>0&&d.d(this.TAG,`${r}`),r.forEach(n=>{var l;let o={peer_id:n.peerId,role:((l=n.role)==null?void 0:l.name)||"",info:{name:n.name,data:n.metadata||"",user_id:n.customerUserId||"",type:n.type},tracks:{},groups:[],realtime:n.realtime};this.peerManager.handlePeerLeave(o)});let s=[];i.forEach(n=>{let o=this.store.getPeerById(n.peer_id),l=Object.values(n.tracks);o&&(this.store.getPeerTracks(o.peerId).forEach(p=>{var h;n.tracks[p.trackId]||(this.removePeerTrack(o,p.trackId),(h=this.listener)==null||h.onTrackUpdate(1,p,o))}),l.forEach(p=>{this.store.getTrackById(p.track_id)||this.store.setTrackState({peerId:o.peerId,trackInfo:p})}),this.trackManager.handleTrackUpdate({peer:n,tracks:n.tracks},!1),this.peerManager.handlePeerUpdate(n)),s.push(n)}),s.length>0&&this.peerManager.handlePeerList(s)}}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 s=e.auxiliaryTracks.findIndex(n=>n.trackId===t);s>=0&&e.auxiliaryTracks.splice(s,1)}}};var L=a=>a?new Date(a):void 0;var fr=class{constructor(e,t,i){this.store=e;this.trackManager=t;this.listener=i;this.TAG="[PeerManager]";this.handlePeerList=e=>{var r,s;if(e.length===0){(r=this.listener)==null||r.onPeerUpdate(9,[]);return}let t=[],i=new Set(e.map(n=>n.peer_id));this.store.getRemotePeers().forEach(({peerId:n,fromRoomState:o})=>{!i.has(n)&&o&&this.store.removePeer(n)});for(let n of e)t.push(this.makePeer(n));(s=this.listener)==null||s.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,s,n;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)),(s=t.auxiliaryTracks)==null||s.forEach(o=>{var l;(l=this.listener)==null||l.onTrackUpdate(1,o,t)}),(n=this.listener)==null||n.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 s,n,o,l,u;let t=this.store.getPeerById(e.peer_id);if(!t&&e.realtime){t=this.makePeer(e),(s=this.listener)==null||s.onPeerUpdate(t.isHandRaised?12:14,t);return}if(t&&!t.isLocal&&!e.realtime){this.store.removePeer(t.peerId),(n=this.listener)==null||n.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),(o=this.listener)==null||o.onPeerUpdate(8,t)}let i=t.isHandRaised;t.updateGroups(e.groups);let r=(l=e.groups)==null?void 0:l.includes(He);i!==r&&((u=this.listener)==null||u.onPeerUpdate(12,t)),this.handlePeerInfoUpdate(m({peer:t},e.info))}handlePeerInfoUpdate({peer:e,name:t,data:i}){var r,s;e&&(t&&e.name!==t&&(e.updateName(t),(r=this.listener)==null||r.onPeerUpdate(10,e)),i&&e.metadata!==i&&(e.updateMetadata(i),(s=this.listener)==null||s.onPeerUpdate(11,e)))}makePeer(e){let t=this.store.getPeerById(e.peer_id);t||(t=be(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 vr=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),s=t.role;t.updateRole(r),r.name===((i=t.asRole)==null?void 0:i.name)&&delete t.asRole,this.eventBus.localRoleUpdate.publish({oldRole:s,newRole:r})}}};var Ks=(f=>(f.FLAG_SERVER_SUB_DEGRADATION="subscribeDegradation",f.FLAG_SERVER_SIMULCAST="simulcast",f.FLAG_NON_WEBRTC_DISABLE_OFFER="nonWebRTCDisableOffer",f.FLAG_PUBLISH_STATS="publishStats",f.FLAG_SUBSCRIBE_STATS="subscribeStats",f.FLAG_ON_DEMAND_TRACKS="onDemandTracks",f.FLAG_DISABLE_VIDEO_TRACK_AUTO_UNSUBSCRIBE="disableVideoTrackAutoUnsubscribe",f.FLAG_WHITEBOARD_ENABLED="whiteboardEnabled",f.FLAG_EFFECTS_SDK_ENABLED="effectsSDKEnabled",f.FLAG_VB_ENABLED="vb",f.FLAG_HIPAA_ENABLED="hipaa",f.FLAG_NOISE_CANCELLATION="noiseCancellation",f.FLAG_SCALE_SCREENSHARE_BASED_ON_PIXELS="scaleScreenshareBasedOnPixels",f.FLAG_DISABLE_NONE_LAYER_REQUEST="disableNoneLayerRequest",f))(Ks||{});var ri=(a,e,t)=>{let i=t==="qa"?_a:Da,r=new URL(i);return r.searchParams.set("endpoint",`https://${e}`),r.searchParams.set("token",a),r.toString()};var Mr=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 n;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}),s=y(m({},t),{title:e==null?void 0:e.title,attributes:e==null?void 0:e.attributes,id:r.id,url:ri(r.token,r.addr,this.store.getEnv()),token:r.token,addr:r.addr,owner:r.owner,permissions:r.permissions||[],open:!0});this.store.setWhiteboard(s),(n=this.listener)==null||n.onWhiteboardUpdate(s)})}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}handleLocalRoleUpdate(){return c(this,null,function*(){var t,i,r;let e=this.store.getWhiteboards();for(let s of e.values())if(s.url){let n=yield this.transport.signal.getWhiteboard({id:s.id}),o=this.store.getLocalPeer(),u=(o==null?void 0:o.customerUserId)===n.owner?(i=(t=o.role)==null?void 0:t.permissions.whiteboard)==null?void 0:i.includes("admin"):n.permissions.length>0,p=y(m({},s),{id:n.id,url:ri(n.token,n.addr,this.store.getEnv()),token:n.token,addr:n.addr,owner:n.owner,permissions:n.permissions,open:u});this.store.setWhiteboard(p),(r=this.listener)==null||r.onWhiteboardUpdate(p)}})}getCreateOptionsWithDefaults(e){var n;let t=Object.values(this.store.getKnownRoles()),i=[],r=[],s=[];return t.forEach(o=>{var l,u,p;(l=o.permissions.whiteboard)!=null&&l.includes("read")&&i.push(o.name),(u=o.permissions.whiteboard)!=null&&u.includes("write")&&r.push(o.name),(p=o.permissions.whiteboard)!=null&&p.includes("admin")&&s.push(o.name)}),{title:(e==null?void 0:e.title)||`${(n=this.store.getRoom())==null?void 0:n.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)||s}}};var si=class{constructor(e,t,i){this.transport=e;this.store=t;this.listener=i;this.whiteboard=new Mr(e,t,i)}setListener(e){this.listener=e,this.whiteboard.setListener(e)}createPoll(e){return c(this,null,function*(){var n,o;let t={customerID:"userid",peerID:"peerid",userName:"username"},{poll_id:i}=yield this.transport.signal.setPollInfo(y(m({},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}),s=yr(y(m({},e),{poll_id:e.id,state:"created",created_by:(n=this.store.getLocalPeer())==null?void 0:n.peerId}));s.questions=r.questions.map(({question:l,options:u,answer:p})=>y(m({},l),{options:u,answer:p})),(o=this.listener)==null||o.onPollsUpdate(0,[s])})}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(s=>{var o,l;let n=this.getQuestionInPoll(i,s.questionIndex);return n.type==="single-choice"?(s.option=s.option||((o=s.options)==null?void 0:o[0])||-1,delete s.text,delete s.options):n.type==="multiple-choice"?((l=s.options)==null||l.sort(),delete s.text,delete s.option):(delete s.option,delete s.options),s.skipped&&(delete s.option,delete s.options,delete s.text),m({duration:0,type:n.type,question:s.questionIndex},s)});yield this.transport.signal.setPollResponses({poll_id:e,responses:r})})}fetchLeaderboard(e,t,i){return c(this,null,function*(){var p,h;let r=this.store.getPoll(e);if(!r)throw new Error("Invalid poll ID - Poll not found");let s=(h=(p=this.store.getLocalPeer())==null?void 0:p.role)==null?void 0:h.permissions,n=!!(s!=null&&s.pollRead||s!=null&&s.pollWrite);if(r.anonymous||r.state!=="stopped"||!n)return{entries:[],hasNext:!1};let o=yield this.transport.signal.fetchPollLeaderboard({poll_id:r.id,count:i,offset:t}),l={avgScore:o.avg_score,avgTime:o.avg_time,votedUsers:o.voted_users,totalUsers:o.total_users,correctUsers:o.correct_users};return{entries:o.questions.map(T=>({position:T.position,totalResponses:T.total_responses,correctResponses:T.correct_responses,duration:T.duration,peer:T.peer,score:T.score})),hasNext:!o.last,summary:l}})}getPollResponses(e,t){return c(this,null,function*(){var s,n;let i=yield this.transport.signal.getPollResponses({poll_id:e.id,index:0,count:50,self:t}),r=JSON.parse(JSON.stringify(e));(s=i.responses)==null||s.forEach(({response:o,peer:l,final:u})=>{var h,T;let p=(h=e==null?void 0:e.questions)==null?void 0:h.find(g=>g.index===o.question);if(p){let g={id:o.response_id,questionIndex:o.question,option:o.option,options:o.options,text:o.text,responseFinal:u,peer:{peerid:l.peerid,userHash:l.hash,userid:l.userid,username:l.username},skipped:o.skipped,type:o.type,update:o.update},f=p.responses&&!t?[...p.responses]:[];(T=r.questions)!=null&&T[o.question-1]&&(r.questions[o.question-1].responses=[...f,g])}}),this.store.setPoll(r),(n=this.listener)==null||n.onPollsUpdate(4,[r])})}getPolls(){return c(this,null,function*(){var s,n,o;let e=yield this.transport.signal.getPollsList({count:50,state:"started"}),t=[],i=(n=(s=this.store.getLocalPeer())==null?void 0:s.role)==null?void 0:n.permissions.pollWrite,r=[...e.polls];if(i){let l=yield this.transport.signal.getPollsList({count:50,state:"created"}),u=yield this.transport.signal.getPollsList({count:50,state:"stopped"});r=[...l.polls,...r,...u.polls]}for(let l of r){let u=yield this.transport.signal.getPollQuestions({poll_id:l.poll_id,index:0,count:50}),p=yr(l),h=this.store.getPoll(l.poll_id);p.questions=u.questions.map(({question:T,options:g,answer:f},P)=>{var M,R;return y(m({},T),{options:g,answer:f,responses:(R=(M=h==null?void 0:h.questions)==null?void 0:M[P])==null?void 0:R.responses})}),t.push(p),this.store.setPoll(p)}return(o=this.listener)==null||o.onPollsUpdate(3,t),t})}createQuestionSetParams(e,t){var n,o;if(e.index){let l=(n=e.options)==null?void 0:n.map((u,p)=>y(m({},u),{index:p+1}));return{question:y(m({},e),{index:t+1}),options:l,answer:e.answer}}let i=y(m({},e),{index:t+1}),r,s=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((l,u)=>({index:u+1,text:l.text,weight:l.weight})),e.type==="single-choice"?s.option=e.options.findIndex(l=>l.isCorrectAnswer)+1||void 0:s.options=e.options.map((l,u)=>l.isCorrectAnswer?u+1:void 0).filter(l=>!!l)):(s==null||delete s.options,s==null||delete s.option),{question:i,options:r,answer:s}}getQuestionInPoll(e,t){var r;let i=(r=e==null?void 0:e.questions)==null?void 0:r.find(s=>s.index===t);if(!i)throw new Error("Invalid question index - Question not found in poll");return i}},yr=a=>{let e={userid:"customerID",peerid:"peerID",username:"userName"};return{id:a.poll_id,title:a.title,startedBy:a.started_by,createdBy:a.created_by,anonymous:a.anonymous,type:a.type,duration:a.duration,locked:a.locked,mode:a.mode?e[a.mode]:void 0,visibility:a.visibility,rolesThatCanVote:a.vote||[],rolesThatCanViewResponses:a.responses||[],state:a.state,stoppedBy:a.stopped_by,startedAt:L(a.started_at),stoppedAt:L(a.stopped_at),createdAt:L(a.created_at)}};var kr=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,r;let t=[];for(let s of e.polls){let n=this.store.getPoll(s.poll_id);if(n&&n.state==="started"){(i=this.listener)==null||i.onPollsUpdate(1,[n]);return}let o=yield this.transport.signal.getPollQuestions({poll_id:s.poll_id,index:0,count:50}),l=yr(s);l.questions=o.questions.map(({question:u,options:p,answer:h})=>y(m({},u),{options:p,answer:h})),yield this.updatePollResponses(l,!0),t.push(l),this.store.setPoll(l)}(r=this.listener)==null||r.onPollsUpdate(1,t)})}handlePollStop(e){return c(this,null,function*(){var i;let t=[];for(let r of e.polls){let s=this.store.getPoll(r.poll_id);if(s){s.state="stopped",s.stoppedAt=L(r.stopped_at),s.stoppedBy=r.stopped_by;let n=yield this.transport.signal.getPollResult({poll_id:r.poll_id});this.updatePollResult(s,n),t.push(s)}}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 s=this.store.getPoll(r.poll_id);if(!s)return;this.updatePollResult(s,r),t.push(s)}t.length>0&&((i=this.listener)==null||i.onPollsUpdate(4,t))})}updatePollResult(e,t){var i;e.result=m({},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 n,o;let s=(n=e.questions)==null?void 0:n.find(l=>l.index===r.question);s&&(s.result=m({},s.result),s.result.correctResponses=r.correct,s.result.skippedCount=r.skipped,s.result.totalResponses=r.total,(o=r.options)==null||o.forEach((l,u)=>{var h;let p=(h=s.options)==null?void 0:h[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:s,peer:n,final:o})=>{var p;let l=(p=e==null?void 0:e.questions)==null?void 0:p.find(h=>h.index===s.question);if(!l)return;let u={id:s.response_id,questionIndex:s.question,option:s.option,options:s.options,text:s.text,responseFinal:o,peer:{peerid:n.peerid,userHash:n.hash,userid:n.userid,username:n.username},skipped:s.skipped,type:s.type,update:s.update};Array.isArray(l.responses)&&l.responses.length>0?l.responses.find(({id:h})=>h===u.id)||l.responses.push(u):l.responses=[u]})})}};var Er=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,s=t?this.store.getPeerById(t):void 0,n=this.store.getLocalPeerTracks().find(l=>l.publishedTrackId===i);if(!n)return;let o=()=>{var l;(l=this.listener)==null||l.onChangeTrackStateRequest({requestedBy:s,track:n,enabled:!r})};if(r){if(n.enabled===!r)return;n.setEnabled(!r).then(o)}else o()}handleChangeTrackStateRequest(e){var u;let{type:t,source:i,value:r,requested_by:s}=e,n=s?this.store.getPeerById(s):void 0,o=!r,l=this.getTracksToBeUpdated({type:t,source:i,enabled:o});if(l.length!==0)if(o)(u=this.listener)==null||u.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,type:t,source:i,enabled:!0});else{let p=[];for(let h of l)p.push(h.setEnabled(!1));Promise.all(p).then(()=>{var h;(h=this.listener)==null||h.onChangeMultiTrackStateRequest({requestedBy:n,tracks:l,enabled:!1})})}}getTracksToBeUpdated({type:e,source:t,enabled:i}){let s=this.store.getLocalPeerTracks();return e&&(s=s.filter(n=>n.type===e)),t&&(s=s.filter(n=>n.source===t)),s.filter(n=>n.enabled!==i)}};var Pr=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;case"on-transcription-update":this.handleTranscriptionStatus([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 u,p,h,T;let{recording:t,streaming:i,transcriptions:r,session_id:s,started_at:n,name:o}=e,l=this.store.getRoom();if(!l){d.w(this.TAG,"on room state - room not present");return}l.name=o,l.rtmp.running=this.isStreamingRunning((u=i==null?void 0:i.rtmp)==null?void 0:u.state),l.rtmp.startedAt=L((p=i==null?void 0:i.rtmp)==null?void 0:p.started_at),l.rtmp.state=(h=i==null?void 0:i.rtmp)==null?void 0:h.state,l.recording.server=this.getPeerListSFURecording(t),l.recording.browser=this.getPeerListBrowserRecording(t),l.recording.hls=this.getPeerListHLSRecording(t),l.hls=this.convertHls(i==null?void 0:i.hls),l.transcriptions=this.addTranscriptionDetail(r),l.sessionId=s,l.startedAt=L(n),(T=this.listener)==null||T.onRoomUpdate("RECORDING_STATE_UPDATED",l)}addTranscriptionDetail(e){return e?e.map(t=>({state:t.state,mode:t.mode,initialised_at:L(t.initialised_at),started_at:L(t.started_at),stopped_at:L(t.stopped_at),updated_at:L(t.updated_at),error:this.toSdkError(t==null?void 0:t.error),translation:t.translation})):[]}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,s)=>{var n,o,l;r.state!=="initialised"?i.variants.push({meetingURL:r==null?void 0:r.meetingURL,url:r==null?void 0:r.url,metadata:r==null?void 0:r.metadata,playlist_type:r==null?void 0:r.playlist_type,startedAt:L((n=e==null?void 0:e.variants)==null?void 0:n[s].started_at),initialisedAt:L((o=e==null?void 0:e.variants)==null?void 0:o[s].initialised_at),state:r.state,stream_type:r==null?void 0:r.stream_type}):i.variants.push({initialisedAt:L((l=e==null?void 0:e.variants)==null?void 0:l[s].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?e.variants.some(s=>this.isStreamingRunning(s.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)}handleTranscriptionStatus(e){var i;let t=this.store.getRoom();if(!t){d.w(this.TAG,"on transcription - room not present");return}t.transcriptions=this.addTranscriptionDetail(e)||[],(i=this.listener)==null||i.onRoomUpdate("TRANSCRIPTION_STATE_UPDATED",t)}convertHls(e){var r;if(e!=null&&e.variants&&e.variants.length>0?e.variants.some(s=>s.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(s=>{i.variants.push({meetingURL:s==null?void 0:s.meeting_url,url:s==null?void 0:s.url,metadata:s==null?void 0:s.metadata,playlist_type:s==null?void 0:s.playlist_type,startedAt:L(s==null?void 0:s.started_at),initialisedAt:L(s==null?void 0:s.initialised_at),state:s.state,stream_type:s==null?void 0:s.stream_type})}),i}getHLSRecording(e){var r,s;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:!!((s=e==null?void 0:e.hls_recording)!=null&&s.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,s;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:(s=t==null?void 0:t.config)==null?void 0:s.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 s;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"),(s=this.listener)==null||s.onRoomUpdate(r,t)}updateRTMPStatus(e){var r,s;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)},(s=this.listener)==null||s.onRoomUpdate("RTMP_STREAMING_STATE_UPDATED",t)}toSdkError(e){if(!(e!=null&&e.code))return;let t=e.message||"error in streaming/recording",i=new k(e.code,"ServerErrors","NONE",t,t);return d.e(this.TAG,"error in streaming/recording",i),i}};var br=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 Ir=class{constructor(e,t,i){this.store=e;this.transport=t;this.listener=i}handleNotification(e,t){e==="on-whiteboard-update"&&this.handleWhiteboardUpdate(t)}handleWhiteboardUpdate(e){return c(this,null,function*(){var o;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),s=e.state==="open",n={id:e.id,title:e.title,attributes:e.attributes};if(n.open=r?i==null?void 0:i.open:s,n.owner=n.open?e.owner:void 0,n.open)if(r)n.url=i==null?void 0:i.url,n.token=i==null?void 0:i.token,n.addr=i==null?void 0:i.addr,n.permissions=i==null?void 0:i.permissions;else{let l=yield this.transport.signal.getWhiteboard({id:e.id});n.url=ri(l.token,l.addr,this.store.getEnv()),n.token=l.token,n.addr=l.addr,n.permissions=l.permissions,n.open=l.permissions.length>0}this.store.setWhiteboard(n),(o=this.listener)==null||o.onWhiteboardUpdate(n)})}};var Ar=class{constructor(e,t,i,r,s,n){this.store=e;this.transport=i;this.listener=r;this.audioListener=s;this.connectionQualityListener=n;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 o=this.transport.isFlagEnabled("onDemandTracks");this.trackManager=o?new gr(this.store,t,this.transport,this.listener):new ft(this.store,t,this.listener),this.peerManager=new fr(this.store,this.trackManager,this.listener),this.peerListManager=new Tr(this.store,this.peerManager,this.trackManager,this.listener),this.broadcastManager=new mr(this.listener),this.policyChangeManager=new vr(this.store,t),this.requestManager=new Er(this.store,this.listener),this.activeSpeakerManager=new hr(this.store,this.listener,this.audioListener),this.connectionQualityManager=new Sr(this.store,this.connectionQualityListener),this.roomUpdateManager=new Pr(this.store,this.listener),this.sessionMetadataManager=new br(this.store,this.listener),this.pollsManager=new kr(this.store,this.transport,this.listener),this.whiteboardManager=new Ir(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 s,n;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"&&(s=window.HMS)!=null&&s.ON_SFU_STATS&&typeof((n=window.HMS)==null?void 0:n.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;case"node-info":this.transport.setSFUNodeId(t.sfu_node_id);break;default:break}}};var Rr=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}),s=L(r);return{value:i,updatedAt:s}})}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 Hr=class{constructor(e,t,i="",r="",s="https://prod-init.100ms.live/init",n=!1,o){this.authToken=e;this.peerId=t;this.peerName=i;this.data=r;this.endpoint=s;this.autoSubscribeVideo=n;this.iceServers=o}};var Z=(s=>(s[s.ConnectFailed=0]="ConnectFailed",s[s.SignalDisconnect=1]="SignalDisconnect",s[s.JoinWSMessageFailed=2]="JoinWSMessageFailed",s[s.PublishIceConnectionFailed=3]="PublishIceConnectionFailed",s[s.SubscribeIceConnectionFailed=4]="SubscribeIceConnectionFailed",s))(Z||{}),Gn={0:[],1:[],2:[1],3:[1],4:[1]};var ai=(o=>(o.Disconnected="Disconnected",o.Connecting="Connecting",o.Joined="Joined",o.Preview="Preview",o.Failed="Failed",o.Reconnecting="Reconnecting",o.Leaving="Leaving",o))(ai||{});var Cr=class{constructor(e){this.promise=new Promise((t,i)=>{this.resolve=t,this.reject=i,e(t,i)})}};var Lr=class{constructor(e,t){this.onStateChange=e;this.sendEvent=t;this.TAG="[RetryScheduler]";this.inProgress=new Map;this.retryTaskIds=[]}schedule(o){return c(this,arguments,function*({category:e,error:t,task:i,originalState:r,maxRetryTime:s=6e4,changeState:n=!0}){yield this.scheduleTask({category:e,error:t,changeState:n,task:i,originalState:r,maxRetryTime:s,failedAt:Date.now()})})}reset(){this.retryTaskIds.forEach(e=>clearTimeout(e)),this.retryTaskIds=[],this.inProgress.clear()}isTaskInProgress(e){return!!this.inProgress.get(e)}scheduleTask(u){return c(this,arguments,function*({category:e,error:t,changeState:i,task:r,originalState:s,failedAt:n,maxRetryTime:o=6e4,failedRetryCount:l=0}){if(d.d(this.TAG,"schedule: ",{category:Z[e],error:t}),l===0){let M=this.inProgress.get(e);if(M){d.d(this.TAG,`schedule: Already a task for ${Z[e]} scheduled, waiting for its completion`),yield M.promise;return}let R=new Cr(($,ce)=>{});this.inProgress.set(e,R),this.sendEvent(t,e)}let p=!1,h=Gn[e];for(let M in h){let R=h[parseInt(M)];try{let $=this.inProgress.get(R);$&&(d.d(this.TAG,`schedule: Suspending retry task of ${Z[e]}, waiting for ${Z[R]} to recover`),yield $.promise,d.d(this.TAG,`schedule: Resuming retry task ${Z[e]} as it's dependency ${Z[R]} is recovered`))}catch($){d.d(this.TAG,`schedule: Stopping retry task of ${Z[e]} as it's dependency ${Z[R]} failed to recover`),p=!0;break}}let T=M=>{if(this.inProgress.delete(e),this.sendEvent(M,e),this.reset(),i)this.onStateChange("Failed",M);else throw M},g=Date.now()-n;if(g>=o||p)return t.description+=`. [${Z[e]}] Could not recover after ${g} milliseconds`,p&&(t.description+=` Could not recover all of it's required dependencies - [${h.map(M=>Z[M]).toString()}]`),t.isTerminal=!0,T(t);i&&this.onStateChange("Reconnecting",t);let f=this.getDelayForRetryCount(e,l);d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Scheduling retry task in ${f}ms`);let P;try{P=yield this.setTimeoutPromise(r,f)}catch(M){P=!1;let R=M;if(R.isTerminal)return d.e(this.TAG,`[${Z[e]}] Un-caught terminal exception ${R.name} in retry-task`,M),T(R);d.w(this.TAG,`[${Z[e]}] Un-caught exception ${R.name} in retry-task, initiating retry`,M)}if(P){let M=this.inProgress.get(e);this.inProgress.delete(e),M==null||M.resolve(l),i&&this.inProgress.size===0&&this.onStateChange(s),d.d(this.TAG,`schedule: [${Z[e]}] [failedRetryCount=${l}] Recovered \u267B\uFE0F after ${g}ms`)}else yield this.scheduleTask({category:e,error:t,changeState:i,task:r,originalState:s,maxRetryTime:o,failedAt:n,failedRetryCount:l+1})})}getDelayForRetryCount(e,t=0){let i=e===2?Math.random()*2:Math.random(),r=0;return e===2?r=2+i:e===1?r=1:e===3&&t>0&&(r=Math.min(ra(2,t-1),4)+i),r*1e3}setTimeoutPromise(e,t){return c(this,null,function*(){return new Promise((i,r)=>{let s=window.setTimeout(()=>c(this,null,function*(){try{let n=yield e();n&&this.retryTaskIds.splice(this.retryTaskIds.indexOf(s),1),i(n)}catch(n){r(n)}}),t);this.retryTaskIds.push(s)})})}};var wr=class extends Ve{constructor(){super(100);this.localStorage=new Ee("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 H(i);super.enqueue(r)})}};var Dr=class{constructor(){this.TAG="[AnalyticsTransport]";this.eventCount=0;this.lastResetTime=Date.now();this.MAX_EVENTS_PER_MINUTE=200;this.RESET_INTERVAL_MS=6e4}checkRateLimit(){let e=Date.now();if(e-this.lastResetTime>=this.RESET_INTERVAL_MS&&(this.eventCount=0,this.lastResetTime=e),this.eventCount>=this.MAX_EVENTS_PER_MINUTE)throw new Error("Too many events being sent, please check the implementation.");this.eventCount++}sendEvent(e){try{this.checkRateLimit()}catch(t){throw d.w(this.TAG,"Rate limit exceeded",t),t}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):Le.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 _r=class extends Dr{constructor(t){super();this.transportProvider=t;this.failedEvents=new wr}};var vt=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.start()}start(){this.shouldSendEvent||(this.stop(),this.shouldSendEvent=!0,this.eventBus.statsUpdate.subscribe(this.handleStatsUpdate.bind(this)),this.startLoop().catch(e=>d.e("[StatsAnalytics]",e.message)))}stop(){this.shouldSendEvent&&this.sendEvent(),this.eventBus.statsUpdate.unsubscribe(this.handleStatsUpdate.bind(this)),this.shouldSendEvent=!1}startLoop(){return c(this,null,function*(){for(;this.shouldSendEvent;)yield te(this.pushInterval*1e3),this.sendEvent()})}sendEvent(){this.trackAnalytics.forEach(e=>{e.clearSamples()})}cleanTrackAnalyticsAndCreateSample(e){this.trackAnalytics.forEach(t=>{!this.store.hasTrack(t.track)&&!(t.samples.length>0)&&this.trackAnalytics.delete(t.track_id)}),e&&this.trackAnalytics.forEach(t=>{t.createSample()})}},Mt=class{constructor({track:e,ssrc:t,rid:i,kind:r,sampleWindowSize:s}){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=s}pushTempStat(e){this.tempStats.push(e)}createSample(){this.tempStats.length!==0&&(this.samples.push(this.collateSample()),this.prevLatestStat=this.getLatestStat(),this.tempStats.length=0)}clearSamples(){this.samples.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!==void 0?t?Math.round(r):r:void 0}calculateDifferenceForSample(e){var r;let t=Number((r=this.prevLatestStat)==null?void 0:r[e])||0;return(Number(this.getLatestStat()[e])||0)-t}calculateDifferenceAverage(e,t=!0){let i=this.calculateDifferenceForSample(e)/this.tempStats.length;return t?Math.round(i):i}calculateInstancesOfHigh(e,t){if(typeof this.getLatestStat()[e]=="number")return this.tempStats.reduce((r,s)=>r+((s[e]||0)>t?1:0),0)}},Nr=(a,e)=>a&&e&&(a.frameWidth!==e.frameWidth||a.frameHeight!==e.frameHeight),Or=(a,e)=>a&&e&&a.enabled!==e.enabled,ni=a=>Object.entries(a).filter(([,e])=>e!==void 0).reduce((e,[t,i])=>(e[t]=i,e),{});var xr=class{constructor(){this.worstState=void 0;this.TAG="[CPUPressureMonitor]";this.stateRanking={nominal:0,fair:1,serious:2,critical:3};this.init()}init(){return c(this,null,function*(){if(!("PressureObserver"in window)){d.d(this.TAG,"PressureObserver API not available");return}try{this.observer=new PressureObserver(e=>{if(e.length>0){let t=e[e.length-1].state;this.updateWorstState(t)}}),yield this.observer.observe("cpu",{sampleInterval:1e4}),this.worstState="nominal",d.d(this.TAG,"CPU pressure monitoring started")}catch(e){d.e(this.TAG,"Failed to initialize CPU pressure monitoring",e)}})}updateWorstState(e){if(this.worstState===void 0){this.worstState=e;return}this.stateRanking[e]>this.stateRanking[this.worstState]&&(this.worstState=e,d.d(this.TAG,`New worst CPU state: ${this.worstState}`))}getWorstState(){return this.worstState}resetWorstState(){this.worstState!==void 0&&(this.worstState="nominal",d.d(this.TAG,"CPU worst state reset to nominal"))}stop(){if(this.observer)try{this.observer.disconnect(),d.d(this.TAG,"CPU pressure monitoring stopped")}catch(e){d.e(this.TAG,"Error stopping CPU pressure monitoring",e)}}};var oi=class extends vt{constructor(t,i,r,s){super(t,i,r,s);this.trackAnalytics=new Map;this.cpuPressureMonitor=new xr}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:30}}sendEvent(){this.eventBus.analytics.publish(v.publishStats(this.toAnalytics())),super.sendEvent()}stop(){var t;super.stop(),(t=this.cpuPressureMonitor)==null||t.stop()}handleStatsUpdate(t){let i=!1,r=t.getLocalTrackStats();Object.keys(r).forEach(s=>{let n=r[s],o=this.store.getLocalPeerTracks().find(l=>l.getTrackIDBeingSent()===s);Object.keys(n).forEach(l=>{var g,f,P;let u=n[l];if(!o)return;let p=this.getTrackIdentifier(o.trackId,u),h=y(m({},u),{availableOutgoingBitrate:(f=(g=t.getLocalPeerStats())==null?void 0:g.publish)==null?void 0:f.availableOutgoingBitrate});if(p&&this.trackAnalytics.has(p))(P=this.trackAnalytics.get(p))==null||P.pushTempStat(h);else if(o){let M=new js({track:o,sampleWindowSize:this.sampleWindowSize,rid:u.rid,ssrc:u.ssrc.toString(),kind:u.kind,cpuPressureMonitor:this.cpuPressureMonitor});M.pushTempStat(h),this.trackAnalytics.set(this.getTrackIdentifier(o.trackId,u),M)}let T=this.trackAnalytics.get(p);T!=null&&T.shouldCreateSample()&&(i=!0)})}),this.cleanTrackAnalyticsAndCreateSample(i)}getTrackIdentifier(t,i){return i.rid?`${t}:${i.rid}`:t}},js=class extends Mt{constructor(t){super(t);this.samples=[];this.getQualityLimitation=t=>{let i=t.qualityLimitationDurations;return i&&{bandwidth_sec:i.bandwidth,cpu_sec:i.cpu,other_sec:i.other}};this.getSourceStats=t=>{if(!t.sourceStatsAvailable)return{};let i=t.sourceFrameHeight?{height_px:t.sourceFrameHeight,width_px:t.sourceFrameWidth}:void 0,r=this.calculateDifferenceForSample("sourceFrames"),s=this.calculateDifferenceForSample("framesEncoded"),n=r&&s?Math.max(0,r-s):void 0;return{source_resolution:i,source_avg_fps:this.calculateAverage("sourceFramesPerSecond"),source_total_frames:r,source_total_frames_dropped:n}};this.collateSample=()=>{var p,h,T,g,f,P;let t=this.getFirstStat(),i=this.getLatestStat(),r=i.frameHeight?{height_px:i.frameHeight,width_px:i.frameWidth}:void 0,s=this.calculateAverage("jitter",!1),n=this.calculateAverage("roundTripTime",!1),o=(p=this.cpuPressureMonitor)==null?void 0:p.getWorstState();(h=this.cpuPressureMonitor)==null||h.resetWorstState();let l=(g=(T=this.track).getMediaTrackSettings)==null?void 0:g.call(T),u=(P=(f=this.track).getPluginsMetrics)==null?void 0:P.call(f);return ni(m({timestamp:Date.now(),sample_start_ts:t.timestamp,sample_end_ts:i.timestamp,sample_duration_ms:i.timestamp-t.timestamp,avg_available_outgoing_bitrate_bps:this.calculateAverage("availableOutgoingBitrate"),avg_bitrate_bps:this.calculateAverage("bitrate"),avg_fps:this.calculateAverage("framesPerSecond"),total_packets_lost:i.packetsLost,total_packets_sent:i.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:s?Math.round(s*1e3):void 0,avg_round_trip_time_ms:n?Math.round(n*1e3):void 0,total_quality_limitation:this.getQualityLimitation(i),resolution:r,cpu_pressure_state:o,track_settings:l,effects_metrics:u&&Object.keys(u).length>0?u:void 0},this.getSourceStats(i)))};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===30||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples});this.cpuPressureMonitor=t.cpuPressureMonitor}};var ci=class extends vt{constructor(){super(...arguments);this.trackAnalytics=new Map}toAnalytics(){var r,s;let t=[],i=[];return this.trackAnalytics.forEach(n=>{n.track.type==="audio"?t.push(n.toAnalytics()):n.track.type==="video"&&i.push(n.toAnalytics())}),{audio:t,video:i,joined_at:(s=(r=this.store.getRoom())==null?void 0:r.joinedAt)==null?void 0:s.getTime(),sequence_num:this.sequenceNum++,max_window_sec:10}}sendEvent(){this.eventBus.analytics.publish(v.subscribeStats(this.toAnalytics())),super.sendEvent()}handleStatsUpdate(t){let i=t.getAllRemoteTracksStats(),r=!1;Object.keys(i).forEach(s=>{var f,P;let n=this.store.getTrackById(s),o=i[s],l=(f=this.trackAnalytics.get(s))==null?void 0:f.getLatestStat(),p=((M,R)=>{let $=(R==null?void 0:R.jitterBufferDelay)||0,ce=(R==null?void 0:R.jitterBufferEmittedCount)||0,B=((M==null?void 0:M.jitterBufferDelay)||0)-$,de=((M==null?void 0:M.jitterBufferEmittedCount)||0)-ce;return de>0?B*1e3/de:(R==null?void 0:R.calculatedJitterBufferDelay)||0})(o,l),h=this.calculateAvSyncForStat(o,t),T=y(m({},o),{calculatedJitterBufferDelay:p,avSync:h});if(o.kind==="video"){let M=n.getPreferredLayerDefinition();T.expectedFrameHeight=M==null?void 0:M.resolution.height,T.expectedFrameWidth=M==null?void 0:M.resolution.width}if(this.trackAnalytics.has(s))(P=this.trackAnalytics.get(s))==null||P.pushTempStat(T);else if(n){let M=new Qs({track:n,sampleWindowSize:this.sampleWindowSize,ssrc:o.ssrc.toString(),kind:o.kind});M.pushTempStat(T),this.trackAnalytics.set(s,M)}let g=this.trackAnalytics.get(s);g!=null&&g.shouldCreateSample()&&(r=!0)}),this.cleanTrackAnalyticsAndCreateSample(r)}calculateAvSyncForStat(t,i){if(!t.peerID||!t.estimatedPlayoutTimestamp||t.kind!=="video")return;let r=this.store.getPeerById(t.peerID),s=r==null?void 0:r.audioTrack,n=r==null?void 0:r.videoTrack;if(!(s&&n&&s.enabled&&n.enabled))return Ot;let l=i.getRemoteTrackStats(s.trackId);if(!l)return Ot;if(l.estimatedPlayoutTimestamp)return l.estimatedPlayoutTimestamp-t.estimatedPlayoutTimestamp}},Qs=class extends Mt{constructor(){super(...arguments);this.samples=[];this.collateSample=()=>{let t=this.getLatestStat(),i=this.getFirstStat(),r={timestamp:Date.now(),sample_start_ts:i.timestamp,sample_end_ts:t.timestamp,sample_duration_ms:t.timestamp-i.timestamp,total_pli_count:this.calculateDifferenceForSample("pliCount"),total_nack_count:this.calculateDifferenceForSample("nackCount"),avg_jitter_buffer_delay:this.calculateAverage("calculatedJitterBufferDelay",!1),avg_bitrate_bps:this.calculateAverage("bitrate")};if(t.kind==="video")return ni(y(m({},r),{avg_av_sync_ms:this.calculateAvgAvSyncForSample(),avg_frames_received_per_sec:this.calculateDifferenceAverage("framesReceived"),avg_frames_dropped_per_sec:this.calculateDifferenceAverage("framesDropped"),avg_frames_decoded_per_sec:this.calculateDifferenceAverage("framesDecoded"),frame_width:this.calculateAverage("frameWidth"),frame_height:this.calculateAverage("frameHeight"),expected_frame_width:this.calculateAverage("expectedFrameWidth"),expected_frame_height:this.calculateAverage("expectedFrameHeight"),pause_count:this.calculateDifferenceForSample("pauseCount"),pause_duration_seconds:this.calculateDifferenceForSample("totalPausesDuration"),freeze_count:this.calculateDifferenceForSample("freezeCount"),freeze_duration_seconds:this.calculateDifferenceForSample("totalFreezesDuration")}));{let s=(t.concealedSamples||0)-(t.silentConcealedSamples||0)-((i.concealedSamples||0)-(i.silentConcealedSamples||0));return ni(y(m({},r),{audio_level:this.calculateInstancesOfHigh("audioLevel",.05),audio_concealed_samples:s,audio_total_samples_received:this.calculateDifferenceForSample("totalSamplesReceived"),audio_concealment_events:this.calculateDifferenceForSample("concealmentEvents"),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")}))}};this.shouldCreateSample=()=>{let t=this.tempStats.length,i=this.tempStats[t-1],r=this.tempStats[t-2];return t===10||Or(i,r)||i.kind==="video"&&Nr(i,r)};this.toAnalytics=()=>({track_id:this.track_id,ssrc:this.ssrc,source:this.source,rid:this.rid,samples:this.samples})}calculateAvgAvSyncForSample(){let i=this.tempStats.map(r=>r.avSync).filter(r=>r!==void 0&&r!==Ot);return i.length===0?Ot:i.reduce((r,s)=>r+s,0)/i.length}};var yt=(t=>(t[t.Publish=0]="Publish",t[t.Subscribe=1]="Subscribe",t))(yt||{});var di=We(require("sdp-transform"));function $n(a,e){var r;let t=di.parse(a.sdp);if(!((r=t.origin)!=null&&r.username.startsWith("mozilla")))return a;let i=e?Array.from(e.values()):[];return t.media.forEach(s=>{var l,u,p;let n=(l=s.msid)==null?void 0:l.split(" ")[0],o=(u=i.find(h=>h.type===s.type&&h.stream_id===n))==null?void 0:u.track_id;o&&(s.msid=(p=s.msid)==null?void 0:p.replace(/\s(.+)/,` ${o}`))}),{type:a.type,sdp:di.write(t)}}function Wn(a,e){var s;if(!(a!=null&&a.sdp)||!e)return;let i=di.parse(a.sdp).media.find(n=>W(n.mid)&&parseInt(n.mid)===parseInt(e));return(s=i==null?void 0:i.msid)==null?void 0:s.split(" ")[1]}function qn(a){return a.sdp.includes("usedtx=1")?a:{type:a.type,sdp:a.sdp.replace("useinbandfec=1","useinbandfec=1;usedtx=1")}}var we="[HMSConnection]",et=class{constructor(e,t){this.candidates=new Array;this.localDescriptionEpoch=0;this.role=e,this.signal=t}get iceConnectionState(){return this.nativeConnection.iceConnectionState}get connectionState(){return this.nativeConnection.connectionState}get signalingState(){return this.nativeConnection.signalingState}get action(){return this.role===0?"PUBLISH":"SUBSCRIBE"}setSfuNodeId(e){this.sfuNodeId=e}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(we,`[role=${this.role}] createOffer offer=${JSON.stringify(i,null,1)}`),qn($n(i,e))}catch(i){throw S.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(we,`[role=${this.role}] createAnswer answer=${JSON.stringify(t,null,1)}`),t}catch(t){throw S.WebrtcErrors.CreateAnswerFailed(this.action,t.message)}})}isStagingLocalDescription(e){return this.localDescriptionEpoch===e}setLocalDescription(e){return c(this,null,function*(){let t=++this.localDescriptionEpoch;try{d.d(we,`[role=${this.role}] setLocalDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setLocalDescription(e)}catch(i){throw S.WebrtcErrors.SetLocalDescriptionFailed(this.action,i.message)}return t})}setRemoteDescription(e){return c(this,null,function*(){try{d.d(we,`[role=${this.role}] setRemoteDescription description=${JSON.stringify(e,null,1)}`),yield this.nativeConnection.setRemoteDescription(e)}catch(t){throw S.WebrtcErrors.SetRemoteDescriptionFailed(this.action,t.message)}})}addIceCandidate(e){return c(this,null,function*(){if(this.nativeConnection.signalingState==="closed"){d.d(we,`[role=${this.role}] addIceCandidate signalling state closed`);return}d.d(we,`[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()}handleSelectedIceCandidatePairs(){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 s=t.transport.iceTransport,n=()=>{typeof s.getSelectedCandidatePair=="function"&&(this.selectedCandidatePair=s.getSelectedCandidatePair(),this.selectedCandidatePair&&(this.observer.onSelectedCandidatePairChange(this.selectedCandidatePair),d.d(we,`${yt[this.role]} connection`,`selected ${i||"unknown"} candidate pair`,JSON.stringify(this.selectedCandidatePair,null,2))))};typeof s.onselectedcandidatepairchange=="function"&&(s.onselectedcandidatepairchange=n),n()}})}catch(e){d.w(we,`Error in logging selected ice candidate pair for ${yt[this.role]} connection`,e)}}removeTrack(e){this.nativeConnection.signalingState!=="closed"&&this.nativeConnection.removeTrack(e)}setMaxBitrateAndFramerate(e,t){return c(this,null,function*(){let i=(t==null?void 0:t.maxBitrate)||e.settings.maxBitrate,r=e instanceof q&&e.settings.maxFramerate,s=this.getSenders().find(n=>{var o;return((o=n==null?void 0:n.track)==null?void 0:o.id)===e.getTrackIDBeingSent()});if(s){let n=s.getParameters();n.encodings.length===1&&(i&&(n.encodings[0].maxBitrate=i*1e3),r&&(n.encodings[0].maxFramerate=r)),yield s.setParameters(n)}else d.w(we,`no sender found to setMaxBitrate for track - ${e.trackId}, sentTrackId - ${e.getTrackIDBeingSent()}`)})}getStats(){return c(this,null,function*(){return yield this.nativeConnection.getStats()})}close(){this.nativeConnection.close()}getReceivers(){return this.nativeConnection.getReceivers()}};var li=class extends et{constructor(t,i,r){super(0,t);this.TAG="[HMSPublishConnection]";this.observer=r,this.nativeConnection=new RTCPeerConnection(i),this.channel=this.nativeConnection.createDataChannel(Ii,{protocol:"SCTP"}),this.channel.onerror=s=>d.e(this.TAG,`publish data channel onerror ${s}`,s),this.nativeConnection.onicecandidate=({candidate:s})=>{s&&(this.observer.onIceCandidate(s),t.trickle(this.role,s))},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 s;this.observer.onDTLSTransportStateChange((s=this.nativeConnection.sctp)==null?void 0:s.transport.state)},this.nativeConnection.sctp.transport.onerror=s=>{var n;this.observer.onDTLSTransportError(new Error((n=s==null?void 0:s.error)==null?void 0:n.errorDetail)||"DTLS Transport failed")})}}close(){super.close(),this.channel.close()}initAfterJoin(){this.nativeConnection.onnegotiationneeded=()=>c(this,null,function*(){d.d(this.TAG,"onnegotiationneeded"),yield this.observer.onRenegotiationNeeded()})}};var jn=We(require("eventemitter2")),Jn=require("uuid");var ui=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 Kn=(a,e)=>`${a}:${e}`,pi=class extends et{constructor(t,i,r,s,n){super(1,t);this.isFlagEnabled=r;this.eventBus=n;this.TAG="[HMSSubscribeConnection]";this.remoteStreams=new Map;this.MAX_RETRIES=3;this.RESPONSE_TIMEOUT=1e4;this.UNPROVEN_CHANNEL_TIMEOUT=500;this.channelProven=!1;this.pendingMessageQueue=[];this.latestRequestPerState=new Map;this.closed=!1;this.pendingAborts=new Set;this.eventEmitter=new jn.default({maxListeners:60});this.abortOnClose=t=>c(this,null,function*(){if(this.closed)throw t.catch(()=>{}),t.cancel("connection closed"),Error("Subscribe connection closed");let i,r=new Promise((s,n)=>{i=n});this.pendingAborts.add(i);try{return yield Promise.race([t,r])}finally{this.pendingAborts.delete(i),t.cancel("request settled")}});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,r)=>c(this,null,function*(){let s=()=>this.latestRequestPerState.get(r)!==i,n=()=>(d.d(this.TAG,`Dropping ${i} - ${this.closed?"closed":"superseded"}`,t),{id:i,dropped:!0}),o,l,u=!1;for(let p=0;p<this.MAX_RETRIES;p++){o=void 0;let h=!1,T=!1;if(s())return n();try{if(yield this.waitForChannelOpen(),s())return n();this.apiChannel.send(t),h=!0;let f=!u;u=!0,T=f&&!this.channelProven,o=yield this.waitForResponse(i,f)}catch(f){if(l=f,d.w(this.TAG,`Attempt failed for ${i}`,{request:t,try:p+1,error:f}),this.closed)break;s()||this.publishRequestEvent(v.subscribeRequestRetry,r,{attempt:p,unproven:T,sent:h});continue}let g=o.error;if(g){if(g.code===404)return d.d(this.TAG,`Track not found ${i}`,{request:t,try:p+1,error:g}),o;if(d.d(this.TAG,`Failed sending ${i}`,{request:t,try:p+1,error:g}),!(Math.floor(g.code/100)===5||g.code===429)){if(s())return n();throw Error(`code=${g.code}, message=${g.message} - ${i} not retried`)}if(p<this.MAX_RETRIES-1){let P=(2+Math.random()*2)*1e3;yield Fe(P)}}else break}if(o!=null&&o.error){if(s())return n();throw Error(`code=${o.error.code}, message=${o.error.message} - ${i} after ${this.MAX_RETRIES} tries`)}if(o)return o;if(s()||this.closed)return n();throw this.publishRequestEvent(v.subscribeRequestUnanswered,r,{attempts:this.MAX_RETRIES}),Error(`No response from SFU for ${i} after ${this.MAX_RETRIES} tries - ${t}`,{cause:l})});this.waitForChannelOpen=()=>c(this,null,function*(){var t;((t=this.apiChannel)==null?void 0:t.readyState)!=="open"&&(yield this.abortOnClose(this.eventEmitter.waitFor("open",{timeout:this.RESPONSE_TIMEOUT})))});this.waitForResponse=(t,i)=>c(this,null,function*(){let r=i&&!this.channelProven,s=yield this.abortOnClose(this.eventEmitter.waitFor("message",{filter:o=>o.includes(t),timeout:r?this.UNPROVEN_CHANNEL_TIMEOUT:this.RESPONSE_TIMEOUT})),n=JSON.parse(s[0]);return d.d(this.TAG,`response for ${t} -`,JSON.stringify(n,null,2)),n});this.observer=s,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===Ii&&(this.channelProven=!1,this.apiChannel=new ui(t.channel,{onMessage:i=>{this.channelProven=!0,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.observer.onIceCandidate(t.candidate),this.signal.trickle(this.role,t.candidate))},this.nativeConnection.ontrack=t=>{var p;let i=t.streams[0],r=i.id;if(!this.remoteStreams.has(r)){let h=new Re(i,this);this.remoteStreams.set(r,h)}i.addEventListener("removetrack",h=>{if(h.track.id!==t.track.id)return;let T=s.tracks.findIndex(g=>{var f;return g.nativeTrack.id===h.track.id&&t.transceiver.mid===((f=g.transceiver)==null?void 0:f.mid)});if(T>=0){let g=s.tracks[T];this.observer.onTrackRemove(g),s.tracks.splice(T,1),s.tracks.length===0&&this.remoteStreams.delete(r)}});let s=this.remoteStreams.get(r),n=t.track.kind==="audio",o=n?le:x,l=n?new o(s,t.track):new o(s,t.track,void 0,this.isFlagEnabled("disableNoneLayerRequest"));t.track.kind==="video"&&s.setVideoLayerLocally("none","addTrack","subscribeConnection"),l.transceiver=t.transceiver;let u=Wn(this.remoteDescription,(p=t.transceiver)==null?void 0:p.mid);u&&l.setSdpTrackId(u),s.tracks.push(l),this.observer.onTrackAdd(l)}}cancelPendingRequest(t,i){this.latestRequestPerState.delete(Kn(t,i))}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){return c(this,null,function*(){let i=(0,Jn.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:i,dropped:!0};let r=JSON.stringify(m({id:i,jsonrpc:"2.0"},t)),s=Kn(t.method,t.params.track_id);this.latestRequestPerState.set(s,i);try{return yield this.sendMessage(r,i,s)}finally{this.latestRequestPerState.get(s)===i&&this.latestRequestPerState.delete(s)}})}close(){var t;this.closed=!0,super.close(),(t=this.apiChannel)==null||t.close(),this.pendingAborts.forEach(i=>i(Error("Subscribe connection closed"))),this.pendingAborts.clear()}publishRequestEvent(t,i,r){var n;let s=i.indexOf(":");(n=this.eventBus)==null||n.analytics.publish(t(y(m({},r),{method:i.slice(0,s),trackId:i.slice(s+1)})))}};var Qn=(a,e)=>!e||e.length===0?a:e.map(i=>({urls:i.urls,credentialType:"password",credential:i.password,username:i.userName}));var Br="[InitService]",hi=class{static handleError(e,t){switch(e.status){case 404:throw S.APIErrors.EndpointUnreachable("INIT",t.message||e.statusText);case 200:break;default:throw S.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:s="",iceServers:n}){d.d(Br,`fetchInitConfig: initEndpoint=${r} token=${e} peerId=${t} region=${s} `);let l=jd(r,t,i,s);try{let u=yield fetch(l,{headers:{Authorization:`Bearer ${e}`}});try{let p=yield u.clone().json();return this.handleError(u,p),d.d(Br,`config is ${JSON.stringify(p,null,2)}`),Jd(p,n)}catch(p){let h=yield u.text();throw d.e(Br,"json error",p.message,h),p instanceof k?p:S.APIErrors.ServerErrors(u.status,"INIT",p.message)}}catch(u){let p=u;throw["Failed to fetch","NetworkError","ECONNRESET"].some(h=>p.message.includes(h))?S.APIErrors.EndpointUnreachable("INIT",p.message):p}})}};function jd(a,e,t,i){try{let r=new URL("/init",a);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 s=r;throw d.e(Br,s.name,s.message),s}}function Jd(a,e){var t;return y(m({},a),{rtcConfiguration:y(m({},a.rtcConfiguration),{iceServers:Qn((t=a.rtcConfiguration)==null?void 0:t.ice_servers,e)})})}var zn=require("uuid");var mi=class{constructor(e){this.TAG="[SIGNAL]: ";this.pongResponseTimes=new Ve(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}setSfuNodeId(e){this.sfuNodeId=e}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 s;let i=(0,zn.v4)(),r={method:e,params:t,id:i,jsonrpc:"2.0"};(s=this.socket)==null||s.send(JSON.stringify(r));try{return yield new Promise((o,l)=>{this.callbacks.set(i,{resolve:o,reject:l,metadata:{method:e}})})}catch(n){if(n instanceof k)throw n;let o=n;throw S.WebsocketMethodErrors.ServerErrors(Number(o.code),Yr(e),o.message)}})}notify(e,t){var r,s;let i={method:e,params:t};((r=this.socket)==null?void 0:r.readyState)===WebSocket.OPEN&&((s=this.socket)==null||s.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 s=()=>{d.e(this.TAG,"Error from websocket"),r=!0,i(S.WebSocketConnectionErrors.FailedToConnect("JOIN","Error opening websocket connection"))};this.onCloseHandler=o=>{d.w(`Websocket closed code=${o.code}`),r?this.setIsConnected(!1,`code: ${o.code}${o.code!==1e3?", unexpected websocket close":""}`):(r=!0,i(S.WebSocketConnectionErrors.AbnormalClose("JOIN",`Error opening websocket connection - websocket closed unexpectedly with code=${o.code}`)))},this.socket.addEventListener("error",s);let n=()=>{var o,l;r=!0,t(),this.setIsConnected(!0),this.id++,(o=this.socket)==null||o.removeEventListener("open",n),(l=this.socket)==null||l.removeEventListener("error",s),this.pingPongLoop(this.id)};this.socket.addEventListener("open",n),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,s,n,o){return c(this,null,function*(){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("JOIN","Failed to send join over WS connection");let l={name:e,disableVidAutoSub:i,data:t,offer:o,server_sub_degrade:r,simulcast:s,onDemandTracks:n},u=yield this.internalCall("join",l);return this.isJoinCompleted=!0,this.pendingTrickle.forEach(({target:p,candidate:h})=>this.trickle(p,h)),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,sfu_node_id:this.sfuNodeId}):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),sfu_node_id:this.sfuNodeId})})}answer(e){this.notify("answer",{desc:e,sfu_node_id:this.sfuNodeId})}trackUpdate(e){this.notify("track-update",{tracks:Object.fromEntries(e)})}broadcast(e){return c(this,null,function*(){return yield this.call("broadcast",e)})}leave(e){this.notify("leave",{client_reason:e})}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(s=>{setTimeout(()=>{s(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",m({},e))})}stopRTMPAndRecording(){return c(this,null,function*(){yield this.call("rtmp-stop",{})})}startHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-start",m({},e))})}stopHLSStreaming(e){return c(this,null,function*(){yield this.call("hls-stop",m({},e))})}startTranscription(e){return c(this,null,function*(){yield this.call("transcription-start",m({},e))})}stopTranscription(e){return c(this,null,function*(){yield this.call("transcription-stop",m({},e))})}updateTranscriptionConfig(e){return c(this,null,function*(){yield this.call("transcription-config-update",m({},e))})}sendHLSTimedMetadata(e){return c(this,null,function*(){yield this.call("hls-timed-metadata",m({},e))})}updatePeer(e){return c(this,null,function*(){yield this.call("peer-update",m({},e))})}getPeer(e){return c(this,null,function*(){return yield this.call("get-peer",m({},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)})}findPeerByName(e){return c(this,null,function*(){return yield this.call("peer-name-search",e)})}setSessionMetadata(e){if(!this.isConnected)throw S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL","Failed to set session store value due to network disconnection");return this.call("set-metadata",m({},e))}listenMetadataChange(e){if(!this.isConnected)throw S.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 S.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",m({},e))}getPollInfo(e){return this.call("poll-info-get",m({},e))}setPollQuestions(e){return this.call("poll-questions-set",m({},e))}startPoll(e){return this.call("poll-start",m({},e))}stopPoll(e){return this.call("poll-stop",m({},e))}getPollQuestions(e){return this.call("poll-questions-get",m({},e))}setPollResponses(e){return this.call("poll-response",m({},e))}getPollResponses(e){return this.call("poll-responses",m({},e))}getPollsList(e){return this.call("poll-list",m({},e))}getPollResult(e){return this.call("poll-result",m({},e))}createWhiteboard(e){return this.validateConnection(),this.call("whiteboard-create",m({},e))}getWhiteboard(e){return this.validateConnection(),this.call("whiteboard-get",m({},e))}fetchPollLeaderboard(e){return this.call("poll-leaderboard",m({},e))}validateConnection(){if(!this.isConnected)throw S.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(S.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,s,n,o;((r=t.metadata)==null?void 0:r.method)!=="ping"&&(d.e(this.TAG,`rejecting pending callback ${(s=t.metadata)==null?void 0:s.method}, id=${i}`),t.reject(S.WebSocketConnectionErrors.WebSocketConnectionLost((n=t.metadata)!=null&&n.method?Yr((o=t.metadata)==null?void 0:o.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 s=yield this.ping(t);this.pongResponseTimes.enqueue(s),s>t?(d.d(this.TAG,`Pong timeout ${e}, pageHidden=${Ta()}`),this.id===e&&this.setIsConnected(!1,"ping pong failure")):setTimeout(()=>{this.id===e&&this.pingPongLoop(e)},((r=window.HMS)==null?void 0:r.PING_INTERVAL)||3e3)}})}call(e,t){return c(this,null,function*(){let r=S.WebsocketMethodErrors.ServerErrors(500,e,`Default ${e} error`),s;for(s=1;s<=3;s++)try{return this.validateConnection(),d.d(this.TAG,`Try number ${s} sending ${e}`,t),yield this.internalCall(e,t)}catch(n){if(r=n,d.e(this.TAG,`Failed sending ${e} try: ${s}`,{method:e,params:t,error:r}),!(parseInt(`${r.code/100}`)===5||r.code===429||r.code===1003))break;let l=(2+Math.random()*2)*1e3;yield Fe(l)}throw d.e(`Sending ${e} over WS failed after ${Math.min(s,3)} retries`,{method:e,params:t,error:r}),r})}};var Yn=()=>{if(!F||typeof navigator.connection=="undefined")return;let a=navigator.connection;return{downlink:a.downlink,downlinkMax:a.downlinkMax,effectiveType:a.effectiveType,rtt:a.rtt,saveData:a.saveData,type:a.type}};var A="[HMSTransport]:",Zn=a=>a instanceof k&&a.code===E.WebrtcErrors.PUBLISH_ANSWER_SUPERSEDED,Si=class{constructor(e,t,i,r,s,n,o){this.observer=e;this.deviceManager=t;this.store=i;this.eventBus=r;this.analyticsEventsService=s;this.analyticsTimer=n;this.pluginUsageTracker=o;this.state="Disconnected";this.trackStates=new Map;this.publishConnection=null;this.subscribeConnection=null;this.maxSubscribeBitrate=0;this.joinRetryCount=0;this.publishDisconnectTimer=0;this.onScreenshareStop=()=>{};this.screenStream=new Set;this.callbacks=new Map;this.setListener=e=>{this.listener=e};this.setOnScreenshareStop=e=>{this.onScreenshareStop=e};this.signalObserver={onOffer:e=>c(this,null,function*(){try{if(!this.subscribeConnection)return;if(e.sfu_node_id&&this.subscribeConnection.sfuNodeId&&this.subscribeConnection.sfuNodeId!==e.sfu_node_id){d.d(A,"ignoring old offer");return}yield this.subscribeConnection.setRemoteDescription(e),d.d(A,`[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(A,"[role=SUBSCRIBE] onOffer renegotiation DONE \u2705")}catch(t){d.d(A,"[role=SUBSCRIBE] onOffer renegotiation FAILED \u274C",t);let i;t instanceof k?i=t:i=S.GenericErrors.Unknown("SUBSCRIBE",t.message),yield this.observer.onStateChange("Failed",i),this.eventBus.analytics.publish(v.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(A,"socket offline",ai[this.state]);try{this.state!=="Leaving"&&this.joinParameters&&this.retryScheduler.schedule({category:1,error:S.WebSocketConnectionErrors.WebSocketConnectionLost("RECONNECT_SIGNAL",e),task:this.retrySignalDisconnectTask,originalState:this.state})}catch(t){console.error(t)}}),onOnline:()=>{var e;d.d(A,"socket online",ai[this.state]),this.analyticsSignalTransport.flushFailedEvents((e=this.store.getLocalPeer())==null?void 0:e.peerId)},onNetworkOnline:()=>{this.analyticsEventsService.flushFailedClientEvents()}};this.signal=new mi(this.signalObserver);this.analyticsSignalTransport=new _r(this.signal);this.publishDtlsStateTimer=0;this.lastPublishDtlsState="new";this.handleLocalRoleUpdate=i=>c(this,[i],function*({oldRole:e,newRole:t}){!this.doesRoleNeedWebRTC(e)&&this.doesRoleNeedWebRTC(t)&&(d.d(A,"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(je,{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(at,{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 e;if(!this.joinParameters||this.state==="Leaving")return!1;d.d(A,"retrySignalDisconnectTask",{signalConnected:this.signal.isConnected}),this.signal.isConnected||(yield this.internalConnect(this.joinParameters.authToken,this.joinParameters.endpoint,this.joinParameters.peerId,this.joinParameters.iceServers));try{return(e=this.store.getRoom())!=null&&e.joinedAt?this.signal.isConnected&&(yield this.retryPublishIceFailedTask()):this.signal.isConnected}finally{this.signal.trackUpdate(this.trackStates)}});this.webrtcInternals=new Fi(this.store,this.eventBus);let l=(u,p)=>c(this,null,function*(){u!==this.state&&(this.state=u,yield this.observer.onStateChange(this.state,p))});this.retryScheduler=new Lr(l,this.sendErrorAnalyticsEvent.bind(this)),this.eventBus.statsUpdate.subscribe(u=>{var h,T;let p=((T=(h=u.getLocalPeerStats())==null?void 0:h.subscribe)==null?void 0:T.bitrate)||0;this.maxSubscribeBitrate=Math.max(this.maxSubscribeBitrate,p)}),this.eventBus.localAudioEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p)),this.eventBus.localVideoEnabled.subscribe(({track:u,enabled:p})=>this.trackUpdate(u,p))}getWebsocketEndpoint(){if(this.initConfig)return this.initConfig.endpoint}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)}setConnectivityListener(e){this.connectivityListener=e}preview(e,t,i,r,s=!1,n){return c(this,null,function*(){let o=yield this.connect(e,t,i,r,s,n);return this.state="Preview",this.observer.onStateChange(this.state),o})}join(e,t,i,r,s=!1,n){return c(this,null,function*(){d.d(A,"join: started \u23F0");try{(!this.signal.isConnected||!this.initConfig)&&(yield this.connect(e,r,t,i,s,n)),this.validateNotDisconnected("connect"),this.initConfig&&(yield this.waitForLocalRoleAvailability(),yield this.createConnectionsAndNegotiateJoin(i,s),this.initStatsAnalytics(),d.d(A,"\u2705 join: Negotiated over PUBLISH connection"))}catch(o){d.e(A,`join: failed \u274C [token=${e}]`,o),this.state="Failed";let l=o;throw l.isTerminal=l.isTerminal||l.code===500,yield this.observer.onStateChange(this.state,l),l}d.d(A,"\u2705 join: successful"),this.state="Joined",this.observer.onStateChange(this.state)})}connect(e,t,i,r,s=!1,n){return c(this,null,function*(){this.setTransportStateForConnect(),this.joinParameters=new Hr(e,i,r.name,r.metaData,t,s,n);try{return yield this.internalConnect(e,t,i,n)}catch(o){if(!(o instanceof k))throw o;if([E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,E.WebSocketConnectionErrors.FAILED_TO_CONNECT,E.WebSocketConnectionErrors.ABNORMAL_CLOSE].includes(o.code)||o.code.toString().startsWith("5")||o.code.toString().startsWith("429")||o.code===E.APIErrors.ENDPOINT_UNREACHABLE&&!navigator.onLine){let u=()=>c(this,null,function*(){return yield this.internalConnect(e,t,i,n),!!(this.initConfig&&this.initConfig.endpoint)});yield this.retryScheduler.schedule({category:0,error:o,task:u,originalState:this.state,changeState:!1})}else throw o}})}leave(i){return c(this,arguments,function*(e,t="user request"){var r,s,n;this.retryScheduler.reset(),this.joinParameters=void 0,d.d(A,"leaving in transport");try{let o=this.pluginUsageTracker.getPluginUsage("HMSKrispPlugin");if(o&&this.eventBus.analytics.publish(v.getKrispUsage(o)),this.state="Leaving",(r=this.publishStatsAnalytics)==null||r.stop(),(s=this.subscribeStatsAnalytics)==null||s.stop(),(n=this.webrtcInternals)==null||n.cleanup(),this.clearPeerConnections(),e)try{this.signal.leave(t),d.d(A,"signal leave done")}catch(l){d.w(A,"failed to send leave on websocket to server",l)}this.analyticsEventsService.flushFailedClientEvents(),this.analyticsEventsService.reset(),yield this.signal.close()}catch(o){this.eventBus.analytics.publish(v.disconnect(o)),d.e(A,"leave: FAILED \u274C",o)}finally{this.state="Disconnected",this.observer.onStateChange(this.state)}})}publish(e){return c(this,null,function*(){var t;for(let i of e)try{yield this.publishTrack(i),(t=this.connectivityListener)==null||t.onMediaPublished(i)}catch(r){this.eventBus.analytics.publish(v.publish({devices:this.deviceManager.getDevices(),error:r}))}})}unpublish(e){return c(this,null,function*(){for(let t of e)yield this.unpublishTrack(t)})}setSFUNodeId(e){var t,i;this.signal.setSfuNodeId(e),this.sfuNodeId?e&&this.sfuNodeId!==e&&(this.sfuNodeId=e,this.handleSFUMigration().catch(r=>d.w(A,"sfu migration aborted",r))):(this.sfuNodeId=e,(t=this.publishConnection)==null||t.setSfuNodeId(e),(i=this.subscribeConnection)==null||i.setSfuNodeId(e))}republishOnMigration(e){return c(this,null,function*(){try{yield this.publishTrack(e)}catch(t){d.w(A,`republish after migration failed for ${e.trackId}`,t),this.eventBus.analytics.publish(v.publish({error:t})),Zn(t)&&e.publishedTrackId&&this.trackStates.has(e.publishedTrackId)&&(this.store.addTrack(e),e.isPublished=!0)}})}handleSFUMigration(){return c(this,null,function*(){var s,n;d.time("sfu migration"),this.clearPeerConnections();let e=this.store.getPeerMap();this.store.removeRemoteTracks();for(let o in e){let l=e[o];l.isLocal||(l.audioTrack=void 0,l.videoTrack=void 0,l.auxiliaryTracks=[])}let t=this.store.getLocalPeer();if(!t)return;this.createPeerConnections(),this.trackStates.clear(),yield this.negotiateOnFirstPublish();let i=new Map;if(t.audioTrack){let o=t.audioTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream));let l=t.audioTrack.clone(i.get(o.id));this.store.removeTrack(t.audioTrack),t.audioTrack.cleanup(),t.audioTrack=l,yield this.republishOnMigration(l)}if(t.videoTrack){let o=t.videoTrack.stream;i.get(o.id)||i.set(o.id,new fe(new MediaStream)),this.store.removeTrack(t.videoTrack);let l=t.videoTrack.clone(i.get(o.id));t.videoTrack.cleanup(),t.videoTrack=l,yield this.republishOnMigration(l)}let r=[];for(;t.auxiliaryTracks.length>0;){let o=t.auxiliaryTracks.shift();if(o){let l=o.stream;i.get(l.id)||i.set(l.id,new fe(o.source==="screen"?l.nativeStream.clone():new MediaStream)),this.store.removeTrack(o);let u=o.clone(i.get(l.id));u.type==="video"&&u.source==="screen"&&(this.screenStream.add(l.nativeStream),this.screenStream.add(u.stream.nativeStream),u.nativeTrack.addEventListener("ended",this.onScreenshareStop)),o.cleanup(),r.push(u),yield this.republishOnMigration(u)}}t.auxiliaryTracks=r,i.clear(),(n=(s=this.listener)==null?void 0:s.onSFUMigration)==null||n.call(s),d.timeEnd("sfu migration")})}trackUpdate(e,t){var s;let r=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);if(r){let n=new Xt(y(m({},r),{mute:!t}));this.trackStates.set(r.track_id,n),d.d(A,"Track Update",this.trackStates,e),this.signal.trackUpdate(new Map([[r.track_id,n]]));let o=this.store.getLocalPeer();o&&t===e.enabled&&((s=this.listener)==null||s.onTrackUpdate(t?3:2,e,o))}}publishTrack(e){return c(this,null,function*(){e.publishedTrackId=e.getTrackIDBeingSent(),d.d(A,`\u23F3 publishTrack: trackId=${e.trackId}, toPublishTrackId=${e.publishedTrackId}`,`${e}`),this.trackStates.set(e.publishedTrackId,new Xt(e));let t=new Promise((s,n)=>{this.callbacks.set(je,{promise:{resolve:s,reject:n},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(A,`Setting maxBitrate=${e.settings.maxBitrate} kpbs${e instanceof q?` and maxFramerate=${e.settings.maxFramerate}`:""} for ${e.source} ${e.type} ${e.trackId}`)}).catch(s=>d.w(A,"Failed setting maxBitrate and maxFramerate",s)),e.isPublished=!0,d.d(A,`\u2705 publishTrack: trackId=${e.trackId}`,`${e}`,this.callbacks)})}unpublishTrack(e){return c(this,null,function*(){if(d.d(A,`\u23F3 unpublishTrack: trackId=${e.trackId}`,`${e}`),e.publishedTrackId&&this.trackStates.has(e.publishedTrackId))this.trackStates.delete(e.publishedTrackId);else{let s=Array.from(this.trackStates.values()).find(n=>e.type===n.type&&e.source===n.source);s&&this.trackStates.delete(s.track_id)}let t=new Promise((r,s)=>{this.callbacks.set(je,{promise:{resolve:r,reject:s},action:"UNPUBLISH",extra:{}})});e.stream.removeSender(e);try{yield t}catch(r){if(!Zn(r))throw r;d.w(A,"unpublishTrack: renegotiation superseded, tearing down anyway",r)}finally{yield this.teardownUnpublishedTrack(e)}d.d(A,`\u2705 unpublishTrack: trackId=${e.trackId}`,this.callbacks)})}teardownUnpublishedTrack(e){return c(this,null,function*(){try{yield e.cleanup()}catch(t){d.w(A,`unpublishTrack: cleanup failed for ${e.trackId}`,t)}e.source==="screen"&&this.screenStream&&this.screenStream.forEach(t=>{t.getTracks().forEach(i=>{i.stop()}),this.screenStream.delete(t)}),this.store.removeTrack(e)})}clearPeerConnections(){return c(this,null,function*(){var e,t;clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0,clearTimeout(this.publishDisconnectTimer),this.publishDisconnectTimer=0,this.lastPublishDtlsState="new",(e=this.publishConnection)==null||e.close(),(t=this.subscribeConnection)==null||t.close(),this.publishConnection=null,this.subscribeConnection=null})}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(){var t,i,r;let e=(s,n,o=!1)=>{(["disconnected","failed"].includes(n)?d.w.bind(d):d.d.bind(d))(A,`${yt[s]} ${o?"ice":""} connection state change: ${n}`)};if(this.initConfig){let s={onRenegotiationNeeded:()=>c(this,null,function*(){yield this.performPublishRenegotiation()}),onDTLSTransportStateChange:o=>{var p,h,T;if((o==="failed"?d.w.bind(d):d.d.bind(d))(A,`Publisher on dtls transport state change: ${o}`),!o||this.lastPublishDtlsState===o||(this.lastPublishDtlsState=o,this.publishDtlsStateTimer!==0&&(clearTimeout(this.publishDtlsStateTimer),this.publishDtlsStateTimer=0),o!=="connecting"&&o!=="failed"))return;let u=(T=(h=(p=this.initConfig)==null?void 0:p.config)==null?void 0:h.dtlsStateTimeouts)==null?void 0:T[o];!u||u<=0||(this.publishDtlsStateTimer=window.setTimeout(()=>{var f;let g=(f=this.publishConnection)==null?void 0:f.nativeConnection.connectionState;if(g&&o&&g===o){let P=S.WebrtcErrors.ICEFailure("PUBLISH",`DTLS transport state ${o} timeout:${u}ms`,!0);this.eventBus.analytics.publish(v.disconnect(P)),this.observer.onFailure(P)}},u))},onDTLSTransportError:o=>{d.e(A,`onDTLSTransportError ${o.name} ${o.message}`,o),this.eventBus.analytics.publish(v.disconnect(o))},onIceConnectionChange:o=>c(this,null,function*(){e(0,o,!0)}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f,P;e(0,o,!1),o!=="new"&&(o==="connected"?((l=this.connectivityListener)==null||l.onICESuccess(!0),(u=this.publishConnection)==null||u.handleSelectedIceCandidatePairs()):o==="failed"?yield this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEFailure("PUBLISH",`local candidate - ${(T=(h=(p=this.publishConnection)==null?void 0:p.selectedCandidatePair)==null?void 0:h.local)==null?void 0:T.candidate}; remote candidate - ${(P=(f=(g=this.publishConnection)==null?void 0:g.selectedCandidatePair)==null?void 0:f.remote)==null?void 0:P.candidate}`)):this.publishDisconnectTimer=window.setTimeout(()=>{var M,R,$,ce,B,de,De;((M=this.publishConnection)==null?void 0:M.connectionState)!=="connected"&&this.handleIceConnectionFailure(0,S.WebrtcErrors.ICEDisconnected("PUBLISH",`local candidate - ${(ce=($=(R=this.publishConnection)==null?void 0:R.selectedCandidatePair)==null?void 0:$.local)==null?void 0:ce.candidate}; remote candidate - ${(De=(de=(B=this.publishConnection)==null?void 0:B.selectedCandidatePair)==null?void 0:de.remote)==null?void 0:De.candidate}`))},5e3))}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!0)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!0)}},n={onApiChannelMessage:o=>{this.observer.onNotification(JSON.parse(o))},onTrackAdd:o=>{d.d(A,"[Subscribe] onTrackAdd",`${o}`),this.observer.onTrackAdd(o)},onTrackRemove:o=>{d.d(A,"[Subscribe] onTrackRemove",`${o}`),this.observer.onTrackRemove(o)},onIceConnectionChange:o=>c(this,null,function*(){var l;if(e(1,o,!0),o==="connected"){let u=this.callbacks.get(at);this.callbacks.delete(at),(l=this.connectivityListener)==null||l.onICESuccess(!1),u&&u.promise.resolve(!0)}}),onConnectionStateChange:o=>c(this,null,function*(){var l,u,p,h,T,g,f;if(e(1,o,!1),o==="failed")yield this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEFailure("SUBSCRIBE",`local candidate - ${(p=(u=(l=this.subscribeConnection)==null?void 0:l.selectedCandidatePair)==null?void 0:u.local)==null?void 0:p.candidate}; remote candidate - ${(g=(T=(h=this.subscribeConnection)==null?void 0:h.selectedCandidatePair)==null?void 0:T.remote)==null?void 0:g.candidate}`));else if(o==="disconnected")setTimeout(()=>{var P,M,R,$,ce,B,de;((P=this.subscribeConnection)==null?void 0:P.connectionState)==="disconnected"&&this.handleIceConnectionFailure(1,S.WebrtcErrors.ICEDisconnected("SUBSCRIBE",`local candidate - ${($=(R=(M=this.subscribeConnection)==null?void 0:M.selectedCandidatePair)==null?void 0:R.local)==null?void 0:$.candidate}; remote candidate - ${(de=(B=(ce=this.subscribeConnection)==null?void 0:ce.selectedCandidatePair)==null?void 0:B.remote)==null?void 0:de.candidate}`))},5e3);else if(o==="connected"){(f=this.subscribeConnection)==null||f.handleSelectedIceCandidatePairs();let P=this.callbacks.get(at);this.callbacks.delete(at),P&&P.promise.resolve(!0)}}),onIceCandidate:o=>{var l;(l=this.connectivityListener)==null||l.onICECandidate(o,!1)},onSelectedCandidatePairChange:o=>{var l;(l=this.connectivityListener)==null||l.onSelectedICECandidatePairChange(o,!1)}};this.publishConnection||(this.publishConnection=new li(this.signal,this.initConfig.rtcConfiguration,s)),this.subscribeConnection||(this.subscribeConnection=new pi(this.signal,this.initConfig.rtcConfiguration,this.isFlagEnabled.bind(this),n,this.eventBus))}(r=this.webrtcInternals)==null||r.setPeerConnections({publish:(t=this.publishConnection)==null?void 0:t.nativeConnection,subscribe:(i=this.subscribeConnection)==null?void 0:i.nativeConnection})}negotiateJoinWithRetry(s){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(n){d.e(A,"Join negotiation failed \u274C",n);let o=n instanceof k?n:S.WebsocketMethodErrors.ServerErrors(500,"JOIN",`Websocket join error - ${n.message}`),l=parseInt(`${o.code/100}`)===5||[E.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,429].includes(o.code);if(o.code===410&&(o.isTerminal=!0),l){this.joinRetryCount=0,o.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:o,task:u,originalState:"Joined",changeState:!1})}else throw n}})}negotiateJoin(s){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(A,"\u23F3 join: Negotiating over PUBLISH connection"),!this.publishConnection)return d.e(A,"Publish peer connection not found, cannot negotiate"),!1;let s=this.publishConnection,n=yield s.createOffer(),o=yield s.setLocalDescription(n),l=this.isFlagEnabled("subscribeDegradation"),u=this.isFlagEnabled("simulcast"),p=this.isFlagEnabled("onDemandTracks"),h=yield this.signal.join(e,t,!i,l,u,p,n);this.setSFUNodeId(h==null?void 0:h.sfu_node_id),this.assertPublishAnswerApplicable(s,o,"JOIN"),yield s.setRemoteDescription(h);for(let T of s.candidates)yield s.addIceCandidate(T);return s.initAfterJoin(),!!h})}negotiateJoinNonWebRTC(r){return c(this,arguments,function*({name:e,data:t,autoSubscribeVideo:i}){d.d(A,"\u23F3 join: Negotiating Non-WebRTC");let s=this.isFlagEnabled("subscribeDegradation"),n=this.isFlagEnabled("simulcast"),o=this.isFlagEnabled("onDemandTracks"),l=yield this.signal.join(e,t,!i,s,n,o);return this.setSFUNodeId(l==null?void 0:l.sfu_node_id),!!l})}negotiateOnFirstPublish(){return c(this,null,function*(){if(d.d(A,"\u23F3 Negotiating offer over PUBLISH connection"),!this.publishConnection)return d.e(A,"Publish peer connection not found, cannot negotiate"),!1;let e=this.publishConnection;try{let t=yield e.createOffer(this.trackStates),i=yield e.setLocalDescription(t),r=yield this.signal.offer(t,this.trackStates),s=this.publishAnswerDiscardReason(e,i,"PUBLISH");if(s==="connection_replaced")throw this.publishAnswerDiscardError(s,i,"PUBLISH");if(s)return e.initAfterJoin(),!1;yield e.setRemoteDescription(r);for(let n of e.candidates)yield e.addIceCandidate(n);return e.initAfterJoin(),!!r}catch(t){return this.handleFirstPublishNegotiationError(t)}})}handleFirstPublishNegotiationError(e){if(!(e instanceof k))throw e;if(e.code===421)return!0;throw e}publishAnswerDiscardReason(e,t,i){let r;if(e!==this.publishConnection?r="connection_replaced":e.isStagingLocalDescription(t)?e.signalingState!=="have-local-offer"&&(r="unexpected_state"):r="superseded_offer",!!r)return d.w(A,`[role=PUBLISH] discarding answer reason=${r} state=${e.signalingState}`),this.eventBus.analytics.publish(v.publishAnswerDiscarded({reason:r,action:i.toString(),signaling_state:e.signalingState,transport_state:ai[this.state],epoch:t})),r}publishAnswerDiscardError(e,t,i){return i==="JOIN"?S.WebrtcErrors.SetRemoteDescriptionFailed(i,`${e} epoch=${t}`):S.WebrtcErrors.PublishAnswerSuperseded(i,`${e} epoch=${t}`)}assertPublishAnswerApplicable(e,t,i){let r=this.publishAnswerDiscardReason(e,t,i);if(r)throw this.publishAnswerDiscardError(r,t,i)}releaseRenegotiationCallback(e){this.callbacks.get(je)===e&&this.callbacks.delete(je)}performPublishRenegotiation(e){return c(this,null,function*(){d.d(A,"\u23F3 [role=PUBLISH] onRenegotiationNeeded START",this.trackStates);let t=this.callbacks.get(je);if(!t){d.w(A,"no callback found for renegotiation");return}let i=this.publishConnection;if(!i){d.e(A,"Publish peer connection not found, cannot renegotiate"),t.promise.reject(S.WebrtcErrors.PublishAnswerSuperseded(t.action,"publish connection is gone")),this.releaseRenegotiationCallback(t);return}try{let r=yield i.createOffer(this.trackStates,e),s=yield i.setLocalDescription(r);d.time("renegotiation-offer-exchange");let n=yield this.signal.offer(r,this.trackStates);d.timeEnd("renegotiation-offer-exchange"),this.assertPublishAnswerApplicable(i,s,t.action),yield i.setRemoteDescription(n),t.promise.resolve(!0),d.d(A,"[role=PUBLISH] onRenegotiationNeeded DONE \u2705")}catch(r){let s;r instanceof k?s=r:s=S.GenericErrors.Unknown("PUBLISH",r.message),s.code===421?t.promise.resolve(!0):t.promise.reject(s),d.d(A,"[role=PUBLISH] onRenegotiationNeeded FAILED \u274C")}finally{this.releaseRenegotiationCallback(t)}})}handleIceConnectionFailure(e,t){return c(this,null,function*(){this.retryScheduler.isTaskInProgress(e===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"}))})}internalConnect(e,t,i,r){return c(this,null,function*(){var n,o,l;d.d(A,"connect: started \u23F0");let s=new Date;try{this.analyticsTimer.start("init_response_time"),this.initConfig=yield hi.fetchInitConfig({token:e,peerId:i,userAgent:this.store.getUserAgent(),initEndpoint:t,iceServers:r}),(n=this.connectivityListener)==null||n.onInitSuccess(this.initConfig.endpoint);let u=this.store.getRoom();return u&&(u.effectsKey=(o=this.initConfig.config.vb)==null?void 0:o.effectsKey,u.isEffectsEnabled=this.isFlagEnabled("effectsSDKEnabled"),u.disableNoneLayerRequest=this.isFlagEnabled("disableNoneLayerRequest"),u.isVBEnabled=this.isFlagEnabled("vb"),u.isHipaaEnabled=this.isFlagEnabled("hipaa"),u.isNoiseCancellationEnabledFromInit=this.isFlagEnabled("noiseCancellation")),this.analyticsTimer.end("init_response_time"),Le.setWebsocketEndpoint(this.initConfig.endpoint),this.validateNotDisconnected("post init"),yield this.openSignal(e,i),this.observer.onConnected(),(l=this.connectivityListener)==null||l.onSignallingSuccess(),this.store.setSimulcastEnabled(this.isFlagEnabled("simulcast")),d.d(A,"Adding Analytics Transport: JsonRpcSignal"),this.analyticsEventsService.setTransport(this.analyticsSignalTransport),this.analyticsEventsService.flush(),this.initConfig}catch(u){throw this.state!=="Reconnecting"&&this.eventBus.analytics.publish(v.connect(u,this.getAdditionalAnalyticsProperties(),s,new Date,t)),d.e(A,"\u274C internal connect: failed",u),u}})}validateNotDisconnected(e){if(this.state==="Disconnected")throw d.w(A,"aborting join as transport state is disconnected"),S.GenericErrors.ValidationFailed(`leave called before join could complete - stage=${e}`)}openSignal(e,t){return c(this,null,function*(){if(!this.initConfig)throw S.APIErrors.InitConfigNotAvailable("INIT","Init Config not found");d.d(A,"\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",La),i.searchParams.set("protocol_spec",wa),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(A,"\u2705 internal connect: connected to ws endpoint")})}initStatsAnalytics(){var e,t;this.isFlagEnabled("publishStats")&&(this.publishStatsAnalytics=new oi(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 ci(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,s;return((s=(r=this.initConfig)==null?void 0:r.config[e])==null?void 0:s[t])||i}doesRoleNeedWebRTC(e){var r,s;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&&((s=e.subscribeParams.subscribeToRoles)==null?void 0:s.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}setTransportStateForConnect(){if(this.state==="Failed"&&(this.state="Disconnected"),this.state!=="Disconnected"&&this.state!=="Reconnecting")throw S.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=v.connect(e,i);break;case 1:r=v.disconnect(e,i);break;case 2:r=v.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=v.publish({error:e});break;case 4:r=v.subscribeFail(e);break}this.eventBus.analytics.publish(r)}getSubscribeConnection(){return this.subscribeConnection}getAdditionalAnalyticsProperties(){var n,o,l,u,p,h,T,g;let e=Yn(),t=typeof document!="undefined"&&document.hidden,i=this.store.getRemoteVideoTracks().filter(f=>f.degraded).length,r=(u=(l=(o=(n=this.getWebrtcInternals())==null?void 0:n.getCurrentStats())==null?void 0:o.getLocalPeerStats())==null?void 0:l.publish)==null?void 0:u.bitrate,s=(g=(T=(h=(p=this.getWebrtcInternals())==null?void 0:p.getCurrentStats())==null?void 0:h.getLocalPeerStats())==null?void 0:T.subscribe)==null?void 0:g.bitrate;return{network_info:e,document_hidden:t,num_degraded_tracks:i,bitrate:{publish:r,subscribe:s},max_sub_bitrate:this.maxSubscribeBitrate,recent_pong_response_times:this.signal.getPongResponseTimes(),transport_state:this.state}}};function Vr(a){if(!a||a.length===0)throw S.APIErrors.InvalidTokenFormat("INIT","Token cannot be an empty string or undefined or null");let e=a.split(".");if(e.length!==3)throw S.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 S.APIErrors.InvalidTokenFormat("INIT",`couldn't parse to json - ${i.message}`)}}var eo={published:!1,isInitialised:!1,isReconnecting:!1,isPreviewInProgress:!1,isPreviewCalled:!1,isJoinInProgress:!1,deviceManagersInitialised:!1},Fr=class{constructor(){this.TAG="[HMSSdk]:";this.transportState="Disconnected";this.analyticsTimer=new Ai;this.sdkState=m({},eo);this.isDiagnostics=!1;this.playlistSettings={video:{bitrate:is},audio:{bitrate:rs}};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,s;let i=n=>c(this,null,function*(){var o,l;yield this.internalLeave(!0,n),!this.sdkState.isPreviewInProgress&&!this.sdkState.isJoinInProgress&&((l=(o=this.errorListener)==null?void 0:o.onError)==null||l.call(o,n)),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,(s=this.listener)==null||s.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.handlePreviewError=e=>{var t;this.analyticsTimer.end("preview_time"),e&&((t=this.errorListener)==null||t.onError(e)),this.sendPreviewAnalyticsEvent(e),this.sdkState.isPreviewInProgress=!1};this.handleTrackInterruption=e=>{var t,i;d.d(this.TAG,"Track interruption",`{
104
104
  started: ${e.started};
105
105
  type: ${e.type};
106
106
  reason: ${e.reason};