@100mslive/hms-video-store
Version:
@100mslive Core SDK which abstracts the complexities of webRTC while providing a reactive store for data management with a unidirectional data flow
33 lines • 386 kB
JavaScript
var Eo=Object.defineProperty,Po=Object.defineProperties;var bo=Object.getOwnPropertyDescriptors;var di=Object.getOwnPropertySymbols,Io=Object.getPrototypeOf,ks=Object.prototype.hasOwnProperty,Es=Object.prototype.propertyIsEnumerable,Ao=Reflect.get;var ys=(a,e,t)=>e in a?Eo(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,m=(a,e)=>{for(var t in e||(e={}))ks.call(e,t)&&ys(a,t,e[t]);if(di)for(var t of di(e))Es.call(e,t)&&ys(a,t,e[t]);return a},M=(a,e)=>Po(a,bo(e));var Ar=(a,e)=>{var t={};for(var i in a)ks.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&di)for(var i of di(a))e.indexOf(i)<0&&Es.call(a,i)&&(t[i]=a[i]);return t};var Ro=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var ue=(a,e,t)=>Ao(Io(a),t,e);var c=(a,e,t)=>new Promise((i,r)=>{var s=d=>{try{n(t.next(d))}catch(u){r(u)}},o=d=>{try{n(t.throw(d))}catch(u){r(u)}},n=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,o);n((t=t.apply(a,e)).next())});var _r=Ro((gd,xo)=>{xo.exports={version:"0.13.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","src"],engines:{node:">=12"},exports:{".":{require:"./dist/index.cjs.js",import:"./dist/index.js",default:"./dist/index.js"}},sideEffects:!1,scripts:{prestart:"rm -rf dist && yarn types:build",start:'concurrently "yarn dev" "yarn types"',dev:"node ../../scripts/dev","build:only":"node ../../scripts/build",build:"yarn build:only && yarn types:build",types:"tsc -w","types:build":"tsc -p tsconfig.json",format:"prettier --write src/**/*.ts",test:"jest --maxWorkers=1","test:watch":"jest --watch","test:coverage":"jest --coverage",lint:"eslint -c ../../.eslintrc .","lint:fix":"yarn lint --fix",prepare:"yarn build",size:"size-limit",analyze:"size-limit --why",docs:"rm -rf ./docs && typedoc && rm -f ./docs/README.md && mkdir ./docs/home &&mv ./docs/modules.md ./docs/home/content.md && node ../../scripts/docs-store && npx prettier --write './docs/**/*'"},name:"@100mslive/hms-video-store",author:"100ms",dependencies:{eventemitter2:"^6.4.9",immer:"^9.0.6","lodash.isequal":"^4.5.0",reselect:"4.0.0","sdp-transform":"^2.14.1","ua-parser-js":"^2.0.6",uuid:"^8.3.2","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:"85d59b539d948170da2e01e45ea0e93f33091b48"}});var Rr=(n=>(n.Disconnected="Disconnected",n.Preview="Preview",n.Connecting="Connecting",n.Connected="Connected",n.Reconnecting="Reconnecting",n.Disconnecting="Disconnecting",n.Failed="Failed",n))(Rr||{});var li=()=>({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}),ui=()=>({peerStats:{},remoteTrackStats:{},localTrackStats:{},localPeer:{id:""}});var Ho=(e=>(e.CHAT="chat",e))(Ho||{});var Ps=(t=>(t.INFO="info",t.ERROR="error",t))(Ps||{}),Hr=(w=>(w.PEER_JOINED="PEER_JOINED",w.PEER_LEFT="PEER_LEFT",w.PEER_LIST="PEER_LIST",w.NEW_MESSAGE="NEW_MESSAGE",w.ERROR="ERROR",w.RECONNECTING="RECONNECTING",w.RECONNECTED="RECONNECTED",w.TRACK_ADDED="TRACK_ADDED",w.TRACK_REMOVED="TRACK_REMOVED",w.TRACK_MUTED="TRACK_MUTED",w.TRACK_UNMUTED="TRACK_UNMUTED",w.TRACK_DEGRADED="TRACK_DEGRADED",w.TRACK_RESTORED="TRACK_RESTORED",w.TRACK_DESCRIPTION_CHANGED="TRACK_DESCRIPTION_CHANGED",w.ROLE_UPDATED="ROLE_UPDATED",w.CHANGE_TRACK_STATE_REQUEST="CHANGE_TRACK_STATE_REQUEST",w.CHANGE_MULTI_TRACK_STATE_REQUEST="CHANGE_MULTI_TRACK_STATE_REQUEST",w.ROOM_ENDED="ROOM_ENDED",w.REMOVED_FROM_ROOM="REMOVED_FROM_ROOM",w.DEVICE_CHANGE_UPDATE="DEVICE_CHANGE_UPDATE",w.PLAYLIST_TRACK_ENDED="PLAYLIST_TRACK_ENDED",w.NAME_UPDATED="NAME_UPDATED",w.METADATA_UPDATED="METADATA_UPDATED",w.POLL_CREATED="POLL_CREATED",w.POLL_STARTED="POLL_STARTED",w.POLL_STOPPED="POLL_STOPPED",w.POLL_VOTES_UPDATED="POLL_VOTES_UPDATED",w.POLLS_LIST="POLLS_LIST",w.HAND_RAISE_CHANGED="HAND_RAISE_CHANGED",w.TRANSCRIPTION_STATE_UPDATED="TRANSCRIPTION_STATE_UPDATED",w))(Hr||{});var bs=(t=>(t.audio="audio",t.video="video",t))(bs||{});import{createSelector as I}from"reselect";function We(a,e){let t,i;if(e)for(let r of e.auxiliaryTracks){let s=a[r];Co(s)&&(i=vt(s)?s:i,t=Mt(s)?s:t)}return{video:t,audio:i}}function vt(a){return a&&a.type==="audio"}function Mt(a){return a&&a.type==="video"}function Co(a){return a&&a.source==="screen"}function pi(a){return a&&a.source==="audioplaylist"}function yt(a){return a&&a.source==="videoplaylist"}function Is(a){return a?!!(a!=null&&a.degraded):!1}function Xe(a,e){return e&&a.tracks[e]?a.tracks[e].enabled:!1}function As(a,e){return e&&a.tracks[e]?a.tracks[e].displayEnabled:!1}function kt(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 Rs=(d=>(d[d.VERBOSE=0]="VERBOSE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.TIME=4]="TIME",d[d.TIMEEND=5]="TIMEEND",d[d.ERROR=6]="ERROR",d[d.NONE=7]="NONE",d))(Rs||{}),Lo=typeof window!="undefined"&&typeof window.expect!="undefined",l=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}}}};l.level=Lo?7:0;var Ze=class{constructor(e){this.tracks=new Array;this.nativeStream=e,this.id=e.id}updateId(e){this.id=e}};import{UAParser as Do}from"ua-parser-js";var Cr=new Do,Et=null,Lr=null,B=typeof window!="undefined";if(B)try{let a=Cr.getResult(),e=a.withClientHints();e&&typeof e.then=="function"?(Lr=e,Lr.then(t=>{Et=t}).catch(()=>{Et=a})):(l.d("UAParser","Client Hints not supported, using standard UA parsing"),Et=e)}catch(a){Et=Cr.getResult()}var we=()=>Et||Cr.getResult(),Se={getBrowser:()=>we().browser,getOS:()=>we().os,getDevice:()=>we().device,getCPU:()=>we().cpu,getEngine:()=>we().engine,getUA:()=>we().ua,getResult:we,withClientHints:()=>Lr||Promise.resolve(we())},Hs,$e=typeof window=="undefined"&&!((Hs=Se.getBrowser().name)!=null&&Hs.toLowerCase().includes("electron"));var wo=()=>!$e,Bc=wo(),Pt=()=>Se.getDevice().type==="mobile",Os=()=>typeof document!="undefined"&&document.hidden,xs=()=>{var a;return((a=Se.getOS().name)==null?void 0:a.toLowerCase())==="ios"},Cs,Ls,Us=(Ls=(Cs=Se.getBrowser())==null?void 0:Cs.name)==null?void 0:Ls.toLowerCase().includes("safari"),Ds,ws,Bs=((ws=(Ds=Se.getBrowser())==null?void 0:Ds.name)==null?void 0:ws.toLowerCase())==="firefox",_s,Ns,Vs=((Ns=(_s=Se.getEngine())==null?void 0:_s.name)==null?void 0:Ns.toLowerCase())==="blink";import{v4 as Uo}from"uuid";var Fs=(i=>(i.CUSTOM="CUSTOM",i.LOCAL="LOCAL",i.HMS="HMS",i))(Fs||{});function _o(){if(B&&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 et=_o();import{v4 as Oo}from"uuid";var k={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},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 E=class a extends Error{constructor(t,i,r,s,o,n=!1){super(s);this.code=t;this.name=i;this.message=s;this.description=o;this.isTerminal=n;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`{
code: ${this.code};
name: ${this.name};
action: ${this.action};
message: ${this.message};
description: ${this.description};
isTerminal: ${this.isTerminal};
nativeError: ${(t=this.nativeError)==null?void 0:t.message};
}`}};var q=class extends E{constructor(t,i,r,s,o,n){super(t,i,r,s,o,!1);this.code=t;this.name=i;this.message=s;this.description=o;this.trackType=n}toAnalyticsProperties(){return M(m({},super.toAnalyticsProperties()),{track_type:this.trackType})}toString(){var t;return`{
code: ${this.code};
name: ${this.name};
action: ${this.action};
message: ${this.message};
description: ${this.description};
isTerminal: ${this.isTerminal};
nativeError: ${(t=this.nativeError)==null?void 0:t.message};
trackType: ${this.trackType};
}`}};var Gs=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUDIO_VIDEO="audio, video",r.SCREEN="screen",r))(Gs||{});function Dr(a){switch(a){case"join":return"JOIN";case"offer":return"PUBLISH";case"answer":return"SUBSCRIBE";case"track-update":return"TRACK";default:return"NONE"}}var No=["join","offer","answer","trickle","on-error","JOIN"],S={WebSocketConnectionErrors:{FailedToConnect(a,e=""){return new E(k.WebSocketConnectionErrors.FAILED_TO_CONNECT,"WebsocketFailedToConnect",a,`[WS]: ${e}`,`[WS]: ${e}`)},WebSocketConnectionLost(a,e=""){return new E(k.WebSocketConnectionErrors.WEBSOCKET_CONNECTION_LOST,"WebSocketConnectionLost",a,"Network connection lost",e)},AbnormalClose(a,e=""){return new E(k.WebSocketConnectionErrors.ABNORMAL_CLOSE,"WebSocketAbnormalClose",a,"Websocket closed abnormally",e)}},APIErrors:{ServerErrors(a,e,t="",i=!0){return new E(a,"ServerErrors",e,`[${e}]: Server error ${t}`,t,i)},EndpointUnreachable(a,e=""){return new E(k.APIErrors.ENDPOINT_UNREACHABLE,"EndpointUnreachable",a,`Endpoint is not reachable - ${e}`,e)},InvalidTokenFormat(a,e=""){return new E(k.APIErrors.INVALID_TOKEN_FORMAT,"InvalidTokenFormat",a,`Token is not in proper JWT format - ${e}`,e,!0)},InitConfigNotAvailable(a,e=""){return new E(k.APIErrors.INIT_CONFIG_NOT_AVAILABLE,"InitError",a,`[INIT]: ${e}`,`[INIT]: ${e}`)}},TracksErrors:{GenericTrack(a,e=""){return new q(k.TracksErrors.GENERIC_TRACK,"GenericTrack",a,`[TRACK]: ${e}`,`[TRACK]: ${e}`,"audio, video")},CantAccessCaptureDevice(a,e,t=""){return new q(k.TracksErrors.CANT_ACCESS_CAPTURE_DEVICE,"CantAccessCaptureDevice",a,`User denied permission to access capture device - ${e}`,t,e)},DeviceNotAvailable(a,e,t=""){return new q(k.TracksErrors.DEVICE_NOT_AVAILABLE,"DeviceNotAvailable",a,`[TRACK]: Capture device is no longer available - ${e}`,t,e)},DeviceInUse(a,e,t=""){return new q(k.TracksErrors.DEVICE_IN_USE,"DeviceInUse",a,`[TRACK]: Capture device is in use by another application - ${e}`,t,e)},DeviceLostMidway(a,e,t=""){return new q(k.TracksErrors.DEVICE_LOST_MIDWAY,"DeviceLostMidway",a,`Lost access to capture device midway - ${e}`,t,e)},NothingToReturn(a,e="",t="There is no media to return. Please select either video or audio or both."){return new q(k.TracksErrors.NOTHING_TO_RETURN,"NothingToReturn",a,t,e,"audio, video")},InvalidVideoSettings(a,e=""){return new q(k.TracksErrors.INVALID_VIDEO_SETTINGS,"InvalidVideoSettings",a,"Cannot enable simulcast when no video settings are provided",e,"video")},AutoplayBlocked(a,e=""){return new q(k.TracksErrors.AUTOPLAY_ERROR,"AutoplayBlocked",a,"Autoplay blocked because the user didn't interact with the document first",e,"audio")},CodecChangeNotPermitted(a,e=""){return new q(k.TracksErrors.CODEC_CHANGE_NOT_PERMITTED,"CodecChangeNotPermitted",a,"Codec can't be changed mid call.",e,"audio, video")},OverConstrained(a,e,t=""){return new q(k.TracksErrors.OVER_CONSTRAINED,"OverConstrained",a,`[TRACK]: Requested constraints cannot be satisfied with the device hardware - ${e}`,t,e)},NoAudioDetected(a,e="Please check the mic or use another audio input"){return new q(k.TracksErrors.NO_AUDIO_DETECTED,"NoAudioDetected",a,"No audio input detected from microphone",e,"audio")},SystemDeniedPermission(a,e,t=""){return new q(k.TracksErrors.SYSTEM_DENIED_PERMISSION,"SystemDeniedPermission",a,`Operating System denied permission to access capture device - ${e}`,t,e)},CurrentTabNotShared(){return new q(k.TracksErrors.CURRENT_TAB_NOT_SHARED,"CurrentTabNotShared","TRACK","The app requires you to share the current tab","You must screen share the current tab in order to proceed","screen")},AudioPlaybackError(a){return new q(k.TracksErrors.AUDIO_PLAYBACK_ERROR,"Audio playback error","TRACK",a,a,"audio")},SelectedDeviceMissing(a){return new q(k.TracksErrors.SELECTED_DEVICE_MISSING,"SelectedDeviceMissing","TRACK",`Could not detect selected ${a} device`,`Please check connection to the ${a} device`,a)},NoDataInTrack(a){return new q(k.TracksErrors.NO_DATA,"Track does not have any data","TRACK",a,"This could possibily due to another application taking priority over the access to camera or microphone or due to an incoming call","audio, video")}},WebrtcErrors:{CreateOfferFailed(a,e=""){return new E(k.WebrtcErrors.CREATE_OFFER_FAILED,"CreateOfferFailed",a,`[${a.toString()}]: Failed to create offer. `,e)},CreateAnswerFailed(a,e=""){return new E(k.WebrtcErrors.CREATE_ANSWER_FAILED,"CreateAnswerFailed",a,`[${a.toString()}]: Failed to create answer. `,e)},SetLocalDescriptionFailed(a,e=""){return new E(k.WebrtcErrors.SET_LOCAL_DESCRIPTION_FAILED,"SetLocalDescriptionFailed",a,`[${a.toString()}]: Failed to set offer. `,e)},SetRemoteDescriptionFailed(a,e=""){return new E(k.WebrtcErrors.SET_REMOTE_DESCRIPTION_FAILED,"SetRemoteDescriptionFailed",a,`[${a.toString()}]: Failed to set answer. `,e,!0)},ICEFailure(a,e="",t=!1){return new E(k.WebrtcErrors.ICE_FAILURE,"ICEFailure",a,`[${a.toString()}]: Ice connection state FAILED`,e,t)},ICEDisconnected(a,e=""){return new E(k.WebrtcErrors.ICE_DISCONNECTED,"ICEDisconnected",a,`[${a.toString()}]: Ice connection state DISCONNECTED`,e)},StatsFailed(a,e=""){return new E(k.WebrtcErrors.STATS_FAILED,"StatsFailed",a,`Failed to WebRTC get stats - ${e}`,e)}},WebsocketMethodErrors:{ServerErrors(a,e,t){return new E(a,"ServerErrors",e,t,t,No.includes(e))},AlreadyJoined(a,e=""){return new E(k.WebsocketMethodErrors.ALREADY_JOINED,"AlreadyJoined",a,"[JOIN]: You have already joined this room.",e)},CannotJoinPreviewInProgress(a,e=""){return new E(k.WebsocketMethodErrors.CANNOT_JOIN_PREVIEW_IN_PROGRESS,"CannotJoinPreviewInProgress",a,"[JOIN]: Cannot join if preview is in progress",e)}},GenericErrors:{NotConnected(a,e=""){return new E(k.GenericErrors.NOT_CONNECTED,"NotConnected",a,"Client is not connected",e)},Signalling(a,e){return new E(k.GenericErrors.SIGNALLING,"Signalling",a,`Unknown signalling error: ${a.toString()} ${e} `,e)},Unknown(a,e){return new E(k.GenericErrors.UNKNOWN,"Unknown",a,`Unknown exception: ${e}`,e)},NotReady(a,e=""){return new E(k.GenericErrors.NOT_READY,"NotReady",a,e,e)},JsonParsingFailed(a,e,t=""){return new E(k.GenericErrors.JSON_PARSING_FAILED,"JsonParsingFailed",a,`Failed to parse JSON message - ${e}`,t)},TrackMetadataMissing(a,e=""){return new E(k.GenericErrors.TRACK_METADATA_MISSING,"TrackMetadataMissing",a,"Track Metadata Missing",e)},RTCTrackMissing(a,e=""){return new E(k.GenericErrors.RTC_TRACK_MISSING,"RTCTrackMissing",a,"RTC Track missing",e)},PeerMetadataMissing(a,e=""){return new E(k.GenericErrors.PEER_METADATA_MISSING,"PeerMetadataMissing",a,"Peer Metadata Missing",e)},ValidationFailed(a,e){return new E(k.GenericErrors.VALIDATION_FAILED,"ValidationFailed","VALIDATION",a,e?JSON.stringify(e):"")},InvalidRole(a,e){return new E(k.GenericErrors.INVALID_ROLE,"InvalidRole",a,"Invalid role. Join with valid role",e,!0)},PreviewAlreadyInProgress(a,e=""){return new E(k.GenericErrors.PREVIEW_IN_PROGRESS,"PreviewAlreadyInProgress",a,"[Preview]: Cannot join if preview is in progress",e)},LocalStorageAccessDenied(a="Access to localStorage has been denied"){return new E(k.GenericErrors.LOCAL_STORAGE_ACCESS_DENIED,"LocalStorageAccessDenied","NONE","LocalStorageAccessDenied",a)},MissingMediaDevices(){return new E(k.GenericErrors.MISSING_MEDIADEVICES,"MissingMediaDevices","JOIN","navigator.mediaDevices is undefined. 100ms SDK won't work on this website as WebRTC is not supported on HTTP endpoints(missing navigator.mediaDevices). Please ensure you're using the SDK either on localhost or a valid HTTPS endpoint.","",!0)},MissingRTCPeerConnection(){return new E(k.GenericErrors.MISSING_RTCPEERCONNECTION,"MissingRTCPeerConnection","JOIN","RTCPeerConnection which is a core requirement for WebRTC call was not found, this could be due to an unsupported browser or browser extensions blocking WebRTC","",!0)}},MediaPluginErrors:{PlatformNotSupported(a,e=""){return new E(7001,"PlatformNotSupported",a,"Check HMS Docs to see the list of supported platforms",e)},InitFailed(a,e=""){return new E(7002,"InitFailed",a,"Plugin init failed",e)},ProcessingFailed(a,e=""){return new E(7003,"ProcessingFailed",a,"Plugin processing failed",e)},AddAlreadyInProgress(a,e=""){return new E(7004,"AddAlreadyInProgress",a,"Plugin add already in progress",e)},DeviceNotSupported(a,e=""){return new E(7005,"DeviceNotSupported",a,"Check HMS Docs to see the list of supported devices",e)}},PlaylistErrors:{NoEntryToPlay(a,e){return new E(k.PlaylistErrors.NO_ENTRY_TO_PLAY,"NoEntryToPlay",a,"Reached end of playlist",e)},NoEntryPlaying(a,e){return new E(k.PlaylistErrors.NO_ENTRY_IS_PLAYING,"NoEntryIsPlaying",a,"No entry is playing at this time",e)}}};var wr=class{constructor(){this.valuesMap=new Map}getItem(e){return this.valuesMap.has(e)?String(this.valuesMap.get(e)):null}setItem(e,t){this.valuesMap.set(e,t)}removeItem(e){this.valuesMap.delete(e)}clear(){this.valuesMap.clear()}key(e){if(arguments.length===0)throw new TypeError("Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present.");return Array.from(this.valuesMap.keys())[e]}get length(){return this.valuesMap.size}},Ws=()=>{try{B&&!localStorage&&(window.localStorage=new wr)}catch(a){l.e("Error initialising localStorage",S.GenericErrors.LocalStorageAccessDenied())}};var ve=class{constructor(e){this.key=e;this.storage=null}getStorage(){try{return B&&!this.storage&&(Ws(),this.storage=window.localStorage),this.storage}catch(e){return l.e("Error initialising localStorage",S.GenericErrors.LocalStorageAccessDenied()),null}}get(){var i;let e=(i=this.getStorage())==null?void 0:i.getItem(this.key);return e?JSON.parse(e):void 0}set(e){var i;let t=JSON.stringify(e);(i=this.getStorage())==null||i.setItem(this.key,t)}clear(){var e;(e=this.getStorage())==null||e.removeItem(this.key)}};var hi=()=>{let a,e=new ve("hms-analytics-deviceId"),t=e.get();return t?a=t:(a=Oo(),e.set(a)),a};var $s="[VALIDATIONS]";function $(a){return a!=null}var bt=()=>{if(!$(RTCPeerConnection)){let a=S.GenericErrors.MissingRTCPeerConnection();throw l.e($s,a),a}},It=()=>{if(!$(navigator.mediaDevices)){let a=S.GenericErrors.MissingMediaDevices();throw l.e($s,a),a}},Ks=a=>{if(!a.getPublishParams())throw S.GenericErrors.NotConnected("VALIDATION","call addTrack after preview or join is successful")};var qs=_r().version;function At(a="prod",e){let t="web",i=et!=="LOCAL"&&a==="prod"?"prod":"debug";if($e)return js({os:"web_nodejs",os_version:process.version,sdk:t,sdk_version:qs,env:i,domain:et,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:"node",framework_version:process.version,framework_sdk_version:e==null?void 0:e.sdkVersion});let r=Se.getOS(),s=Se.getDevice(),o=Se.getBrowser(),n=Nr(`web_${r.name}`),d=r.version||"",u=Nr(`${o.name}_${o.version}`),p=u;return s.type&&(p=`${Nr(`${s.vendor}_${s.type}`)}/${u}`),js({os:n,os_version:d,sdk:t,sdk_version:qs,device_model:p,env:i,domain:et,is_prebuilt:!!(e!=null&&e.isPrebuilt),framework:e==null?void 0:e.type,framework_version:e==null?void 0:e.version,framework_sdk_version:e==null?void 0:e.sdkVersion})}function Nr(a){return a.replace(/ /g,"_")}var js=(a,e=",")=>Object.keys(a).filter(t=>$(a[t])).map(t=>`${t}:${a[t]}`).join(e);var C=class{constructor({name:e,level:t,properties:i,includesPII:r,timestamp:s}){this.metadata={peer:{},userAgent:At()};this.name=e,this.level=t,this.includesPII=r||!1,this.properties=i||{},this.timestamp=s||new Date().getTime(),this.event_id=Uo(),this.device_id=hi()}toSignalParams(){return{name:this.name,info:M(m({},this.properties),{timestamp:this.timestamp,domain:et}),timestamp:new Date().getTime()}}};var y=class{static connect(e,t,i=new Date,r=new Date,s){let o=this.eventNameFor("connect",e===void 0),n=e?2:1,d=this.getPropertiesWithError(M(m({},t),{[this.KEY_REQUESTED_AT]:i==null?void 0:i.getTime(),[this.KEY_RESPONDED_AT]:r==null?void 0:r.getTime(),endpoint:s}),e);return new C({name:o,level:n,properties:d})}static disconnect(e,t){let i="disconnected",r=e?2:1,s=this.getPropertiesWithError(t,e);return new C({name:i,level:r,properties:s})}static preview(i){var r=i,{error:e}=r,t=Ar(r,["error"]);let s=this.eventNameFor("preview",e===void 0),o=e?2:1,n=this.getPropertiesWithError(t,e);return new C({name:s,level:o,properties:n})}static join(i){var r=i,{error:e}=r,t=Ar(r,["error"]);let s=this.eventNameFor("join",e===void 0),o=e?2:1,n=this.getPropertiesWithError(M(m({},t),{is_preview_called:!!t.is_preview_called}),e);return new C({name:s,level:o,properties:n})}static publish({devices:e,settings:t,error:i}){let r=this.eventNameFor("publish",i===void 0),s=i?2:1,o=this.getPropertiesWithError({devices:e,audio:t==null?void 0:t.audio,video:t==null?void 0:t.video},i);return new C({name:r,level:s,properties:o})}static hlsPlayerError(e){return new C({name:"hlsPlayerError",level:2,properties:this.getErrorProperties(e)})}static subscribeFail(e){let t=this.eventNameFor("subscribe",!1),i=2,r=this.getErrorProperties(e);return new C({name:t,level:i,properties:r})}static leave(){return new C({name:"leave",level:1})}static autoplayError(){return new C({name:"autoplayError",level:2})}static audioPlaybackError(e){return new C({name:"audioPlaybackError",level:2,properties:this.getErrorProperties(e)})}static audioRecovered(e){return new C({name:"audioRecovered",level:1,properties:{message:e}})}static permissionChange(e,t){return new C({name:"permissionChanged",level:1,properties:{message:`Perrmission for ${e} changed to ${t}`}})}static deviceChange({isUserSelection:e,selection:t,type:i,devices:r,error:s}){let o=this.eventNameFor(s?"publish":`device.${i}`,s===void 0),n=s?2:1,d=this.getPropertiesWithError({selection:t,devices:r,isUserSelection:e},s);return new C({name:o,level:n,properties:d})}static performance(e){let t="perf.stats",i=1,r=e.toAnalyticsProperties();return new C({name:t,level:i,properties:r})}static rtcStats(e){let t="rtc.stats",i=1,r=e.toAnalyticsProperties();return new C({name:t,level:i,properties:r})}static rtcStatsFailed(e){let t="rtc.stats.failed",i=2;return new C({name:t,level:i,properties:this.getErrorProperties(e)})}static degradationStats(e,t){let i="video.degradation.stats",r=1,s={degradedAt:e.degradedAt,trackId:e.trackId};if(!t&&e.degradedAt instanceof Date){let o=new Date,n=o.valueOf()-e.degradedAt.valueOf();s=M(m({},s),{duration:n,restoredAt:o})}return new C({name:i,level:r,properties:s})}static audioDetectionFail(e,t){let i=this.getPropertiesWithError({device:t},e),r=2,s="audiopresence.failed";return new C({name:s,level:r,properties:i})}static previewNetworkQuality(e){return new C({name:"perf.networkquality.preview",level:e.error?2:1,properties:e})}static publishStats(e){return new C({name:"publisher.stats",level:1,properties:e})}static subscribeStats(e){return new C({name:"subscriber.stats",level:1,properties:e})}static getKrispUsage(e){return new C({name:"krisp.usage",level:1,properties:{duration:e}})}static krispStart(){return new C({name:"krisp.start",level:1})}static krispStop(){return new C({name:"krisp.stop",level:1})}static interruption({started:e,type:t,reason:i,deviceInfo:r,trackInfo:s}){return new C({name:`${e?"interruption.start":"interruption.stop"}`,level:1,properties:M(m({reason:i,type:t,pageHidden:document.visibilityState==="hidden"},r),{trackInfo:s})})}static mediaConstraints({requestedConstraints:e,appliedConstraints:t,trackSettings:i}){return new C({name:"media.constraints",level:1,properties:{requested_constraints:e,applied_constraints:t,track_settings:i,webgpu_supported:typeof navigator!="undefined"&&"gpu"in navigator,media_stream_track_processor_supported:typeof window!="undefined"&&"MediaStreamTrackProcessor"in window}})}static eventNameFor(e,t){return`${e}.${t?"success":"failed"}`}static getPropertiesWithError(e,t){let i=this.getErrorProperties(t);return e=m(m({},i),e),e}static getErrorProperties(e){return e?e instanceof E?e.toAnalyticsProperties():{error_name:e.name,error_message:e.message,error_description:e.cause}:{}}};y.KEY_REQUESTED_AT="requested_at",y.KEY_RESPONDED_AT="responded_at";var mi=a=>a?`{
trackId: ${a.id};
kind: ${a.kind};
enabled: ${a.enabled};
muted: ${a.muted};
readyState: ${a.readyState};
}`:"";var _e=class{constructor(e,t,i){this.logIdentifier="";this.isTrackNotPublishing=()=>this.nativeTrack.readyState==="ended"||this.nativeTrack.muted;this.stream=e,this.nativeTrack=t,this.source=i}get enabled(){return this.nativeTrack.enabled}get trackId(){return this.firstTrackId||this.sdpTrackId||this.nativeTrack.id}getMediaTrackSettings(){return this.nativeTrack.getSettings()}getPluginsMetrics(){}setEnabled(e){return c(this,null,function*(){this.nativeTrack.enabled=e})}setSdpTrackId(e){this.sdpTrackId=e}setFirstTrackId(e){this.firstTrackId=e}sendInterruptionEvent({started:e,reason:t}){let i=this.nativeTrack;return y.interruption({started:e,type:this.type,reason:t,deviceInfo:{deviceId:i.getSettings().deviceId,groupId:i.getSettings().groupId},trackInfo:{label:i.label,enabled:i.enabled,muted:i.muted,readyState:i.readyState,settings:i.getSettings()}})}cleanup(){var e;l.d("[HMSTrack]","Stopping track",this.toString()),(e=this.nativeTrack)==null||e.stop()}toString(){var e;return`{
streamId: ${this.stream.id};
peerId: ${this.peerId};
trackId: ${this.trackId};
mid: ${((e=this.transceiver)==null?void 0:e.mid)||"-"};
logIdentifier: ${this.logIdentifier};
source: ${this.source};
enabled: ${this.enabled};
nativeTrack: ${mi(this.nativeTrack)};
}`}};var Ne=class extends _e{constructor(t,i,r){super(t,i,r);this.type="audio";this.audioElement=null;if(i.kind!=="audio")throw new Error("Expected 'track' kind = 'audio'")}getVolume(){return this.audioElement?Math.floor(this.audioElement.volume*100):null}setVolume(t){return c(this,null,function*(){if(t<0||t>100)throw Error("Please pass a valid number between 0-100");yield this.subscribeToAudio(t===0?!1:this.enabled),this.audioElement&&(this.audioElement.volume=t/100)})}setAudioElement(t){l.d("[HMSAudioTrack]",this.logIdentifier,"adding audio element",`${this}`,t),this.audioElement=t}getAudioElement(){return this.audioElement}getOutputDevice(){return this.outputDevice}cleanup(){super.cleanup(),this.audioElement&&(this.audioElement.srcObject=null,this.audioElement.remove(),this.audioElement=null)}setOutputDevice(t){return c(this,null,function*(){var i;if(!t){l.d("[HMSAudioTrack]",this.logIdentifier,"device is null",`${this}`);return}if(!this.audioElement){l.d("[HMSAudioTrack]",this.logIdentifier,"no audio element to set output",`${this}`),this.outputDevice=t;return}try{typeof this.audioElement.setSinkId=="function"&&Vs&&(yield(i=this.audioElement)==null?void 0:i.setSinkId(t.deviceId),this.outputDevice=t)}catch(r){l.d("[HMSAudioTrack]","error in setSinkId",r)}})}subscribeToAudio(t){return c(this,null,function*(){this.stream instanceof be&&(yield this.stream.setAudio(t,this.trackId,this.logIdentifier))})}};import qo from"lodash.isequal";var Or=class{constructor(){this.storage=new ve("hms-device-selection");this.remember=!1;this.TAG="[HMSDeviceStorage]"}setDevices(e){var r;if(this.devices=e,!this.remember)return;let t=this.storage.get();if(!t)return;let i=["audioInput","videoInput","audioOutput"];for(let s of i){let o=t[s];o&&((r=e[s])!=null&&r.some(d=>this.isSame(o,d))||(l.w(this.TAG,`Removing ${s} device from storage as it's no longer available: ${o.deviceId}`),this.removeSelection(s)))}}rememberDevices(e){this.remember=e}updateSelection(e,{deviceId:t,groupId:i}){if(!this.devices||!this.remember)return;let r=this.devices[e].find(o=>this.isSame({deviceId:t,groupId:i},o));if(!r){l.w(this.TAG,`Could not find device with deviceId: ${t}, groupId: ${i}`);return}let s=this.storage.get()||{};s[e]=r,this.storage.set(s)}removeSelection(e){let t=this.storage.get()||{};t[e]&&(delete t[e],this.storage.set(t))}getSelection(){if(this.remember)return this.storage.get()}cleanup(){this.remember=!1,this.devices=void 0}isSame(e,t){return e.deviceId===t.deviceId&&(e.groupId===t.groupId||!e.groupId)}},te=new Or;var xr=(t=>(t.TRANSFORM="TRANSFORM",t.ANALYZE="ANALYZE",t))(xr||{}),Ur=(t=>(t.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",t.DEVICE_NOT_SUPPORTED="DEVICE_NOT_SUPPORTED",t))(Ur||{});var ge=class{static failure(e,t){let i="mediaPlugin.failed",r=2,s=m({plugin_name:e},t.toAnalyticsProperties());return new C({name:i,level:r,properties:s})}static audioPluginFailure(e,t,i){let r="mediaPlugin.failed",s=2,o=m({plugin_name:e,sampleRate:t},i.toAnalyticsProperties());return new C({name:r,level:s,properties:o})}static audioPluginStats({pluginName:e,duration:t,loadTime:i,sampleRate:r}){let s="mediaPlugin.stats",o=1,n={plugin_name:e,duration:t,load_time:i,sampleRate:r};return new C({name:s,level:o,properties:n})}static added(e,t){let i="mediaPlugin.added",r=1,s={plugin_name:e,added_at:t};return new C({name:i,level:r,properties:s})}static stats({pluginName:e,duration:t,loadTime:i,avgPreProcessingTime:r,avgProcessingTime:s,inputFrameRate:o,pluginFrameRate:n}){let d="mediaPlugin.stats",u=1,p={plugin_name:e,duration:t,load_time:i,avg_preprocessing_time:r,avg_processing_time:s,input_frame_rate:o,plugin_frame_rate:n};return new C({name:d,level:u,properties:p})}};var Si=class{constructor(e){this.eventBus=e;this.TAG="[AudioPluginsAnalytics]";this.initTime={},this.addedTimestamps={},this.pluginAdded={},this.pluginSampleRate={}}added(e,t){this.pluginAdded[e]=!0,this.addedTimestamps[e]=Date.now(),this.initTime[e]=0,this.pluginSampleRate[e]=t,this.eventBus.analytics.publish(ge.added(e,this.addedTimestamps[e]))}removed(e){if(this.pluginAdded[e]){let t={pluginName:e,duration:Math.floor((Date.now()-this.addedTimestamps[e])/1e3),loadTime:this.initTime[e],sampleRate:this.pluginSampleRate[e]};this.eventBus.analytics.publish(ge.audioPluginStats(t)),this.clean(e)}}failure(e,t){this.pluginAdded[e]&&(this.eventBus.analytics.publish(ge.audioPluginFailure(e,this.pluginSampleRate[e],t)),this.clean(e))}initWithTime(e,t){return c(this,null,function*(){if(this.initTime[e]){l.i(this.TAG,`Plugin Already loaded ${e}, time it took: ${this.initTime[e]}`);return}let i;try{i=yield this.timeInMs(t),l.i(this.TAG,`Time taken for Plugin ${e} initialization : ${i}`)}catch(r){let s=S.MediaPluginErrors.InitFailed("AUDIO_PLUGINS",`failed during initialization of plugin${r.message||r}`);throw l.e(this.TAG,s),this.failure(e,s),s}i&&(this.initTime[e]=i)})}timeInMs(e){return c(this,null,function*(){let t=Date.now();return yield e(),Math.floor(Date.now()-t)})}clean(e){delete this.addedTimestamps[e],delete this.initTime[e],delete this.pluginAdded[e],delete this.pluginSampleRate[e]}};var Rt=class{constructor(e,t,i){this.eventBus=t;this.TAG="[AudioPluginsManager]";this.pluginAddInProgress=!1;this.hmsTrack=e,this.pluginsMap=new Map,this.analytics=new Si(t),this.audioContext=pe.getAudioContext(),this.room=i}getPlugins(){return Array.from(this.pluginsMap.keys())}addPlugin(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(!t){l.w("no name provided by the plugin");return}if(this.pluginAddInProgress){let s=S.MediaPluginErrors.AddAlreadyInProgress("AUDIO_PLUGINS","Add Plugin is already in Progress");throw this.analytics.added(t,this.audioContext.sampleRate),this.analytics.failure(t,s),l.w("can't add another plugin when previous add is in progress"),s}switch(e.getName()){case"HMSKrispPlugin":{if(!((r=this.room)!=null&&r.isNoiseCancellationEnabled)){let s="Krisp Noise Cancellation is not enabled for this room";if(this.pluginsMap.size===0)throw Error(s);l.w(this.TAG,s);return}this.eventBus.analytics.publish(y.krispStart());break}default:}this.pluginAddInProgress=!0;try{yield this.addPluginInternal(e)}finally{this.pluginAddInProgress=!1}})}addPluginInternal(e){return c(this,null,function*(){var i,r;let t=(i=e.getName)==null?void 0:i.call(e);if(this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} already added.`);return}yield this.validateAndThrow(t,e),(r=e.setEventBus)==null||r.call(e,this.eventBus);try{this.pluginsMap.size===0?yield this.initAudioNodes():this.prevAudioNode&&this.prevAudioNode.disconnect(),this.analytics.added(t,this.audioContext.sampleRate),yield this.analytics.initWithTime(t,()=>c(this,null,function*(){return e.init()})),this.pluginsMap.set(t,e),yield this.processPlugin(e),yield this.connectToDestination(),yield this.updateProcessedTrack()}catch(s){throw l.e(this.TAG,"failed to add plugin",s),s}})}validatePlugin(e){return e.checkSupport(this.audioContext)}validateAndThrow(e,t){return c(this,null,function*(){let i=this.validatePlugin(t);if(i.isSupported)l.i(this.TAG,`plugin is supported,- ${t.getName()}`);else if(this.analytics.added(e,this.audioContext.sampleRate),i.errType==="PLATFORM_NOT_SUPPORTED"){let r=S.MediaPluginErrors.PlatformNotSupported("AUDIO_PLUGINS","platform not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}else if(i.errType==="DEVICE_NOT_SUPPORTED"){let r=S.MediaPluginErrors.DeviceNotSupported("AUDIO_PLUGINS","audio device not supported, see docs");throw this.analytics.failure(e,r),yield this.cleanup(),r}})}removePlugin(e){return c(this,null,function*(){switch(e.getName()){case"HMSKrispPlugin":{this.eventBus.analytics.publish(y.krispStop());break}default:break}yield this.removePluginInternal(e),this.pluginsMap.size===0?(yield this.cleanup(),l.i(this.TAG,"No plugins left, stopping plugins loop"),yield this.hmsTrack.setProcessedTrack(void 0)):yield this.reprocessPlugins()})}cleanup(){return c(this,null,function*(){var e,t,i;for(let r of this.pluginsMap.values())yield this.removePluginInternal(r);yield this.hmsTrack.setProcessedTrack(void 0),(e=this.sourceNode)==null||e.disconnect(),(t=this.prevAudioNode)==null||t.disconnect(),(i=this.outputTrack)==null||i.stop(),this.sourceNode=void 0,this.destinationNode=void 0,this.prevAudioNode=void 0,this.outputTrack=void 0})}closeContext(){return c(this,null,function*(){this.audioContext=void 0})}reprocessPlugins(){return c(this,null,function*(){if(this.pluginsMap.size===0||!this.sourceNode)return;let e=Array.from(this.pluginsMap.values());yield this.cleanup(),yield this.initAudioNodes();for(let t of e)yield this.addPlugin(t);yield this.updateProcessedTrack()})}initAudioNodes(){return c(this,null,function*(){if(this.audioContext){let e=new MediaStream([this.hmsTrack.nativeTrack]);this.sourceNode=this.audioContext.createMediaStreamSource(e),this.destinationNode||(this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputTrack=this.destinationNode.stream.getAudioTracks()[0])}})}updateProcessedTrack(){return c(this,null,function*(){try{yield this.hmsTrack.setProcessedTrack(this.outputTrack)}catch(e){throw l.e(this.TAG,"error in setting processed track",e),e}})}processPlugin(e){return c(this,null,function*(){try{let t=yield e.processAudioTrack(this.audioContext,this.prevAudioNode||this.sourceNode);this.prevAudioNode&&this.prevAudioNode.connect(t),this.prevAudioNode=t}catch(t){let i=e.getName();l.e(this.TAG,`error in processing plugin ${i}`,t),yield this.removePluginInternal(e)}})}connectToDestination(){return c(this,null,function*(){try{this.prevAudioNode&&this.destinationNode&&this.prevAudioNode.context===this.destinationNode.context&&this.prevAudioNode.connect(this.destinationNode)}catch(e){l.e(this.TAG,"error in connecting to destination node",e)}})}removePluginInternal(e){return c(this,null,function*(){var i;let t=(i=e.getName)==null?void 0:i.call(e);if(!this.pluginsMap.get(t)){l.w(this.TAG,`plugin - ${t} not found to remove.`);return}l.i(this.TAG,`removing plugin ${t}`),this.pluginsMap.delete(t),e.stop(),this.analytics.removed(t)})}};import{v4 as Wo}from"uuid";var Bo=["init_response_time","ws_connect_time","on_policy_change_time","local_audio_track_time","local_video_track_time","peer_list_time","room_state_time","join_response_time"],gi=class{constructor(){this.eventPerformanceMeasures={}}start(e){try{typeof performance!="undefined"&&performance.mark&&performance.mark(e)}catch(t){l.w("[AnalyticsTimer]",`Error marking performance for event ${e}`,{error:t})}}end(e){var t;try{typeof performance!="undefined"&&performance.measure&&(this.eventPerformanceMeasures[e]=performance.measure(e,e),l.d("[HMSPerformanceTiming]",e,(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration))}catch(i){l.w("[AnalyticsTimer]",`Error in measuring performance for event ${e}`,{error:i})}}getTimeTaken(e){var t;return(t=this.eventPerformanceMeasures[e])==null?void 0:t.duration}getTimes(...e){return[...Bo,...e].reduce((t,i)=>M(m({},t),{[i]:this.getTimeTaken(i)}),{})}cleanup(){this.eventPerformanceMeasures={}}};import Qs from"webrtc-adapter";function Vo(a,e){let t=a.toLowerCase(),i=S.TracksErrors.GenericTrack("TRACK",a);return t.includes("device not found")?i=S.TracksErrors.DeviceNotAvailable("TRACK",e,a):t.includes("permission denied")&&(i=S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a)),i}function Fo(a,e=""){if(Qs.browserDetails.browser==="chrome"&&a.name==="NotAllowedError"&&a.message.includes("denied by system"))return S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);if(Qs.browserDetails.browser==="firefox"&&a.name==="NotFoundError"){let i=S.TracksErrors.SystemDeniedPermission("TRACK",e,a.message);return i.description=`Capture device is either blocked at Operating System level or not available - ${e}`,i}switch(a.name){case"OverconstrainedError":return S.TracksErrors.OverConstrained("TRACK",e,a.constraint);case"NotAllowedError":return S.TracksErrors.CantAccessCaptureDevice("TRACK",e,a.message);case"NotFoundError":return S.TracksErrors.DeviceNotAvailable("TRACK",e,a.message);case"NotReadableError":return S.TracksErrors.DeviceInUse("TRACK",e,a.message);case"TypeError":return S.TracksErrors.NothingToReturn("TRACK",a.message);default:return Vo(a.message,e)}}function Oe(a,e){let t=Fo(a,e);return t.addNativeError(a),t}var Br=(t=>(t.SIP="sip",t.REGULAR="regular",t))(Br||{});var Js=(n=>(n.NONE="none",n.INITIALISED="initialised",n.STARTED="started",n.PAUSED="paused",n.RESUMED="resumed",n.STOPPED="stopped",n.FAILED="failed",n))(Js||{});var zs=(t=>(t.DVR="dvr",t.NO_DVR="no-dvr",t))(zs||{}),Ys=(i=>(i.REGULAR="regular",i.SCREEN="screen",i.COMPOSITE="composite",i))(Ys||{}),Xs=(r=>(r.INITIALISED="initialised",r.STARTED="started",r.STOPPED="stopped",r.FAILED="failed",r))(Xs||{}),Zs=(e=>(e.CAPTION="caption",e))(Zs||{});var Ke={f:"high",h:"medium",q:"low"};var Vr=(t=>(t.VOICE="voice",t.MUSIC="music",t))(Vr||{});var ea=(i=>(i.videoInput="videoInput",i.audioInput="audioInput",i.audioOutput="audioOutput",i))(ea||{});var Y=class{constructor(){this._volume=1;this._codec="opus";this._maxBitrate=32;this._deviceId="default";this._audioMode="voice";this._advanced=[{autoGainControl:{exact:!0}},{noiseSuppression:{exact:!0}},{highpassFilter:{exact:!0}},{audioMirroring:{exact:!0}}]}volume(e){if(!(0<=e&&e<=1))throw Error("volume can only be in range [0.0, 1.0]");return this._volume=e,this}codec(e){return this._codec=e,this}maxBitrate(e){if(e&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=this._audioMode==="music"?320:e,this}deviceId(e){return this._deviceId=e,this}audioMode(e="voice"){return this._audioMode=e,this._audioMode==="music"?this._maxBitrate=320:this._maxBitrate=32,this}advanced(e){return this._advanced=e,this}build(){return new qe(this._volume,this._codec,this._maxBitrate,this._deviceId,this._advanced,this._audioMode)}},qe=class{constructor(e,t,i,r,s,o){this.volume=e,this.codec=t,this.maxBitrate=i,this.deviceId=r,this.advanced=s,this.audioMode=o,this.audioMode==="music"?this.maxBitrate=320:this.maxBitrate=32}toConstraints(){return{deviceId:this.deviceId==="default"?this.deviceId:{exact:this.deviceId},advanced:this.audioMode==="music"?[]:this.advanced}}toAnalyticsProperties(){return{audio_bitrate:this.maxBitrate,audio_codec:this.codec}}};var J=class{constructor(){this._width=320;this._height=180;this._codec="vp8";this._maxFramerate=30;this._maxBitrate=150;this._advanced=[]}setWidth(e){return this._width=e,this}setHeight(e){return this._height=e,this}codec(e){return this._codec=e,this}maxFramerate(e){if(e&&e<=0)throw Error("maxFramerate should be >= 1");return this._maxFramerate=e,this}maxBitrate(e,t=!0){if(typeof e=="number"&&e<=0)throw Error("maxBitrate should be >= 1");return this._maxBitrate=e,!this._maxBitrate&&t&&(this._maxBitrate=15e4),this}deviceId(e){return this._deviceId=e,this}advanced(e){return this._advanced=e,this}facingMode(e){return this._facingMode=e,this}build(){return new je(this._width,this._height,this._codec,this._maxFramerate,this._deviceId,this._advanced,this._maxBitrate,this._facingMode)}},je=class{constructor(e,t,i,r,s,o,n,d){this.width=e,this.height=t,this.codec=i,this.maxFramerate=r,this.maxBitrate=n,this.deviceId=s,this.advanced=o,this.facingMode=d}toConstraints(e){let t="ideal";e&&(t="max");let i=this.improviseConstraintsAspect();return{width:{[t]:i.width},height:{[t]:i.height},frameRate:this.maxFramerate,deviceId:this.deviceId==="default"?this.deviceId:{exact:this.deviceId},facingMode:this.facingMode}}toAnalyticsProperties(){return{width:this.width,height:this.height,video_bitrate:this.maxBitrate,framerate:this.maxFramerate,video_codec:this.codec,facingMode:this.facingMode}}improviseConstraintsAspect(){return Pt()&&this.height&&this.width&&this.height>this.width?{width:this.height,height:this.width}:{width:this.width,height:this.height}}};var xe=class{constructor(){this._video=new J().build();this._audio=new Y().build();this._screen=new J().build();this._simulcast=!1}video(e){return this._video=e,this}audio(e){return this._audio=e,this}screen(e){return this._screen=e,this}simulcast(e){return this._simulcast=e,this}build(){if(this._audio===null&&this._video===null)throw S.TracksErrors.NothingToReturn("TRACK");if(this._video===null&&this._simulcast)throw S.TracksErrors.InvalidVideoSettings("TRACK","Cannot enable simulcast when no video settings are provided");return new tt(this._video,this._audio,this._simulcast,this._screen||void 0)}},tt=class{constructor(e,t,i,r=null){this.video=e,this.audio=t,this.simulcast=i,this.screen=r}toAnalyticsProperties(){let e={audio_enabled:this.audio!==null,video_enabled:this.video!==null};return this.audio&&(e=m(m({},this.audio.toAnalyticsProperties()),e)),this.video&&(e=m(m({},this.video.toAnalyticsProperties()),e)),e}};var Go=32e3;var pe={audioContext:null,getAudioContext(){return this.audioContext||(this.audioContext=Bs?new AudioContext:new AudioContext({sampleRate:Go})),this.audioContext},resumeContext(){return c(this,null,function*(){try{return yield this.getAudioContext().resume()}catch(a){l.e("AudioContext",a)}})}},Fr=(r=>(r.SPEAKERPHONE="SPEAKERPHONE",r.WIRED="WIRED",r.BLUETOOTH="BLUETOOTH",r.EARPIECE="EARPIECE",r))(Fr||{}),Gr=a=>{if(!a)return l.w("[DeviceManager]:","No device label provided"),"SPEAKERPHONE";let e=a.toLowerCase();return e.includes("speakerphone")?"SPEAKERPHONE":e.includes("wired")?"WIRED":/airpods|buds|wireless|bluetooth/gi.test(e)?"BLUETOOTH":e.includes("earpiece")?"EARPIECE":"SPEAKERPHONE"};var Wr={isAudioMuted:!1,isVideoMuted:!1,audioInputDeviceId:"default",audioOutputDeviceId:"default",videoDeviceId:"default",audioMode:"voice"},Me,Ti,Te=class a{constructor(e,t,i,r,s){this.store=e;this.observer=t;this.deviceManager=i;this.eventBus=r;this.analyticsTimer=s;this.TAG="[LocalTrackManager]";this.setScreenCaptureHandleConfig()}getTracksToPublish(){return c(this,arguments,function*(e=Wr){let t=this.getAVTrackSettings(e);if(!t)return[];let i=!!t.audio,r=!!t.video,s=[],{videoTrack:o,audioTrack:n}=yield this.updateCurrentLocalTrackSettings(t),d=(o==null?void 0:o.stream)||(n==null?void 0:n.stream),u=!!(o&&this.store.getTrackById(o.trackId)),p=!!(n&&this.store.getTrackById(n.trackId));if(u&&p)return[];let h={audio:i&&!n&&(e.isAudioMuted?"empty":!0),video:r&&!o&&(e.isVideoMuted?"empty":!0)};h.audio&&this.analyticsTimer.start("local_audio_track_time"),h.video&&this.analyticsTimer.start("local_video_track_time");try{l.d(this.TAG,"Init Local Tracks",{fetchTrackOptions:h}),s=yield this.getLocalTracks(h,t,d)}catch(T){s=yield this.retryGetLocalTracks(T,t,h,d)}return h.audio&&this.analyticsTimer.end("local_audio_track_time"),h.video&&this.analyticsTimer.end("local_video_track_time"),o&&r&&!u&&s.push(o),n&&i&&!p&&s.push(n),s})}getLocalTracks(){return c(this,arguments,function*(e={audio:!0,video:!0},t,i){try{let r=yield this.getNativeLocalTracks(e,t);return this.createHMSLocalTracks(r,t,i)}catch(r){throw this.eventBus.analytics.publish(y.publish({devices:this.deviceManager.getDevices(),error:r,settings:t})),r}})}getNativeLocalTracks(){return c(this,arguments,function*(e={audio:!1,video:!1},t){let i=new tt(e.video===!0?t.video:null,e.audio===!0?t.audio:null,t.simulcast),r=[];return(i.audio||i.video)&&r.push(...yield this.getAVTracks(i)),r.push(...this.getEmptyTracks(e)),r})}optimizeScreenShareConstraint(e,t){return c(this,null,function*(){var s,o,n;if(typeof t.video=="boolean"||!((s=t.video)!=null&&s.width)||!((o=t.video)!=null&&o.height))return;let i=this.store.getPublishParams();if(!i||!((n=i.allowed)!=null&&n.includes("screen")))return;let r=document.createElement("video");r.srcObject=e,r.addEventListener("loadedmetadata",()=>c(this,null,function*(){let{videoWidth:d,videoHeight:u}=r,p=i.screen,h=p.width*p.height,T=d/u,g=p.width/p.height;if(T>g){let f=t.video,P=T/g,v=Math.sqrt(P);d*u>h?(f.width=d/v,f.height=u/v):(f.height=u*v,f.width=d*v),yield e.getVideoTracks()[0].applyConstraints(f)}}))})}getLocalScreen(e,t=!1){return c(this,null,function*(){var T;let i=yield this.getOrDefaultScreenshareConfig(e),r=this.getScreenshareSettings(i.videoOnly),s={video:M(m({},r==null?void 0:r.video.toConstraints(!0)),{displaySurface:i.displaySurface}),preferCurrentTab:i.preferCurrentTab,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio};if(r!=null&&r.audio){let g=(T=r==null?void 0:r.audio)==null?void 0:T.toConstraints();delete g.advanced,s.audio=M(m({},g),{autoGainControl:!1,noiseSuppression:!1,googAutoGainControl:!1,echoCancellation:!1})}else e!=null&&e.forceCurrentTab&&e.preferCurrentTab&&e.cropElement&&(s.audio={echoCancellation:!0,noiseSuppression:!0});let o;try{l.d("retrieving screenshare with ",{config:i},{constraints:s}),o=yield navigator.mediaDevices.getDisplayMedia(s),t&&(yield this.optimizeScreenShareConstraint(o,s))}catch(g){l.w(this.TAG,"error in getting screenshare - ",g);let f=Oe(g,"screen");throw this.eventBus.analytics.publish(y.publish({error:f,devices:this.deviceManager.getDevices(),settings:new tt(r==null?void 0:r.video,r==null?void 0:r.audio,!1)})),f}let n=[],d=new fe(o),u=o.getVideoTracks()[0],p=new K(d,u,"screen",this.eventBus,r==null?void 0:r.video,this.store.getRoom());p.setSimulcastDefinitons(this.store.getSimulcastDefinitionsForPeer(this.store.getLocalPeer(),"screen"));try{let g=this.validateCurrentTabCapture(p