(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){var n=e[i][1][r];return o(n||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;imaxVolume&&fftBins[i]<0){maxVolume=fftBins[i]}}return maxVolume}var audioContextType;if(typeof window!=="undefined"){audioContextType=window.AudioContext||window.webkitAudioContext}var audioContext=null;module.exports=function(stream,options){var harker=new WildEmitter;if(!audioContextType)return harker;var options=options||{},smoothing=options.smoothing||.1,interval=options.interval||50,threshold=options.threshold,play=options.play,history=options.history||10,running=true;audioContext=options.audioContext||audioContext||new audioContextType;var sourceNode,fftBins,analyser;analyser=audioContext.createAnalyser();analyser.fftSize=512;analyser.smoothingTimeConstant=smoothing;fftBins=new Float32Array(analyser.frequencyBinCount);if(stream.jquery)stream=stream[0];if(stream instanceof HTMLAudioElement||stream instanceof HTMLVideoElement){sourceNode=audioContext.createMediaElementSource(stream);if(typeof play==="undefined")play=true;threshold=threshold||-50}else{sourceNode=audioContext.createMediaStreamSource(stream);threshold=threshold||-50}sourceNode.connect(analyser);if(play)analyser.connect(audioContext.destination);harker.speaking=false;harker.suspend=function(){return audioContext.suspend()};harker.resume=function(){return audioContext.resume()};Object.defineProperty(harker,"state",{get:function(){return audioContext.state}});audioContext.onstatechange=function(){harker.emit("state_change",audioContext.state)};harker.setThreshold=function(t){threshold=t};harker.setInterval=function(i){interval=i};harker.stop=function(){running=false;harker.emit("volume_change",-100,threshold);if(harker.speaking){harker.speaking=false;harker.emit("stopped_speaking")}analyser.disconnect();sourceNode.disconnect()};harker.speakingHistory=[];for(var i=0;ithreshold&&!harker.speaking){for(var i=harker.speakingHistory.length-3;i=2){harker.speaking=true;harker.emit("speaking")}}else if(currentVolumethreshold));looper()}),interval)};looper();return harker}},{wildemitter:38}],6:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}}else{module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],7:[function(require,module,exports){var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();function JL(loggerName){if(!loggerName){return JL.__}if(!Array.prototype.reduce){Array.prototype.reduce=function(callback,initialValue){var previousValue=initialValue;for(var i=0;i=this.maxBatchSize){this.nbrLogItemsSkipped+=logItems.length;return}if(!(JL.maxMessages==null)){if(JL.maxMessages<1){return}JL.maxMessages-=logItems.length}this.batchBuffer=this.batchBuffer.concat(logItems);var that=this;setTimer(this.batchTimeoutTimer,this.batchTimeout,(function(){that.sendBatch.call(that)}))};Appender.prototype.batchBufferHasOverdueMessages=function(){for(var i=0;ithis.batchTimeout){return true}}return false};Appender.prototype.batchBufferHasStrandedMessage=function(){return!(JL.maxMessages==null)&&JL.maxMessages<1&&this.batchBuffer.length>0};Appender.prototype.sendBatchIfComplete=function(){if(this.batchBuffer.length>=this.batchSize||this.batchBufferHasOverdueMessages()||this.batchBufferHasStrandedMessage()){this.sendBatch()}};Appender.prototype.onSendingEnded=function(){clearTimer(this.sendTimeoutTimer);this.nbrLogItemsBeingSent=0;this.sendBatchIfComplete()};Appender.prototype.setOptions=function(options){copyProperty("level",options,this);copyProperty("ipRegex",options,this);copyProperty("userAgentRegex",options,this);copyProperty("disallow",options,this);copyProperty("sendWithBufferLevel",options,this);copyProperty("storeInBufferLevel",options,this);copyProperty("bufferSize",options,this);copyProperty("batchSize",options,this);copyProperty("maxBatchSize",options,this);copyProperty("batchTimeout",options,this);copyProperty("sendTimeout",options,this);if(this.bufferSize0){this.buffer.push(logItem);if(this.buffer.length>this.bufferSize){this.buffer.shift()}}return}this.addLogItemsToBuffer([logItem]);if(levelNbr>=this.sendWithBufferLevel){if(this.buffer.length){this.addLogItemsToBuffer(this.buffer);this.buffer.length=0}}this.sendBatchIfComplete()};Appender.prototype.sendBatch=function(){if(this.nbrLogItemsBeingSent>0){return}clearTimer(this.batchTimeoutTimer);if(this.batchBuffer.length==0){return}this.nbrLogItemsBeingSent=this.batchBuffer.length;var that=this;setTimer(this.sendTimeoutTimer,this.sendTimeout,(function(){that.onSendingEnded.call(that)}));this.sendLogItems(this.batchBuffer,(function(){that.batchBuffer.splice(0,that.nbrLogItemsBeingSent);if(that.nbrLogItemsSkipped>0){that.batchBuffer.push(newLogItem(getWarnLevel(),"Lost "+that.nbrLogItemsSkipped+" messages. Either connection with the server was down or logging was disabled via the enabled option. Reduce lost messages by increasing the ajaxAppender option maxBatchSize.",that.appenderName));that.nbrLogItemsSkipped=0}that.onSendingEnded.call(that)}))};return Appender}();JL.Appender=Appender;var AjaxAppender=function(_super){__extends(AjaxAppender,_super);function AjaxAppender(appenderName){return _super.call(this,appenderName,AjaxAppender.prototype.sendLogItemsAjax)||this}AjaxAppender.prototype.setOptions=function(options){copyProperty("url",options,this);copyProperty("beforeSend",options,this);_super.prototype.setOptions.call(this,options);return this};AjaxAppender.prototype.sendLogItemsAjax=function(logItems,successCallback){try{if(!allow(this)){return}if(this.xhr&&this.xhr.readyState!=0&&this.xhr.readyState!=4){this.xhr.abort()}this.xhr=JL._createXMLHttpRequest();var ajaxUrl="/jsnlog.logger";if(!(JL.defaultAjaxUrl==null)){ajaxUrl=JL.defaultAjaxUrl}if(this.url){ajaxUrl=this.url}this.xhr.open("POST",ajaxUrl);this.xhr.setRequestHeader("Content-Type","application/json");this.xhr.setRequestHeader("JSNLog-RequestId",JL.requestId);var that=this;this.xhr.onreadystatechange=function(){if(that.xhr.readyState==4&&(that.xhr.status>=200&&that.xhr.status<300)){successCallback()}};var json={r:JL.requestId,lg:logItems};if(typeof this.beforeSend==="function"){this.beforeSend.call(this,this.xhr,json)}else if(typeof JL.defaultBeforeSend==="function"){JL.defaultBeforeSend.call(this,this.xhr,json)}var finalmsg=JSON.stringify(json);this.xhr.send(finalmsg)}catch(e){}};return AjaxAppender}(Appender);JL.AjaxAppender=AjaxAppender;var ConsoleAppender=function(_super){__extends(ConsoleAppender,_super);function ConsoleAppender(appenderName){return _super.call(this,appenderName,ConsoleAppender.prototype.sendLogItemsConsole)||this}ConsoleAppender.prototype.clog=function(logEntry){JL._console.log(logEntry)};ConsoleAppender.prototype.cerror=function(logEntry){if(JL._console.error){JL._console.error(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cwarn=function(logEntry){if(JL._console.warn){JL._console.warn(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cinfo=function(logEntry){if(JL._console.info){JL._console.info(logEntry)}else{this.clog(logEntry)}};ConsoleAppender.prototype.cdebug=function(logEntry){if(JL._console.debug){JL._console.debug(logEntry)}else{this.cinfo(logEntry)}};ConsoleAppender.prototype.sendLogItemsConsole=function(logItems,successCallback){try{if(!allow(this)){return}if(!JL._console){return}var i;for(i=0;i=this.level&&allow(this)){if(e){excObject=this.buildExceptionObject(e);excObject.logData=stringifyLogObjectFunction(logObject)}else{excObject=logObject}compositeMessage=stringifyLogObject(excObject);if(allowMessage(this,compositeMessage.finalString)){if(this.onceOnly){i=this.onceOnly.length-1;while(i>=0){if(new RegExp(this.onceOnly[i]).test(compositeMessage.finalString)){if(this.seenRegexes[i]){return this}this.seenRegexes[i]=true}i--}}compositeMessage.meta=compositeMessage.meta||{};i=this.appenders.length-1;while(i>=0){this.appenders[i].log(levelToString(level),compositeMessage.msg,compositeMessage.meta,(function(){}),level,compositeMessage.finalString,this.loggerName);i--}}}return this};Logger.prototype.trace=function(logObject){return this.log(getTraceLevel(),logObject)};Logger.prototype.debug=function(logObject){return this.log(getDebugLevel(),logObject)};Logger.prototype.info=function(logObject){return this.log(getInfoLevel(),logObject)};Logger.prototype.warn=function(logObject){return this.log(getWarnLevel(),logObject)};Logger.prototype.error=function(logObject){return this.log(getErrorLevel(),logObject)};Logger.prototype.fatal=function(logObject){return this.log(getFatalLevel(),logObject)};Logger.prototype.fatalException=function(logObject,e){return this.log(getFatalLevel(),logObject,e)};return Logger}();JL.Logger=Logger;function createAjaxAppender(appenderName){return new AjaxAppender(appenderName)}JL.createAjaxAppender=createAjaxAppender;function createConsoleAppender(appenderName){return new ConsoleAppender(appenderName)}JL.createConsoleAppender=createConsoleAppender;var defaultAppender;if(typeof window!=="undefined"){defaultAppender=new AjaxAppender("")}else{defaultAppender=new ConsoleAppender("")}JL.__=new JL.Logger("");JL.__.setOptions({level:JL.getDebugLevel(),appenders:[defaultAppender]})})(JL||(JL={}));if(typeof exports!=="undefined"){exports.__esModule=true;exports.JL=JL}var define;if(typeof define=="function"&&define.amd){define("jsnlog",[],(function(){return JL}))}if(typeof __jsnlog_configure=="function"){__jsnlog_configure(JL)}if(typeof window!=="undefined"&&!window.onerror){window.onerror=function(errorMsg,url,lineNumber,column,errorObj){JL("onerrorLogger").fatalException({msg:"Uncaught Exception",errorMsg:errorMsg?errorMsg.message||errorMsg:"",url:url,"line number":lineNumber,column:column},errorObj);return false}}if(typeof window!=="undefined"&&!window.onunhandledrejection){window.onunhandledrejection=function(event){JL("onerrorLogger").fatalException({msg:"unhandledrejection",errorMsg:event.reason?event.reason.message:event.message||null},event.reason)}}},{}],8:[function(require,module,exports){"use strict";function Mime(){this._types=Object.create(null);this._extensions=Object.create(null);for(let i=0;i1){url=parts[1];parts=parts[0].split(":");output.username=parts[0];output.credential=(input||{}).credential||parts[1]||""}output.url=protocol+url;output.urls=[output.url];return output}},{}],12:[function(require,module,exports){(function(global){(function(){(function(){"use strict";var objectTypes={function:true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var maxSafeInteger=Math.pow(2,53)-1;var reOpera=/\bOpera/;var thisBinding=this;var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var toString=objectProto.toString;function capitalize(string){string=String(string);return string.charAt(0).toUpperCase()+string.slice(1)}function cleanupOS(os,pattern,label){var data={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};if(pattern&&label&&/^Win/i.test(os)&&!/^Windows Phone /i.test(os)&&(data=data[/[\d.]+$/.exec(os)])){os="Windows "+data}os=String(os);if(pattern&&label){os=os.replace(RegExp(pattern,"i"),label)}os=format(os.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").replace(/\b(Chrome OS \w+) [\d.]+\b/,"$1").split(" on ")[0]);return os}function each(object,callback){var index=-1,length=object?object.length:0;if(typeof length=="number"&&length>-1&&length<=maxSafeInteger){while(++index3&&"WebKit"||/\bOpera\b/.test(name)&&(/\bOPR\b/.test(ua)?"Blink":"Presto")||/\b(?:Midori|Nook|Safari)\b/i.test(ua)&&!/^(?:Trident|EdgeHTML)$/.test(layout)&&"WebKit"||!layout&&/\bMSIE\b/i.test(ua)&&(os=="Mac OS"?"Tasman":"Trident")||layout=="WebKit"&&/\bPlayStation\b(?! Vita\b)/i.test(name)&&"NetFront"){layout=[data]}if(name=="IE"&&(data=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua)||0)[1])){name+=" Mobile";os="Windows Phone "+(/\+$/.test(data)?data:data+".x");description.unshift("desktop mode")}else if(/\bWPDesktop\b/i.test(ua)){name="IE Mobile";os="Windows Phone 8.x";description.unshift("desktop mode");version||(version=(/\brv:([\d.]+)/.exec(ua)||0)[1])}else if(name!="IE"&&layout=="Trident"&&(data=/\brv:([\d.]+)/.exec(ua))){if(name){description.push("identifying as "+name+(version?" "+version:""))}name="IE";version=data[1]}if(useFeatures){if(isHostType(context,"global")){if(java){data=java.lang.System;arch=data.getProperty("os.arch");os=os||data.getProperty("os.name")+" "+data.getProperty("os.version")}if(rhino){try{version=context.require("ringo/engine").version.join(".");name="RingoJS"}catch(e){if((data=context.system)&&data.global.system==context.system){name="Narwhal";os||(os=data[0].os||null)}}if(!name){name="Rhino"}}else if(typeof context.process=="object"&&!context.process.browser&&(data=context.process)){if(typeof data.versions=="object"){if(typeof data.versions.electron=="string"){description.push("Node "+data.versions.node);name="Electron";version=data.versions.electron}else if(typeof data.versions.nw=="string"){description.push("Chromium "+version,"Node "+data.versions.node);name="NW.js";version=data.versions.nw}}if(!name){name="Node.js";arch=data.arch;os=data.platform;version=/[\d.]+/.exec(data.version);version=version?version[0]:null}}}else if(getClassOf(data=context.runtime)==airRuntimeClass){name="Adobe AIR";os=data.flash.system.Capabilities.os}else if(getClassOf(data=context.phantom)==phantomClass){name="PhantomJS";version=(data=data.version||null)&&data.major+"."+data.minor+"."+data.patch}else if(typeof doc.documentMode=="number"&&(data=/\bTrident\/(\d+)/i.exec(ua))){version=[version,doc.documentMode];if((data=+data[1]+4)!=version[1]){description.push("IE "+version[1]+" mode");layout&&(layout[1]="");version[1]=data}version=name=="IE"?String(version[1].toFixed(1)):version[0]}else if(typeof doc.documentMode=="number"&&/^(?:Chrome|Firefox)\b/.test(name)){description.push("masking as "+name+" "+version);name="IE";version="11.0";layout=["Trident"];os="Windows"}os=os&&format(os)}if(version&&(data=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version)||/(?:alpha|beta)(?: ?\d)?/i.exec(ua+";"+(useFeatures&&nav.appMinorVersion))||/\bMinefield\b/i.test(ua)&&"a")){prerelease=/b/i.test(data)?"beta":"alpha";version=version.replace(RegExp(data+"\\+?$"),"")+(prerelease=="beta"?beta:alpha)+(/\d+\+?/.exec(data)||"")}if(name=="Fennec"||name=="Firefox"&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(os)){name="Firefox Mobile"}else if(name=="Maxthon"&&version){version=version.replace(/\.[\d.]+/,".x")}else if(/\bXbox\b/i.test(product)){if(product=="Xbox 360"){os=null}if(product=="Xbox 360"&&/\bIEMobile\b/.test(ua)){description.unshift("mobile mode")}}else if((/^(?:Chrome|IE|Opera)$/.test(name)||name&&!product&&!/Browser|Mobi/.test(name))&&(os=="Windows CE"||/Mobi/i.test(ua))){name+=" Mobile"}else if(name=="IE"&&useFeatures){try{if(context.external===null){description.unshift("platform preview")}}catch(e){description.unshift("embedded")}}else if((/\bBlackBerry\b/.test(product)||/\bBB10\b/.test(ua))&&(data=(RegExp(product.replace(/ +/g," *")+"/([.\\d]+)","i").exec(ua)||0)[1]||version)){data=[data,/BB10/.test(ua)];os=(data[1]?(product=null,manufacturer="BlackBerry"):"Device Software")+" "+data[0];version=null}else if(this!=forOwn&&product!="Wii"&&(useFeatures&&opera||/Opera/.test(name)&&/\b(?:MSIE|Firefox)\b/i.test(ua)||name=="Firefox"&&/\bOS X (?:\d+\.){2,}/.test(os)||name=="IE"&&(os&&!/^Win/.test(os)&&version>5.5||/\bWindows XP\b/.test(os)&&version>8||version==8&&!/\bTrident\b/.test(ua)))&&!reOpera.test(data=parse.call(forOwn,ua.replace(reOpera,"")+";"))&&data.name){data="ing as "+data.name+((data=data.version)?" "+data:"");if(reOpera.test(name)){if(/\bIE\b/.test(data)&&os=="Mac OS"){os=null}data="identify"+data}else{data="mask"+data;if(operaClass){name=format(operaClass.replace(/([a-z])([A-Z])/g,"$1 $2"))}else{name="Opera"}if(/\bIE\b/.test(data)){os=null}if(!useFeatures){version=null}}layout=["Presto"];description.push(data)}if(data=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua)||0)[1]){data=[parseFloat(data.replace(/\.(\d)$/,".0$1")),data];if(name=="Safari"&&data[1].slice(-1)=="+"){name="WebKit Nightly";prerelease="alpha";version=data[1].slice(0,-1)}else if(version==data[1]||version==(data[2]=(/\bSafari\/([\d.]+\+?)/i.exec(ua)||0)[1])){version=null}data[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(ua)||0)[1];if(data[0]==537.36&&data[2]==537.36&&parseFloat(data[1])>=28&&layout=="WebKit"){layout=["Blink"]}if(!useFeatures||!likeChrome&&!data[1]){layout&&(layout[1]="like Safari");data=(data=data[0],data<400?1:data<500?2:data<526?3:data<533?4:data<534?"4+":data<535?5:data<537?6:data<538?7:data<601?8:data<602?9:data<604?10:data<606?11:data<608?12:"12")}else{layout&&(layout[1]="like Chrome");data=data[1]||(data=data[0],data<530?1:data<532?2:data<532.05?3:data<533?4:data<534.03?5:data<534.07?6:data<534.1?7:data<534.13?8:data<534.16?9:data<534.24?10:data<534.3?11:data<535.01?12:data<535.02?"13+":data<535.07?15:data<535.11?16:data<535.19?17:data<536.05?18:data<536.1?19:data<537.01?20:data<537.11?"21+":data<537.13?23:data<537.18?24:data<537.24?25:data<537.36?26:layout!="Blink"?"27":"28")}layout&&(layout[1]+=" "+(data+=typeof data=="number"?".x":/[.+]/.test(data)?"":"+"));if(name=="Safari"&&(!version||parseInt(version)>45)){version=data}else if(name=="Chrome"&&/\bHeadlessChrome/i.test(ua)){description.unshift("headless")}}if(name=="Opera"&&(data=/\bzbov|zvav$/.exec(os))){name+=" ";description.unshift("desktop mode");if(data=="zvav"){name+="Mini";version=null}else{name+="Mobile"}os=os.replace(RegExp(" *"+data+"$"),"")}else if(name=="Safari"&&/\bChrome\b/.exec(layout&&layout[1])){description.unshift("desktop mode");name="Chrome Mobile";version=null;if(/\bOS X\b/.test(os)){manufacturer="Apple";os="iOS 4.3+"}else{os=null}}else if(/\bSRWare Iron\b/.test(name)&&!version){version=getVersion("Chrome")}if(version&&version.indexOf(data=/[\d.]+$/.exec(os))==0&&ua.indexOf("/"+data+"-")>-1){os=trim(os.replace(data,""))}if(os&&os.indexOf(name)!=-1&&!RegExp(name+" OS").test(os)){os=os.replace(RegExp(" *"+qualify(name)+" *"),"")}if(layout&&!/\b(?:Avant|Nook)\b/.test(name)&&(/Browser|Lunascape|Maxthon/.test(name)||name!="Safari"&&/^iOS/.test(os)&&/\bSafari\b/.test(layout[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(name)&&layout[1])){(data=layout[layout.length-1])&&description.push(data)}if(description.length){description=["("+description.join("; ")+")"]}if(manufacturer&&product&&product.indexOf(manufacturer)<0){description.push("on "+manufacturer)}if(product){description.push((/^on /.test(description[description.length-1])?"":"on ")+product)}if(os){data=/ ([\d.+]+)$/.exec(os);isSpecialCasedOS=data&&os.charAt(os.length-data[0].length-1)=="/";os={architecture:32,family:data&&!isSpecialCasedOS?os.replace(data[0],""):os,version:data?data[1]:null,toString:function(){var version=this.version;return this.family+(version&&!isSpecialCasedOS?" "+version:"")+(this.architecture==64?" 64-bit":"")}}}if((data=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch))&&!/\bi686\b/i.test(arch)){if(os){os.architecture=64;os.family=os.family.replace(RegExp(" *"+data),"")}if(name&&(/\bWOW64\b/i.test(ua)||useFeatures&&/\w(?:86|32)$/.test(nav.cpuClass||nav.platform)&&!/\bWin64; x64\b/i.test(ua))){description.unshift("32-bit")}}else if(os&&/^OS X/.test(os.family)&&name=="Chrome"&&parseFloat(version)>=39){os.architecture=64}ua||(ua=null);var platform={};platform.description=ua;platform.layout=layout&&layout[0];platform.manufacturer=manufacturer;platform.name=name;platform.prerelease=prerelease;platform.product=product;platform.ua=ua;platform.version=name&&version;platform.os=os||{architecture:null,family:null,version:null,toString:function(){return"null"}};platform.parse=parse;platform.toString=toStringPlatform;if(platform.version){description.unshift(version)}if(platform.name){description.unshift(name)}if(os&&name&&!(os==String(os).split(" ")[0]&&(os==name.split(" ")[0]||product))){description.push(product?"("+os+")":"on "+os)}if(description.length){platform.description=description.join(" ")}return platform}var platform=parse();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root.platform=platform;define((function(){return platform}))}else if(freeExports&&freeModule){forOwn(platform,(function(value,key){freeExports[key]=value}))}else{root.platform=platform}}).call(this)}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],13:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;iMAX_LENGTH){throw new TypeError(`version is longer than ${MAX_LENGTH} characters`)}debug("SemVer",version,options);this.options=options;this.loose=!!options.loose;this.includePrerelease=!!options.includePrerelease;const m=version.trim().match(options.loose?re[t.LOOSE]:re[t.FULL]);if(!m){throw new TypeError(`Invalid Version: ${version}`)}this.raw=version;this.major=+m[1];this.minor=+m[2];this.patch=+m[3];if(this.major>MAX_SAFE_INTEGER||this.major<0){throw new TypeError("Invalid major version")}if(this.minor>MAX_SAFE_INTEGER||this.minor<0){throw new TypeError("Invalid minor version")}if(this.patch>MAX_SAFE_INTEGER||this.patch<0){throw new TypeError("Invalid patch version")}if(!m[4]){this.prerelease=[]}else{this.prerelease=m[4].split(".").map((id=>{if(/^[0-9]+$/.test(id)){const num=+id;if(num>=0&&num=0){if(typeof this.prerelease[i]==="number"){this.prerelease[i]++;i=-2}}if(i===-1){this.prerelease.push(0)}}if(identifier){if(compareIdentifiers(this.prerelease[0],identifier)===0){if(isNaN(this.prerelease[1])){this.prerelease=[identifier,0]}}else{this.prerelease=[identifier,0]}}break;default:throw new Error(`invalid increment argument: ${release}`)}this.format();this.raw=this.version;return this}}module.exports=SemVer},{"../internal/constants":17,"../internal/debug":18,"../internal/identifiers":19,"../internal/parse-options":20,"../internal/re":21}],15:[function(require,module,exports){const SemVer=require("../classes/semver");const major=(a,loose)=>new SemVer(a,loose).major;module.exports=major},{"../classes/semver":14}],16:[function(require,module,exports){const SemVer=require("../classes/semver");const minor=(a,loose)=>new SemVer(a,loose).minor;module.exports=minor},{"../classes/semver":14}],17:[function(require,module,exports){const SEMVER_SPEC_VERSION="2.0.0";const MAX_LENGTH=256;const MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991;const MAX_SAFE_COMPONENT_LENGTH=16;module.exports={SEMVER_SPEC_VERSION:SEMVER_SPEC_VERSION,MAX_LENGTH:MAX_LENGTH,MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MAX_SAFE_COMPONENT_LENGTH:MAX_SAFE_COMPONENT_LENGTH}},{}],18:[function(require,module,exports){(function(process){(function(){const debug=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...args)=>console.error("SEMVER",...args):()=>{};module.exports=debug}).call(this)}).call(this,require("_process"))},{_process:13}],19:[function(require,module,exports){const numeric=/^[0-9]+$/;const compareIdentifiers=(a,b)=>{const anum=numeric.test(a);const bnum=numeric.test(b);if(anum&&bnum){a=+a;b=+b}return a===b?0:anum&&!bnum?-1:bnum&&!anum?1:acompareIdentifiers(b,a);module.exports={compareIdentifiers:compareIdentifiers,rcompareIdentifiers:rcompareIdentifiers}},{}],20:[function(require,module,exports){const opts=["includePrerelease","loose","rtl"];const parseOptions=options=>!options?{}:typeof options!=="object"?{loose:true}:opts.filter((k=>options[k])).reduce(((o,k)=>{o[k]=true;return o}),{});module.exports=parseOptions},{}],21:[function(require,module,exports){const{MAX_SAFE_COMPONENT_LENGTH:MAX_SAFE_COMPONENT_LENGTH}=require("./constants");const debug=require("./debug");exports=module.exports={};const re=exports.re=[];const src=exports.src=[];const t=exports.t={};let R=0;const createToken=(name,value,isGlobal)=>{const index=R++;debug(name,index,value);t[name]=index;src[index]=value;re[index]=new RegExp(value,isGlobal?"g":undefined)};createToken("NUMERICIDENTIFIER","0|[1-9]\\d*");createToken("NUMERICIDENTIFIERLOOSE","[0-9]+");createToken("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*");createToken("MAINVERSION",`(${src[t.NUMERICIDENTIFIER]})\\.`+`(${src[t.NUMERICIDENTIFIER]})\\.`+`(${src[t.NUMERICIDENTIFIER]})`);createToken("MAINVERSIONLOOSE",`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.`+`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.`+`(${src[t.NUMERICIDENTIFIERLOOSE]})`);createToken("PRERELEASEIDENTIFIER",`(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASEIDENTIFIERLOOSE",`(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`);createToken("PRERELEASE",`(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);createToken("PRERELEASELOOSE",`(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);createToken("BUILDIDENTIFIER","[0-9A-Za-z-]+");createToken("BUILD",`(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);createToken("FULLPLAIN",`v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);createToken("FULL",`^${src[t.FULLPLAIN]}$`);createToken("LOOSEPLAIN",`[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);createToken("LOOSE",`^${src[t.LOOSEPLAIN]}$`);createToken("GTLT","((?:<|>)?=?)");createToken("XRANGEIDENTIFIERLOOSE",`${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);createToken("XRANGEIDENTIFIER",`${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);createToken("XRANGEPLAIN",`[v=\\s]*(${src[t.XRANGEIDENTIFIER]})`+`(?:\\.(${src[t.XRANGEIDENTIFIER]})`+`(?:\\.(${src[t.XRANGEIDENTIFIER]})`+`(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?`+`)?)?`);createToken("XRANGEPLAINLOOSE",`[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})`+`(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?`+`)?)?`);createToken("XRANGE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);createToken("XRANGELOOSE",`^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);createToken("COERCE",`${"(^|[^\\d])"+"(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})`+`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`+`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`+`(?:$|[^\\d])`);createToken("COERCERTL",src[t.COERCE],true);createToken("LONETILDE","(?:~>?)");createToken("TILDETRIM",`(\\s*)${src[t.LONETILDE]}\\s+`,true);exports.tildeTrimReplace="$1~";createToken("TILDE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);createToken("TILDELOOSE",`^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("LONECARET","(?:\\^)");createToken("CARETTRIM",`(\\s*)${src[t.LONECARET]}\\s+`,true);exports.caretTrimReplace="$1^";createToken("CARET",`^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);createToken("CARETLOOSE",`^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);createToken("COMPARATORLOOSE",`^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);createToken("COMPARATOR",`^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);createToken("COMPARATORTRIM",`(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`,true);exports.comparatorTrimReplace="$1$2$3";createToken("HYPHENRANGE",`^\\s*(${src[t.XRANGEPLAIN]})`+`\\s+-\\s+`+`(${src[t.XRANGEPLAIN]})`+`\\s*$`);createToken("HYPHENRANGELOOSE",`^\\s*(${src[t.XRANGEPLAINLOOSE]})`+`\\s+-\\s+`+`(${src[t.XRANGEPLAINLOOSE]})`+`\\s*$`);createToken("STAR","(<|>)?=?\\s*\\*");createToken("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");createToken("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},{"./constants":17,"./debug":18}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"NIL",{enumerable:true,get:function(){return _nil.default}});Object.defineProperty(exports,"parse",{enumerable:true,get:function(){return _parse.default}});Object.defineProperty(exports,"stringify",{enumerable:true,get:function(){return _stringify.default}});Object.defineProperty(exports,"v1",{enumerable:true,get:function(){return _v.default}});Object.defineProperty(exports,"v3",{enumerable:true,get:function(){return _v2.default}});Object.defineProperty(exports,"v4",{enumerable:true,get:function(){return _v3.default}});Object.defineProperty(exports,"v5",{enumerable:true,get:function(){return _v4.default}});Object.defineProperty(exports,"validate",{enumerable:true,get:function(){return _validate.default}});Object.defineProperty(exports,"version",{enumerable:true,get:function(){return _version.default}});var _v=_interopRequireDefault(require("./v1.js"));var _v2=_interopRequireDefault(require("./v3.js"));var _v3=_interopRequireDefault(require("./v4.js"));var _v4=_interopRequireDefault(require("./v5.js"));var _nil=_interopRequireDefault(require("./nil.js"));var _version=_interopRequireDefault(require("./version.js"));var _validate=_interopRequireDefault(require("./validate.js"));var _stringify=_interopRequireDefault(require("./stringify.js"));var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}},{"./nil.js":25,"./parse.js":26,"./stringify.js":30,"./v1.js":31,"./v3.js":32,"./v4.js":34,"./v5.js":35,"./validate.js":36,"./version.js":37}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;function md5(bytes){if(typeof bytes==="string"){const msg=unescape(encodeURIComponent(bytes));bytes=new Uint8Array(msg.length);for(let i=0;i>5]>>>i%32&255;const hex=parseInt(hexTab.charAt(x>>>4&15)+hexTab.charAt(x&15),16);output.push(hex)}return output}function getOutputLength(inputLength8){return(inputLength8+64>>>9<<4)+14+1}function wordsToMd5(x,len){x[len>>5]|=128<>5]|=(input[i/8]&255)<>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}function bitRotateLeft(num,cnt){return num<>>32-cnt}function md5cmn(q,a,b,x,s,t){return safeAdd(bitRotateLeft(safeAdd(safeAdd(a,q),safeAdd(x,t)),s),b)}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t)}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t)}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t)}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t)}var _default=md5;exports.default=_default},{}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;const randomUUID=typeof crypto!=="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var _default={randomUUID:randomUUID};exports.default=_default},{}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default="00000000-0000-0000-0000-000000000000";exports.default=_default},{}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function parse(uuid){if(!(0,_validate.default)(uuid)){throw TypeError("Invalid UUID")}let v;const arr=new Uint8Array(16);arr[0]=(v=parseInt(uuid.slice(0,8),16))>>>24;arr[1]=v>>>16&255;arr[2]=v>>>8&255;arr[3]=v&255;arr[4]=(v=parseInt(uuid.slice(9,13),16))>>>8;arr[5]=v&255;arr[6]=(v=parseInt(uuid.slice(14,18),16))>>>8;arr[7]=v&255;arr[8]=(v=parseInt(uuid.slice(19,23),16))>>>8;arr[9]=v&255;arr[10]=(v=parseInt(uuid.slice(24,36),16))/1099511627776&255;arr[11]=v/4294967296&255;arr[12]=v>>>24&255;arr[13]=v>>>16&255;arr[14]=v>>>8&255;arr[15]=v&255;return arr}var _default=parse;exports.default=_default},{"./validate.js":36}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;exports.default=_default},{}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=rng;let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){getRandomValues=typeof crypto!=="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto);if(!getRandomValues){throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported")}}return getRandomValues(rnds8)}},{}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z}}function ROTL(x,n){return x<>>32-n}function sha1(bytes){const K=[1518500249,1859775393,2400959708,3395469782];const H=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof bytes==="string"){const msg=unescape(encodeURIComponent(bytes));bytes=[];for(let i=0;i>>0;e=d;d=c;c=ROTL(b,30)>>>0;b=a;a=T}H[0]=H[0]+a>>>0;H[1]=H[1]+b>>>0;H[2]=H[2]+c>>>0;H[3]=H[3]+d>>>0;H[4]=H[4]+e>>>0}return[H[0]>>24&255,H[0]>>16&255,H[0]>>8&255,H[0]&255,H[1]>>24&255,H[1]>>16&255,H[1]>>8&255,H[1]&255,H[2]>>24&255,H[2]>>16&255,H[2]>>8&255,H[2]&255,H[3]>>24&255,H[3]>>16&255,H[3]>>8&255,H[3]&255,H[4]>>24&255,H[4]>>16&255,H[4]>>8&255,H[4]&255]}var _default=sha1;exports.default=_default},{}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;exports.unsafeStringify=unsafeStringify;var _validate=_interopRequireDefault(require("./validate.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const byteToHex=[];for(let i=0;i<256;++i){byteToHex.push((i+256).toString(16).slice(1))}function unsafeStringify(arr,offset=0){return(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase()}function stringify(arr,offset=0){const uuid=unsafeStringify(arr,offset);if(!(0,_validate.default)(uuid)){throw TypeError("Stringified UUID is invalid")}return uuid}var _default=stringify;exports.default=_default},{"./validate.js":36}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _stringify=require("./stringify.js");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}let _nodeId;let _clockseq;let _lastMSecs=0;let _lastNSecs=0;function v1(options,buf,offset){let i=buf&&offset||0;const b=buf||new Array(16);options=options||{};let node=options.node||_nodeId;let clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;if(node==null||clockseq==null){const seedBytes=options.random||(options.rng||_rng.default)();if(node==null){node=_nodeId=[seedBytes[0]|1,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]]}if(clockseq==null){clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&16383}}let msecs=options.msecs!==undefined?options.msecs:Date.now();let nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;const dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&16383}if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0}if(nsecs>=1e4){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec")}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=122192928e5;const tl=((msecs&268435455)*1e4+nsecs)%4294967296;b[i++]=tl>>>24&255;b[i++]=tl>>>16&255;b[i++]=tl>>>8&255;b[i++]=tl&255;const tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255;b[i++]=tmh&255;b[i++]=tmh>>>24&15|16;b[i++]=tmh>>>16&255;b[i++]=clockseq>>>8|128;b[i++]=clockseq&255;for(let n=0;n<6;++n){b[i+n]=node[n]}return buf||(0,_stringify.unsafeStringify)(b)}var _default=v1;exports.default=_default},{"./rng.js":28,"./stringify.js":30}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}const v3=(0,_v.default)("v3",48,_md.default);var _default=v3;exports.default=_default},{"./md5.js":23,"./v35.js":33}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.URL=exports.DNS=void 0;exports.default=v35;var _stringify=require("./stringify.js");var _parse=_interopRequireDefault(require("./parse.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function stringToBytes(str){str=unescape(encodeURIComponent(str));const bytes=[];for(let i=0;i0){_this.chunks.push(e.data)}};_this.mediaRecorder.onerror=function(e){logger.error("MediaRecorder error: ",e)};_this.mediaRecorder.onstart=function(){logger.log("MediaRecorder started (state="+_this.mediaRecorder.state+")")};_this.mediaRecorder.onstop=function(){_this.onStopDefault()};_this.mediaRecorder.onpause=function(){logger.log("MediaRecorder paused (state="+_this.mediaRecorder.state+")")};_this.mediaRecorder.onresume=function(){logger.log("MediaRecorder resumed (state="+_this.mediaRecorder.state+")")};_this.state=LocalRecorderState_1.LocalRecorderState.RECORDING;return resolve()}))};LocalRecorder.prototype.stop=function(){var _this=this;return new Promise((function(resolve,reject){try{if(_this.state===LocalRecorderState_1.LocalRecorderState.READY||_this.state===LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.stop()' needs 'LocalRecord.state' to be 'RECORDING' or 'PAUSED' (current value: '"+_this.state+"'). Call 'LocalRecorder.start()' before")}_this.mediaRecorder.onstop=function(){_this.onStopDefault();return resolve()};_this.mediaRecorder.stop()}catch(e){return reject(e)}}))};LocalRecorder.prototype.pause=function(){var _this=this;return new Promise((function(resolve,reject){try{if(_this.state!==LocalRecorderState_1.LocalRecorderState.RECORDING){return reject(Error("'LocalRecord.pause()' needs 'LocalRecord.state' to be 'RECORDING' (current value: '"+_this.state+"'). Call 'LocalRecorder.start()' or 'LocalRecorder.resume()' before"))}_this.mediaRecorder.pause();_this.state=LocalRecorderState_1.LocalRecorderState.PAUSED;return resolve()}catch(error){return reject(error)}}))};LocalRecorder.prototype.resume=function(){var _this=this;return new Promise((function(resolve,reject){try{if(_this.state!==LocalRecorderState_1.LocalRecorderState.PAUSED){throw Error("'LocalRecord.resume()' needs 'LocalRecord.state' to be 'PAUSED' (current value: '"+_this.state+"'). Call 'LocalRecorder.pause()' before")}_this.mediaRecorder.resume();_this.state=LocalRecorderState_1.LocalRecorderState.RECORDING;return resolve()}catch(error){return reject(error)}}))};LocalRecorder.prototype.preview=function(parentElement){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.preview()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before")}this.videoPreview=document.createElement("video");this.videoPreview.id=this.id;this.videoPreview.autoplay=true;if(platform.isSafariBrowser()){this.videoPreview.playsInline=true}if(typeof parentElement==="string"){var parentElementDom=document.getElementById(parentElement);if(parentElementDom){this.videoPreview=parentElementDom.appendChild(this.videoPreview)}}else{this.videoPreview=parentElement.appendChild(this.videoPreview)}this.videoPreview.src=this.videoPreviewSrc;return this.videoPreview};LocalRecorder.prototype.clean=function(){var _this=this;var f=function(){delete _this.blob;_this.chunks=[];_this.state=LocalRecorderState_1.LocalRecorderState.READY};if(this.state===LocalRecorderState_1.LocalRecorderState.RECORDING||this.state===LocalRecorderState_1.LocalRecorderState.PAUSED){this.stop().then((function(){return f()})).catch((function(){return f()}))}else{f()}};LocalRecorder.prototype.download=function(){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("'LocalRecord.download()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+this.state+"'). Call 'LocalRecorder.stop()' before")}else{var a=document.createElement("a");a.style.display="none";document.body.appendChild(a);var url=globalThis.URL.createObjectURL(this.blob);a.href=url;a.download=this.id+"."+Mime.getExtension(this.blob.type);a.click();globalThis.URL.revokeObjectURL(url);document.body.removeChild(a)}};LocalRecorder.prototype.getBlob=function(){if(this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){throw Error("Call 'LocalRecord.stop()' before getting Blob file")}else{return this.blob}};LocalRecorder.prototype.uploadAsBinary=function(endpoint,headers){var _this=this;return new Promise((function(resolve,reject){if(_this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){return reject(Error("'LocalRecord.uploadAsBinary()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+_this.state+"'). Call 'LocalRecorder.stop()' before"))}else{var http_1=new XMLHttpRequest;http_1.open("POST",endpoint,true);if(typeof headers==="object"){for(var _i=0,_a=Object.keys(headers);_i<_a.length;_i++){var key=_a[_i];http_1.setRequestHeader(key,headers[key])}}http_1.onreadystatechange=function(){if(http_1.readyState===4){if(http_1.status.toString().charAt(0)==="2"){return resolve(http_1.responseText)}else{return reject(http_1.status)}}};http_1.send(_this.blob)}}))};LocalRecorder.prototype.uploadAsMultipartfile=function(endpoint,headers){var _this=this;return new Promise((function(resolve,reject){if(_this.state!==LocalRecorderState_1.LocalRecorderState.FINISHED){return reject(Error("'LocalRecord.uploadAsMultipartfile()' needs 'LocalRecord.state' to be 'FINISHED' (current value: '"+_this.state+"'). Call 'LocalRecorder.stop()' before"))}else{var http_2=new XMLHttpRequest;http_2.open("POST",endpoint,true);if(typeof headers==="object"){for(var _i=0,_a=Object.keys(headers);_i<_a.length;_i++){var key=_a[_i];http_2.setRequestHeader(key,headers[key])}}var sendable=new FormData;sendable.append("file",_this.blob,_this.id+"."+Mime.getExtension(_this.blob.type));http_2.onreadystatechange=function(){if(http_2.readyState===4){if(http_2.status.toString().charAt(0)==="2"){return resolve(http_2.responseText)}else{return reject(http_2.status)}}};http_2.send(sendable)}}))};LocalRecorder.prototype.onStopDefault=function(){logger.log("MediaRecorder stopped (state="+this.mediaRecorder.state+")");this.blob=new Blob(this.chunks,{type:this.mediaRecorder.mimeType});this.chunks=[];this.videoPreviewSrc=globalThis.URL.createObjectURL(this.blob);this.state=LocalRecorderState_1.LocalRecorderState.FINISHED};return LocalRecorder}();exports.LocalRecorder=LocalRecorder},{"../OpenViduInternal/Enums/LocalRecorderState":52,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"mime/lite":9}],46:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]MAX_ATTEMPTS){clearTimeout(repeatUntilChangeOrMaxAttempts)}publisher.getVideoDimensions().then((function(newDimensions){if(newDimensions.width!==oldWidth||newDimensions.height!==oldHeight){clearTimeout(repeatUntilChangeOrMaxAttempts);_this.sendVideoDimensionsChangedEvent(publisher,reason,oldWidth,oldHeight,newDimensions.width,newDimensions.height)}}))}),WAIT_INTERVAL)};OpenVidu.prototype.sendVideoDimensionsChangedEvent=function(publisher,reason,oldWidth,oldHeight,newWidth,newHeight){var _this=this;publisher.stream.videoDimensions={width:newWidth||0,height:newHeight||0};this.sendRequest("streamPropertyChanged",{streamId:publisher.stream.streamId,property:"videoDimensions",newValue:JSON.stringify(publisher.stream.videoDimensions),reason:reason},(function(error,response){if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{_this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(_this.session,publisher.stream,"videoDimensions",publisher.stream.videoDimensions,{width:oldWidth,height:oldHeight},reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,"videoDimensions",publisher.stream.videoDimensions,{width:oldWidth,height:oldHeight},reason)]);_this.session.sendVideoData(publisher)}}))};OpenVidu.prototype.sendTrackChangedEvent=function(publisher,oldLabel,newLabel,propertyType){var _this=this;var oldValue={label:oldLabel};var newValue={label:newLabel};var reason="trackReplaced";if(publisher.stream.isLocalStreamPublished){this.sendRequest("streamPropertyChanged",{streamId:publisher.stream.streamId,property:propertyType,newValue:newValue,reason:reason},(function(error,response){if(error){logger.error("Error sending 'streamPropertyChanged' event",error)}else{_this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(_this.session,publisher.stream,propertyType,newValue,oldValue,reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,propertyType,newValue,oldValue,reason)])}}))}else{this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(this.session,publisher.stream,propertyType,newValue,oldValue,reason)]);publisher.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(publisher,publisher.stream,propertyType,newValue,oldValue,reason)])}};OpenVidu.prototype.generateMediaConstraints=function(publisherProperties){var _this=this;return new Promise((function(resolve,reject){var myConstraints={audioTrack:undefined,videoTrack:undefined,constraints:{audio:undefined,video:undefined}};var audioSource=publisherProperties.audioSource;var videoSource=publisherProperties.videoSource;if(audioSource===null||audioSource===false){myConstraints.constraints.audio=false}if(videoSource===null||videoSource===false){myConstraints.constraints.video=false}if(myConstraints.constraints.audio===false&&myConstraints.constraints.video===false){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.NO_INPUT_SOURCE_SET,"Properties 'audioSource' and 'videoSource' cannot be set to false or null at the same time"))}if(typeof MediaStreamTrack!=="undefined"&&audioSource instanceof MediaStreamTrack){myConstraints.audioTrack=audioSource}if(typeof MediaStreamTrack!=="undefined"&&videoSource instanceof MediaStreamTrack){myConstraints.videoTrack=videoSource}if(audioSource===undefined){myConstraints.constraints.audio=true}if(videoSource===undefined){myConstraints.constraints.video={width:{ideal:640},height:{ideal:480}}}if(videoSource!==null&&videoSource!==false){if(!!publisherProperties.resolution){var widthAndHeight=publisherProperties.resolution.toLowerCase().split("x");var idealWidth=Number(widthAndHeight[0]);var idealHeight=Number(widthAndHeight[1]);myConstraints.constraints.video={width:{ideal:idealWidth},height:{ideal:idealHeight}}}if(!!publisherProperties.frameRate){myConstraints.constraints.video.frameRate={ideal:publisherProperties.frameRate}}}_this.configureDeviceIdOrScreensharing(myConstraints,publisherProperties,resolve,reject);return resolve(myConstraints)}))};OpenVidu.prototype.startWs=function(onConnectSucces){var config={heartbeat:5e3,ws:{uri:this.wsUri+"?sessionId="+this.session.sessionId,onconnected:onConnectSucces,ondisconnect:this.disconnectCallback.bind(this),onreconnecting:this.reconnectingCallback.bind(this),onreconnected:this.reconnectedCallback.bind(this),ismasternodecrashed:this.isMasterNodeCrashed.bind(this)},rpc:{requestTimeout:1e4,heartbeatRequestTimeout:5e3,participantJoined:this.session.onParticipantJoined.bind(this.session),participantPublished:this.session.onParticipantPublished.bind(this.session),participantUnpublished:this.session.onParticipantUnpublished.bind(this.session),participantLeft:this.session.onParticipantLeft.bind(this.session),participantEvicted:this.session.onParticipantEvicted.bind(this.session),recordingStarted:this.session.onRecordingStarted.bind(this.session),recordingStopped:this.session.onRecordingStopped.bind(this.session),broadcastStarted:this.session.onBroadcastStarted.bind(this.session),broadcastStopped:this.session.onBroadcastStopped.bind(this.session),sendMessage:this.session.onNewMessage.bind(this.session),streamPropertyChanged:this.session.onStreamPropertyChanged.bind(this.session),connectionPropertyChanged:this.session.onConnectionPropertyChanged.bind(this.session),networkQualityLevelChanged:this.session.onNetworkQualityLevelChangedChanged.bind(this.session),filterEventDispatched:this.session.onFilterEventDispatched.bind(this.session),iceCandidate:this.session.recvIceCandidate.bind(this.session),mediaError:this.session.onMediaError.bind(this.session),masterNodeCrashedNotification:this.onMasterNodeCrashedNotification.bind(this),forciblyReconnectSubscriber:this.session.onForciblyReconnectSubscriber.bind(this.session),speechToTextMessage:this.session.onSpeechToTextMessage.bind(this.session),speechToTextDisconnected:this.session.onSpeechToTextDisconnected.bind(this.session)}};this.jsonRpcClient=new RpcBuilder.clients.JsonRpcClient(config)};OpenVidu.prototype.onMasterNodeCrashedNotification=function(response){console.error("Master Node has crashed");this.masterNodeHasCrashed=true;this.session.onLostConnection("nodeCrashed");this.jsonRpcClient.close(4103,"Master Node has crashed")};OpenVidu.prototype.getWsReadyState=function(){return this.jsonRpcClient.getReadyState()};OpenVidu.prototype.closeWs=function(){this.jsonRpcClient.close(4102,"Connection closed by client")};OpenVidu.prototype.sendRequest=function(method,params,callback){var _a;if(params&¶ms instanceof Function){callback=params;params={}}logger.debug('Sending request: {method:"'+method+'", params: '+JSON.stringify(params)+"}");(_a=this.jsonRpcClient)===null||_a===void 0?void 0:_a.send(method,params,callback)};OpenVidu.prototype.getWsUri=function(){return this.wsUri};OpenVidu.prototype.getSecret=function(){return this.secret};OpenVidu.prototype.getRecorder=function(){return this.recorder};OpenVidu.prototype.getStt=function(){return this.stt};OpenVidu.prototype.generateAudioDeviceError=function(error,constraints){if(error.name==="Error"){error.name=error.constructor.name}var errorName,errorMessage;switch(error.name.toLowerCase()){case"notfounderror":errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"notallowederror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ACCESS_DENIED;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"overconstrainederror":if(error.constraint.toLowerCase()==="deviceid"){errorName=OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_NOT_FOUND;errorMessage="Audio input device with deviceId '"+constraints.audio.deviceId.exact+"' not found"}else{errorName=OpenViduError_1.OpenViduErrorName.PUBLISHER_PROPERTIES_ERROR;errorMessage="Audio input device doesn't support the value passed for constraint '"+error.constraint+"'"}return new OpenViduError_1.OpenViduError(errorName,errorMessage);case"notreadableerror":errorName=OpenViduError_1.OpenViduErrorName.DEVICE_ALREADY_IN_USE;errorMessage=error.toString();return new OpenViduError_1.OpenViduError(errorName,errorMessage);default:return new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.INPUT_AUDIO_DEVICE_GENERIC_ERROR,error.toString())}};OpenVidu.prototype.addAlreadyProvidedTracks=function(myConstraints,mediaStream,stream){if(!!myConstraints.videoTrack){mediaStream.addTrack(myConstraints.videoTrack);if(!!stream){if(!!myConstraints.constraints.video){stream.lastVideoTrackConstraints=myConstraints.constraints.video}else{stream.lastVideoTrackConstraints=myConstraints.videoTrack.getConstraints()}}}if(!!myConstraints.audioTrack){mediaStream.addTrack(myConstraints.audioTrack)}return mediaStream};OpenVidu.prototype.configureDeviceIdOrScreensharing=function(myConstraints,publisherProperties,resolve,reject){var _this=this;var audioSource=publisherProperties.audioSource;var videoSource=publisherProperties.videoSource;if(typeof audioSource==="string"){myConstraints.constraints.audio={deviceId:{exact:audioSource}}}if(typeof videoSource==="string"){if(!this.isScreenShare(videoSource)){this.setVideoSource(myConstraints,videoSource)}else{if(!this.checkScreenSharingCapabilities()){var error=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_SHARING_NOT_SUPPORTED,"You can only screen share in desktop Chrome, Firefox, Opera, Safari (>=13.0), Edge (>= 80) or Electron. Detected client: "+platform.getName()+" "+platform.getVersion());logger.error(error);return reject(error)}else{if(platform.isElectron()){var prefix="screen:";var videoSourceString=videoSource;var electronScreenId=videoSourceString.substr(videoSourceString.indexOf(prefix)+prefix.length);myConstraints.constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:electronScreenId}};return resolve(myConstraints)}else{if(!!this.advancedConfiguration.screenShareChromeExtension&&!(platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser())&&!navigator.mediaDevices["getDisplayMedia"]){screenSharing.getScreenConstraints((function(error,screenConstraints){if(!!error||!!screenConstraints.mandatory&&screenConstraints.mandatory.chromeMediaSource==="screen"){if(error==="permission-denied"||error==="PermissionDeniedError"){var error_5=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED,"You must allow access to one window of your desktop");logger.error(error_5);return reject(error_5)}else{var extensionId=_this.advancedConfiguration.screenShareChromeExtension.split("/").pop().trim();screenSharing.getChromeExtensionStatus(extensionId,(function(status){if(status==="installed-disabled"){var error_6=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_DISABLED,"You must enable the screen extension");logger.error(error_6);return reject(error_6)}if(status==="not-installed"){var error_7=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED,_this.advancedConfiguration.screenShareChromeExtension);logger.error(error_7);return reject(error_7)}}));return}}else{myConstraints.constraints.video=screenConstraints;return resolve(myConstraints)}}));return}else{if(navigator.mediaDevices["getDisplayMedia"]){return resolve(myConstraints)}else{var firefoxString=platform.isFirefoxBrowser()||platform.isFirefoxMobileBrowser()?publisherProperties.videoSource:undefined;screenSharingAuto.getScreenId(firefoxString,(function(error,sourceId,screenConstraints){if(!!error){if(error==="not-installed"){var extensionUrl=!!_this.advancedConfiguration.screenShareChromeExtension?_this.advancedConfiguration.screenShareChromeExtension:"https://chrome.google.com/webstore/detail/openvidu-screensharing/lfcgfepafnobdloecchnfaclibenjold";var err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_NOT_INSTALLED,extensionUrl);logger.error(err);return reject(err)}else if(error==="installed-disabled"){var err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_EXTENSION_DISABLED,"You must enable the screen extension");logger.error(err);return reject(err)}else if(error==="permission-denied"){var err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.SCREEN_CAPTURE_DENIED,"You must allow access to one window of your desktop");logger.error(err);return reject(err)}else{var err=new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"Unknown error when accessing screen share");logger.error(err);logger.error(error);return reject(err)}}else{myConstraints.constraints.video=screenConstraints.video;return resolve(myConstraints)}}));return}}}}}}};OpenVidu.prototype.setVideoSource=function(myConstraints,videoSource){if(!myConstraints.constraints.video){myConstraints.constraints.video={}}myConstraints.constraints.video["deviceId"]={exact:videoSource}};OpenVidu.prototype.disconnectCallback=function(){logger.warn("Websocket connection lost");if(this.isRoomAvailable()){this.session.onLostConnection("networkDisconnect")}else{alert("Connection error. Please reload page.")}};OpenVidu.prototype.reconnectingCallback=function(){logger.warn("Websocket connection lost (reconnecting)");if(!this.isRoomAvailable()){alert("Connection error. Please reload page.")}else{this.session.emitEvent("reconnecting",[])}};OpenVidu.prototype.reconnectWebsocketThroughRpcConnectMethod=function(rpcSessionId){var _this=this;this.sendRequest("connect",{sessionId:rpcSessionId,reconnect:true},(function(error,response){if(!!error){if(_this.isMasterNodeCrashed()){logger.warn("Master Node has crashed!")}else{logger.error(error);var notifyLostConnection_1=function(reason,errorMsg){logger.warn(errorMsg);_this.session.onLostConnection(reason);_this.jsonRpcClient.close(4101,"Reconnection fault: "+errorMsg)};var rpcSessionStatus=function(){if(_this.life===-1){notifyLostConnection_1("networkDisconnect","WS successfully reconnected but the user was already evicted due to timeout")}else{_this.sendRequest("sessionStatus",{sessionId:_this.session.sessionId},(function(error,response){if(error!=null){console.error("Error checking session status",error)}else{if(_this.life===response.life){notifyLostConnection_1("networkDisconnect","WS successfully reconnected but the user was already evicted due to timeout")}else{notifyLostConnection_1("nodeCrashed","WS successfully reconnected to OpenVidu Server but your Master Node crashed")}}}))}};if(error.code===40007&&error.message==="reconnection error"){console.error("Invalid RPC sessionId. Client network disconnection or Master Node crash");rpcSessionStatus()}else{rpcSessionStatus()}}}else{_this.jsonRpcClient.resetPing();_this.session.onRecoveredConnection()}}))};OpenVidu.prototype.reconnectedCallback=function(){logger.warn("Websocket reconnected");if(this.isRoomAvailable()){if(!!this.session.connection){this.reconnectWebsocketThroughRpcConnectMethod(this.session.connection.rpcSessionId)}else{logger.warn("There was no previous connection when running reconnection callback");var sessionDisconnectEvent=new SessionDisconnectedEvent_1.SessionDisconnectedEvent(this.session,"networkDisconnect");this.session.ee.emitEvent("sessionDisconnected",[sessionDisconnectEvent]);sessionDisconnectEvent.callDefaultBehavior()}}else{alert("Connection error. Please reload page.")}};OpenVidu.prototype.isMasterNodeCrashed=function(){return this.masterNodeHasCrashed};OpenVidu.prototype.isRoomAvailable=function(){if(this.session!==undefined&&this.session instanceof Session_1.Session){return true}else{logger.warn("Session instance not found");return false}};OpenVidu.prototype.isScreenShare=function(videoSource){return videoSource==="screen"||videoSource==="window"||platform.isElectron()&&videoSource.startsWith("screen:")};return OpenVidu}();exports.OpenVidu=OpenVidu},{"../../package.json":40,"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/SessionDisconnectedEvent":64,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/KurentoUtils/kurento-jsonrpc":76,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Logger/OpenViduLoggerConfiguration":82,"../OpenViduInternal/ScreenSharing/Screen-Capturing":84,"../OpenViduInternal/ScreenSharing/Screen-Capturing-Auto":83,"../OpenViduInternal/Utils/Platform":85,"./LocalRecorder":45,"./Publisher":47,"./Session":48,"wolfy87-eventemitter":39}],47:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]=1){resolveDimensions()}else{loadedmetadataListener=function(){if(!_this.videoReference.videoWidth){var interval_1=setInterval((function(){if(!!_this.videoReference.videoWidth){clearInterval(interval_1);resolveDimensions()}}),40)}else{resolveDimensions()}};_this.videoReference.addEventListener("loadedmetadata",loadedmetadataListener);if(requiresDomInsertion){document.body.appendChild(_this.videoReference)}}}))};Publisher.prototype.reestablishStreamPlayingEvent=function(){if(this.ee.getListeners("streamPlaying").length>0){this.addPlayEventToFirstVideo()}};Publisher.prototype.initializeVideoReference=function(mediaStream){this.videoReference=document.createElement("video");this.videoReference.style.display="none";this.videoReference.muted=true;this.videoReference.autoplay=true;this.videoReference.controls=false;if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){this.videoReference.playsInline=true}this.stream.setMediaStream(mediaStream);if(!!this.firstVideoElement){this.createVideoElement(this.firstVideoElement.targetElement,this.properties.insertMode)}this.videoReference.srcObject=this.stream.getMediaStream()};Publisher.prototype.replaceTrackInMediaStream=function(track,updateLastConstraints){var mediaStream=this.stream.displayMyRemote()?this.stream.localMediaStreamWhenSubscribedToRemote:this.stream.getMediaStream();var removedTrack;if(track.kind==="video"){removedTrack=mediaStream.getVideoTracks()[0];if(updateLastConstraints){this.stream.lastVideoTrackConstraints=track.getConstraints()}}else{removedTrack=mediaStream.getAudioTracks()[0]}removedTrack.enabled=false;removedTrack.stop();mediaStream.removeTrack(removedTrack);mediaStream.addTrack(track);var trackInfo={oldLabel:(removedTrack===null||removedTrack===void 0?void 0:removedTrack.label)||"",newLabel:(track===null||track===void 0?void 0:track.label)||""};if(track.kind==="video"&&updateLastConstraints){this.openvidu.sendNewVideoDimensionsIfRequired(this,"trackReplaced",50,30);this.openvidu.sendTrackChangedEvent(this,trackInfo.oldLabel,trackInfo.newLabel,"videoTrack");if(this.stream.isLocalStreamPublished){this.session.sendVideoData(this.stream.streamManager,5,true,5)}}else if(track.kind==="audio"&&updateLastConstraints){this.openvidu.sendTrackChangedEvent(this,trackInfo.oldLabel,trackInfo.newLabel,"audioTrack")}if(track.kind==="audio"){this.stream.disableHarkSpeakingEvent(false);this.stream.disableHarkStoppedSpeakingEvent(false);this.stream.disableHarkVolumeChangeEvent(false);this.stream.initHarkEvents()}};Publisher.prototype.setPermissionDialogTimer=function(waitTime){var _this=this;this.permissionDialogTimeout=setTimeout((function(){_this.emitEvent("accessDialogOpened",[])}),waitTime)};Publisher.prototype.clearPermissionDialogTimer=function(startTime,waitTime){clearTimeout(this.permissionDialogTimeout);if(Date.now()-startTime>waitTime){this.emitEvent("accessDialogClosed",[])}};Publisher.prototype.replaceTrackInRtcRtpSender=function(track){return __awaiter(this,void 0,void 0,(function(){var senders,sender;return __generator(this,(function(_a){switch(_a.label){case 0:senders=this.stream.getRTCPeerConnection().getSenders();if(track.kind==="video"){sender=senders.find((function(s){return!!s.track&&s.track.kind==="video"}));if(!sender){throw new Error("There's no replaceable track for that kind of MediaStreamTrack in this Publisher object")}}else if(track.kind==="audio"){sender=senders.find((function(s){return!!s.track&&s.track.kind==="audio"}));if(!sender){throw new Error("There's no replaceable track for that kind of MediaStreamTrack in this Publisher object")}}else{throw new Error("Unknown track kind "+track.kind)}return[4,sender.replaceTrack(track)];case 1:_a.sent();return[2]}}))}))};return Publisher}(StreamManager_1.StreamManager);exports.Publisher=Publisher},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/TypeOfVideo":54,"../OpenViduInternal/Events/StreamEvent":67,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./Session":48,"./Stream":49,"./StreamManager":50}],48:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0){var connectionIds_1=[];signal.to.forEach((function(connection){if(!!connection.connectionId){connectionIds_1.push(connection.connectionId)}}));signalMessage["to"]=connectionIds_1}else{signalMessage["to"]=[]}signalMessage["data"]=signal.data?signal.data:"";var typeAux=signal.type?signal.type:"signal";if(!!typeAux){if(typeAux.substring(0,7)!=="signal:"){typeAux="signal:"+typeAux}}signalMessage["type"]=typeAux;_this.openvidu.sendRequest("sendMessage",{message:JSON.stringify(signalMessage)},(function(error,response){if(!!error){return reject(error)}else{return resolve()}}))}))};Session.prototype.subscribeToSpeechToText=function(stream,lang){var _this=this;return new Promise((function(resolve,reject){_this.openvidu.sendRequest("subscribeToSpeechToText",{connectionId:stream.connection.connectionId,lang:lang},(function(error,response){if(!!error){return reject(error)}else{return resolve()}}))}))};Session.prototype.unsubscribeFromSpeechToText=function(stream){var _this=this;return new Promise((function(resolve,reject){_this.openvidu.sendRequest("unsubscribeFromSpeechToText",{connectionId:stream.connection.connectionId},(function(error,response){if(!!error){return reject(error)}else{return resolve()}}))}))};Session.prototype.on=function(type,handler){var _a,_b,_c,_d;_super.prototype.onAux.call(this,type,"Event '"+type+"' triggered by 'Session'",handler);if(type==="publisherStartSpeaking"){this.remoteConnections.forEach((function(remoteConnection){var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableHarkSpeakingEvent()}}));if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.hasAudio)){this.connection.stream.enableHarkSpeakingEvent()}}if(type==="publisherStopSpeaking"){this.remoteConnections.forEach((function(remoteConnection){var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableHarkStoppedSpeakingEvent()}}));if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.hasAudio)){this.connection.stream.enableHarkStoppedSpeakingEvent()}}return this};Session.prototype.once=function(type,handler){var _a,_b,_c,_d;_super.prototype.onceAux.call(this,type,"Event '"+type+"' triggered once by 'Session'",handler);if(type==="publisherStartSpeaking"){this.remoteConnections.forEach((function(remoteConnection){var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableOnceHarkSpeakingEvent()}}));if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.hasAudio)){this.connection.stream.enableOnceHarkSpeakingEvent()}}if(type==="publisherStopSpeaking"){this.remoteConnections.forEach((function(remoteConnection){var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.hasAudio)){remoteConnection.stream.enableOnceHarkStoppedSpeakingEvent()}}));if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.hasAudio)){this.connection.stream.enableOnceHarkStoppedSpeakingEvent()}}return this};Session.prototype.off=function(type,handler){var _this=this;var _a,_b,_c,_d;_super.prototype.offAux.call(this,type,handler);if(type==="publisherStartSpeaking"){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false)){this.remoteConnections.forEach((function(remoteConnection){var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.streamManager)){if(!_this.anySpeechEventListenerEnabled("publisherStartSpeaking",false,remoteConnection.stream.streamManager)){remoteConnection.stream.disableHarkSpeakingEvent(false)}}}));if(!!((_b=(_a=this.connection)===null||_a===void 0?void 0:_a.stream)===null||_b===void 0?void 0:_b.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStartSpeaking",false,this.connection.stream.streamManager)){this.connection.stream.disableHarkSpeakingEvent(false)}}}}if(type==="publisherStopSpeaking"){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false)){this.remoteConnections.forEach((function(remoteConnection){var _a;if(!!((_a=remoteConnection.stream)===null||_a===void 0?void 0:_a.streamManager)){if(!_this.anySpeechEventListenerEnabled("publisherStopSpeaking",false,remoteConnection.stream.streamManager)){remoteConnection.stream.disableHarkStoppedSpeakingEvent(false)}}}));if(!!((_d=(_c=this.connection)===null||_c===void 0?void 0:_c.stream)===null||_d===void 0?void 0:_d.streamManager)){if(!this.anySpeechEventListenerEnabled("publisherStopSpeaking",false,this.connection.stream.streamManager)){this.connection.stream.disableHarkStoppedSpeakingEvent(false)}}}}return this};Session.prototype.onParticipantJoined=function(event){var _this=this;this.getConnection(event.id,"").then((function(connection){logger.warn("Connection "+connection.connectionId+" already exists in connections list")})).catch((function(openViduError){var connection=new Connection_1.Connection(_this,event);_this.remoteConnections.set(event.id,connection);_this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,_this,"connectionCreated",connection,"")])}))};Session.prototype.onParticipantLeft=function(event){var _this=this;this.getRemoteConnection(event.connectionId,"onParticipantLeft").then((function(connection){if(!!connection.stream){var stream=connection.stream;var streamEvent=new StreamEvent_1.StreamEvent(true,_this,"streamDestroyed",stream,event.reason);_this.ee.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();_this.remoteStreamsCreated.delete(stream.streamId)}connection.dispose();_this.remoteConnections.delete(connection.connectionId);_this.ee.emitEvent("connectionDestroyed",[new ConnectionEvent_1.ConnectionEvent(false,_this,"connectionDestroyed",connection,event.reason)])})).catch((function(openViduError){logger.error(openViduError)}))};Session.prototype.onParticipantPublished=function(event){var _this=this;var afterConnectionFound=function(connection){_this.remoteConnections.set(connection.connectionId,connection);if(!_this.remoteStreamsCreated.get(connection.stream.streamId)){_this.ee.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,_this,"streamCreated",connection.stream,"")])}_this.remoteStreamsCreated.set(connection.stream.streamId,true)};var connection;this.getRemoteConnection(event.id,"onParticipantPublished").then((function(con){connection=con;event.metadata=con.data;connection.remoteOptions=event;connection.initRemoteStreams(event.streams);afterConnectionFound(connection)})).catch((function(openViduError){connection=new Connection_1.Connection(_this,event);afterConnectionFound(connection)}))};Session.prototype.onParticipantUnpublished=function(event){var _this=this;if(event.connectionId===this.connection.connectionId){this.stopPublisherStream(event.reason)}else{this.getRemoteConnection(event.connectionId,"onParticipantUnpublished").then((function(connection){var streamEvent=new StreamEvent_1.StreamEvent(true,_this,"streamDestroyed",connection.stream,event.reason);_this.ee.emitEvent("streamDestroyed",[streamEvent]);streamEvent.callDefaultBehavior();if(connection.stream!=null){var streamId=connection.stream.streamId;_this.remoteStreamsCreated.delete(streamId);connection.removeStream()}})).catch((function(openViduError){logger.error(openViduError)}))}};Session.prototype.onParticipantEvicted=function(event){if(event.connectionId===this.connection.connectionId){if(!!this.sessionId&&!this.connection.disposed){this.leave(true,event.reason)}}};Session.prototype.onNewMessage=function(event){var _this=this;logger.info("New signal: "+JSON.stringify(event));var strippedType=!!event.type?event.type.replace(/^(signal:)/,""):undefined;if(!!event.from){this.getConnection(event.from,"Connection '"+event.from+"' unknown when 'onNewMessage'. Existing remote connections: "+JSON.stringify(this.remoteConnections.keys())+". Existing local connection: "+this.connection.connectionId).then((function(connection){_this.ee.emitEvent("signal",[new SignalEvent_1.SignalEvent(_this,strippedType,event.data,connection)]);if(!!event.type&&event.type!=="signal"){_this.ee.emitEvent(event.type,[new SignalEvent_1.SignalEvent(_this,strippedType,event.data,connection)])}})).catch((function(openViduError){logger.error(openViduError)}))}else{this.ee.emitEvent("signal",[new SignalEvent_1.SignalEvent(this,strippedType,event.data,undefined)]);if(!!event.type&&event.type!=="signal"){this.ee.emitEvent(event.type,[new SignalEvent_1.SignalEvent(this,strippedType,event.data,undefined)])}}};Session.prototype.onStreamPropertyChanged=function(event){var _this=this;var callback=function(connection){if(!!connection.stream&&connection.stream.streamId===event.streamId){var stream=connection.stream;var oldValue=void 0;switch(event.property){case"audioActive":oldValue=stream.audioActive;event.newValue=event.newValue==="true";stream.audioActive=event.newValue;break;case"videoActive":oldValue=stream.videoActive;event.newValue=event.newValue==="true";stream.videoActive=event.newValue;break;case"videoTrack":event.newValue=JSON.parse(event.newValue);break;case"audioTrack":event.newValue=JSON.parse(event.newValue);break;case"videoDimensions":oldValue=stream.videoDimensions;event.newValue=JSON.parse(JSON.parse(event.newValue));stream.videoDimensions=event.newValue;break;case"filter":oldValue=stream.filter;event.newValue=Object.keys(event.newValue).length>0?event.newValue:undefined;if(event.newValue!==undefined){stream.filter=new Filter_1.Filter(event.newValue.type,event.newValue.options);stream.filter.stream=stream;if(event.newValue.lastExecMethod){stream.filter.lastExecMethod=event.newValue.lastExecMethod}}else{delete stream.filter}event.newValue=stream.filter;break}_this.ee.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(_this,stream,event.property,event.newValue,oldValue,event.reason)]);if(!!stream.streamManager){stream.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(stream.streamManager,stream,event.property,event.newValue,oldValue,event.reason)])}}else{logger.error("No stream with streamId '"+event.streamId+"' found for connection '"+event.connectionId+"' on 'streamPropertyChanged' event")}};if(event.connectionId===this.connection.connectionId){callback(this.connection)}else{this.getRemoteConnection(event.connectionId,"onStreamPropertyChanged").then((function(connection){callback(connection)})).catch((function(openViduError){logger.error(openViduError)}))}};Session.prototype.onConnectionPropertyChanged=function(event){var oldValue;switch(event.property){case"role":oldValue=this.connection.role.slice();this.connection.role=event.newValue;this.connection.localOptions.role=event.newValue;break;case"record":oldValue=this.connection.record;event.newValue=event.newValue==="true";this.connection.record=event.newValue;this.connection.localOptions.record=event.newValue;break}this.ee.emitEvent("connectionPropertyChanged",[new ConnectionPropertyChangedEvent_1.ConnectionPropertyChangedEvent(this,this.connection,event.property,event.newValue,oldValue)])};Session.prototype.onNetworkQualityLevelChangedChanged=function(event){var _this=this;if(event.connectionId===this.connection.connectionId){this.ee.emitEvent("networkQualityLevelChanged",[new NetworkQualityLevelChangedEvent_1.NetworkQualityLevelChangedEvent(this,event.newValue,event.oldValue,this.connection)])}else{this.getConnection(event.connectionId,"Connection not found for connectionId "+event.connectionId).then((function(connection){_this.ee.emitEvent("networkQualityLevelChanged",[new NetworkQualityLevelChangedEvent_1.NetworkQualityLevelChangedEvent(_this,event.newValue,event.oldValue,connection)])})).catch((function(openViduError){logger.error(openViduError)}))}};Session.prototype.recvIceCandidate=function(event){var candidateInit={candidate:event.candidate,sdpMLineIndex:event.sdpMLineIndex,sdpMid:event.sdpMid};var iceCandidate=new RTCIceCandidate(candidateInit);this.getConnection(event.senderConnectionId,"Connection not found for connectionId "+event.senderConnectionId+" owning endpoint "+event.endpointName+". Ice candidate will be ignored: "+iceCandidate).then((function(connection){var stream=connection.stream;stream.getWebRtcPeer().addIceCandidate(iceCandidate).catch((function(error){logger.error("Error adding candidate for "+stream.streamId+" stream of endpoint "+event.endpointName+": "+error)}))})).catch((function(openViduError){logger.error(openViduError)}))};Session.prototype.onSessionClosed=function(msg){logger.info("Session closed: "+JSON.stringify(msg));var s=msg.sessionId;if(s!==undefined){this.ee.emitEvent("session-closed",[{session:s}])}else{logger.warn("Session undefined on session closed",msg)}};Session.prototype.onLostConnection=function(reason){logger.warn("Lost connection in Session "+this.sessionId);if(!!this.sessionId&&!!this.connection&&!this.connection.disposed){this.leave(true,reason)}};Session.prototype.onRecoveredConnection=function(){logger.info("Recovered connection in Session "+this.sessionId);this.reconnectBrokenStreams();this.ee.emitEvent("reconnected",[])};Session.prototype.onMediaError=function(event){logger.error("Media error: "+JSON.stringify(event));var err=event.error;if(err){this.ee.emitEvent("error-media",[{error:err}])}else{logger.warn("Received undefined media error:",event)}};Session.prototype.onRecordingStarted=function(event){this.ee.emitEvent("recordingStarted",[new RecordingEvent_1.RecordingEvent(this,"recordingStarted",event.id,event.name)])};Session.prototype.onRecordingStopped=function(event){this.ee.emitEvent("recordingStopped",[new RecordingEvent_1.RecordingEvent(this,"recordingStopped",event.id,event.name,event.reason)])};Session.prototype.onBroadcastStarted=function(){this.ee.emitEvent("broadcastStarted",[])};Session.prototype.onBroadcastStopped=function(){this.ee.emitEvent("broadcastStopped",[])};Session.prototype.onFilterEventDispatched=function(event){var _this=this;var connectionId=event.connectionId;this.getConnection(connectionId,"No connection found for connectionId "+connectionId).then((function(connection){logger.info('Filter event of type "'.concat(event.eventType,'" dispatched'));var stream=connection.stream;if(!stream||!stream.filter){return logger.error('Filter event of type "'.concat(event.eventType,'" dispatched for stream ').concat(stream.streamId," but there is no ").concat(!stream?"stream":"filter"," defined"))}var eventHandler=stream.filter.handlers.get(event.eventType);if(!eventHandler||typeof eventHandler!=="function"){var actualHandlers=Array.from(stream.filter.handlers.keys());return logger.error('Filter event of type "'.concat(event.eventType,'" not handled or not a function! Active filter events: ').concat(actualHandlers.join(",")))}else{eventHandler.call(_this,new FilterEvent_1.FilterEvent(stream.filter,event.eventType,event.data))}}))};Session.prototype.onForciblyReconnectSubscriber=function(event){var _this=this;return new Promise((function(resolve,reject){_this.getRemoteConnection(event.connectionId,"onForciblyReconnectSubscriber").then((function(connection){if(!!connection.stream&&connection.stream.streamId===event.streamId){var stream_1=connection.stream;if(stream_1.setupReconnectionEventEmitter(resolve,reject)){if(stream_1.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]!=null){stream_1.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]=event;return reject("Ongoing forced subscriber reconnection")}else{stream_1.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"]=event;var callback_1=function(){var eventAux=stream_1.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"];delete stream_1.reconnectionEventEmitter["onForciblyReconnectSubscriberLastEvent"];_this.onForciblyReconnectSubscriber(eventAux)};stream_1.reconnectionEventEmitter.once("success",(function(){callback_1()}));stream_1.reconnectionEventEmitter.once("error",(function(){callback_1()}))}return}stream_1.completeWebRtcPeerReceive(true,true,event.sdpOffer).then((function(){return stream_1.finalResolveForSubscription(true,resolve)})).catch((function(error){return stream_1.finalRejectForSubscription(true,"Error while forcibly reconnecting remote stream ".concat(event.streamId,": ").concat(error.toString()),reject)}))}else{var errMsg="No stream with streamId '"+event.streamId+"' found for connection '"+event.connectionId+"' on 'streamPropertyChanged' event";logger.error(errMsg);return reject(errMsg)}})).catch((function(openViduError){logger.error(openViduError);return reject(openViduError)}))}))};Session.prototype.reconnectBrokenStreams=function(){logger.info("Re-establishing media connections...");var someReconnection=false;if(!!this.connection.stream&&this.connection.stream.streamIceConnectionStateBroken()){logger.warn("Re-establishing Publisher "+this.connection.stream.streamId);this.connection.stream.initWebRtcPeerSend(true);someReconnection=true}this.remoteConnections.forEach((function(remoteConnection){if(!!remoteConnection.stream&&remoteConnection.stream.streamIceConnectionStateBroken()){logger.warn("Re-establishing Subscriber "+remoteConnection.stream.streamId);remoteConnection.stream.initWebRtcPeerReceive(true);someReconnection=true}}));if(!someReconnection){logger.info("There were no media streams in need of a reconnection")}};Session.prototype.onSpeechToTextMessage=function(event){return __awaiter(this,void 0,void 0,(function(){var connection,ev;return __generator(this,(function(_a){switch(_a.label){case 0:return[4,this.getConnection(event.connectionId,"No connection found for connectionId "+event.connectionId)];case 1:connection=_a.sent();ev=new SpeechToTextEvent_1.SpeechToTextEvent(this,connection,event.text,event.reason.toLowerCase(),event.raw,event.lang);this.ee.emitEvent("speechToTextMessage",[ev]);return[2]}}))}))};Session.prototype.onSpeechToTextDisconnected=function(event){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a){this.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this,ExceptionEvent_1.ExceptionEventName.SPEECH_TO_TEXT_DISCONNECTED,this,event.message)]);return[2]}))}))};Session.prototype.emitEvent=function(type,eventArray){this.ee.emitEvent(type,eventArray)};Session.prototype.leave=function(forced,reason){var _this=this;forced=!!forced;logger.info("Leaving Session (forced="+forced+")");this.stopVideoDataIntervals();if(!!this.connection){if(!this.connection.disposed&&!forced){this.openvidu.sendRequest("leaveRoom",(function(error,response){if(error){logger.error("leaveRoom error: ".concat(JSON.stringify(error)))}_this.openvidu.closeWs()}))}else{this.openvidu.closeWs()}this.stopPublisherStream(reason);if(!this.connection.disposed){var sessionDisconnectEvent=new SessionDisconnectedEvent_1.SessionDisconnectedEvent(this,reason);this.ee.emitEvent("sessionDisconnected",[sessionDisconnectEvent]);sessionDisconnectEvent.callDefaultBehavior()}}else{logger.warn("You were not connected to the session "+this.sessionId)}logger.flush()};Session.prototype.initializeParams=function(token){var joinParams={token:!!token?token:"",session:this.sessionId,platform:!!platform.getDescription()?platform.getDescription():"unknown",sdkVersion:this.openvidu.libraryVersion,metadata:!!this.options.metadata?this.options.metadata:"",secret:this.openvidu.getSecret(),recorder:this.openvidu.getRecorder(),stt:this.openvidu.getStt()};return joinParams};Session.prototype.sendVideoData=function(streamManager,intervalSeconds,doInterval,maxLoops){var _this=this;var _a,_b;if(intervalSeconds===void 0){intervalSeconds=1}if(doInterval===void 0){doInterval=false}if(maxLoops===void 0){maxLoops=1}if(platform.isChromeBrowser()||platform.isChromeMobileBrowser()||platform.isOperaBrowser()||platform.isOperaMobileBrowser()||platform.isEdgeBrowser()||platform.isEdgeMobileBrowser()||platform.isElectron()||platform.isSafariBrowser()&&!platform.isIonicIos()||platform.isAndroidBrowser()||platform.isSamsungBrowser()||platform.isIonicAndroid()||platform.isIOSWithSafari()){var obtainAndSendVideo_1=function(){return __awaiter(_this,void 0,void 0,(function(){var pc,statsMap,arr_1;return __generator(this,(function(_a){switch(_a.label){case 0:pc=streamManager.stream.getRTCPeerConnection();if(!(pc.connectionState==="connected"))return[3,2];return[4,pc.getStats()];case 1:statsMap=_a.sent();arr_1=[];statsMap.forEach((function(stats){if("frameWidth"in stats&&"frameHeight"in stats&&arr_1.length===0){arr_1.push(stats)}}));if(arr_1.length>0){this.openvidu.sendRequest("videoData",{height:arr_1[0].frameHeight,width:arr_1[0].frameWidth,videoActive:streamManager.stream.videoActive!=null?streamManager.stream.videoActive:false,audioActive:streamManager.stream.audioActive!=null?streamManager.stream.audioActive:false},(function(error,response){if(error){logger.error("Error sending 'videoData' event",error)}}))}_a.label=2;case 2:return[2]}}))}))};if(doInterval){var loops_1=1;this.videoDataInterval=setInterval((function(){if(loops_10)return true;var listenersInStreamManager=0;if(!!streamManager){var handlersInStreamManager=streamManager.ee.getListeners(event);if(onlyOnce){handlersInStreamManager=handlersInStreamManager.filter((function(h){return h.once}))}listenersInStreamManager=handlersInStreamManager.length}return listenersInStreamManager>0};Session.prototype.getTokenParams=function(token){var match=token.match(/^(wss?)\:\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);if(!!match){var url={protocol:match[1],host:match[2],hostname:match[3],port:match[4],pathname:match[5],search:match[6],hash:match[7]};var params=token.split("?");var queryParams=decodeURI(params[1]).split("&").map((function(param){return param.split("=")})).reduce((function(values,_a){var key=_a[0],value=_a[1];values[key]=value;return values}),{});return{sessionId:queryParams["sessionId"],secret:queryParams["secret"],recorder:queryParams["recorder"],stt:queryParams["stt"],webrtcStatsInterval:queryParams["webrtcStatsInterval"],sendBrowserLogs:queryParams["sendBrowserLogs"],edition:queryParams["edition"],wsUri:url.protocol+"://"+url.host+"/openvidu",httpUri:"https://"+url.host}}else{throw new Error('Token not valid: "'.concat(token,'"'))}};Session.prototype.connectAux=function(token){var _this=this;return new Promise((function(resolve,reject){_this.openvidu.startWs((function(error){if(!!error){return reject(error)}else{var joinParams=_this.initializeParams(token);_this.openvidu.sendRequest("joinRoom",joinParams,(function(error,response){if(!!error){return reject(error)}else{_this.processJoinRoomResponse(response,token);_this.connection=new Connection_1.Connection(_this,response);var events_1={connections:new Array,streams:new Array};var existingParticipants=response.value;existingParticipants.forEach((function(remoteConnectionOptions){var connection=new Connection_1.Connection(_this,remoteConnectionOptions);_this.remoteConnections.set(connection.connectionId,connection);events_1.connections.push(connection);if(!!connection.stream){_this.remoteStreamsCreated.set(connection.stream.streamId,true);events_1.streams.push(connection.stream)}}));_this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,_this,"connectionCreated",_this.connection,"")]);events_1.connections.forEach((function(connection){_this.ee.emitEvent("connectionCreated",[new ConnectionEvent_1.ConnectionEvent(false,_this,"connectionCreated",connection,"")])}));events_1.streams.forEach((function(stream){_this.ee.emitEvent("streamCreated",[new StreamEvent_1.StreamEvent(false,_this,"streamCreated",stream,"")])}));if(!!response.recordingId&&!!response.recordingName){_this.ee.emitEvent("recordingStarted",[new RecordingEvent_1.RecordingEvent(_this,"recordingStarted",response.recordingId,response.recordingName)])}return resolve()}}))}}))}))};Session.prototype.stopPublisherStream=function(reason){if(!!this.connection.stream){this.connection.stream.disposeWebRtcPeer();if(this.connection.stream.isLocalStreamPublished){this.connection.stream.ee.emitEvent("local-stream-destroyed",[reason])}}};Session.prototype.stopVideoDataIntervals=function(){clearInterval(this.videoDataInterval);clearTimeout(this.videoDataTimeout)};Session.prototype.stringClientMetadata=function(metadata){if(typeof metadata!=="string"){return JSON.stringify(metadata)}else{return metadata}};Session.prototype.getConnection=function(connectionId,errorMessage){var _this=this;return new Promise((function(resolve,reject){var connection=_this.remoteConnections.get(connectionId);if(!!connection){return resolve(connection)}else{if(_this.connection.connectionId===connectionId){return resolve(_this.connection)}else{return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,errorMessage))}}}))};Session.prototype.getRemoteConnection=function(connectionId,operation){var _this=this;return new Promise((function(resolve,reject){var connection=_this.remoteConnections.get(connectionId);if(!!connection){return resolve(connection)}else{var errorMessage="Remote connection "+connectionId+" unknown when '"+operation+"'. "+"Existing remote connections: "+JSON.stringify(_this.remoteConnections.keys());return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,errorMessage))}}))};Session.prototype.processToken=function(token){var tokenParams=this.getTokenParams(token);this.sessionId=tokenParams.sessionId;if(!!tokenParams.secret){this.openvidu.secret=tokenParams.secret}if(!!tokenParams.recorder){this.openvidu.recorder=true}if(!!tokenParams.stt){this.openvidu.stt=true}if(!!tokenParams.webrtcStatsInterval){this.openvidu.webrtcStatsInterval=tokenParams.webrtcStatsInterval}if(!!tokenParams.sendBrowserLogs){this.openvidu.sendBrowserLogs=tokenParams.sendBrowserLogs}this.openvidu.isAtLeastPro=tokenParams.edition==="pro"||tokenParams.edition==="enterprise";this.openvidu.isEnterprise=tokenParams.edition==="enterprise";this.openvidu.wsUri=tokenParams.wsUri;this.openvidu.httpUri=tokenParams.httpUri};Session.prototype.processJoinRoomResponse=function(opts,token){this.sessionId=opts.session;if(opts.customIceServers!=null&&opts.customIceServers.length>0){this.openvidu.iceServers=[];for(var _i=0,_a=opts.customIceServers;_i<_a.length;_i++){var iceServer=_a[_i];var rtcIceServer={urls:[iceServer.url]};logger.log("STUN/TURN server IP: "+iceServer.url);if(iceServer.username!=null&&iceServer.credential!=null){rtcIceServer.username=iceServer.username;rtcIceServer.credential=iceServer.credential;logger.log("TURN credentials ["+iceServer.username+":"+iceServer.credential+"]")}this.openvidu.iceServers.push(rtcIceServer)}}this.openvidu.role=opts.role;this.openvidu.finalUserId=opts.finalUserId;this.openvidu.mediaServer=opts.mediaServer;this.openvidu.videoSimulcast=opts.videoSimulcast;this.capabilities={subscribe:true,publish:this.openvidu.role!=="SUBSCRIBER",forceUnpublish:this.openvidu.role==="MODERATOR",forceDisconnect:this.openvidu.role==="MODERATOR"};logger.info("openvidu-server version: "+opts.version);if(opts.life!=null){this.openvidu.life=opts.life}var minorDifference=semverMinor(opts.version)-semverMinor(this.openvidu.libraryVersion);if(semverMajor(opts.version)!==semverMajor(this.openvidu.libraryVersion)||!(minorDifference==0||minorDifference==1)){logger.error("openvidu-browser (".concat(this.openvidu.libraryVersion,") and openvidu-server (").concat(opts.version,") versions are incompatible. ")+"Errors are likely to occur. openvidu-browser SDK is only compatible with the same version or the immediately following minor version of an OpenVidu deployment")}else if(minorDifference==1){logger.warn("openvidu-browser version ".concat(this.openvidu.libraryVersion," does not match openvidu-server version ").concat(opts.version,". ")+"These versions are still compatible with each other, but openvidu-browser version must be updated as soon as possible to ".concat(semverMajor(opts.version),".").concat(semverMinor(opts.version),".x. ")+"This client using openvidu-browser ".concat(this.openvidu.libraryVersion," will become incompatible with the next release of openvidu-server"))}OpenViduLogger_1.OpenViduLogger.configureJSNLog(this.openvidu,token);this.token=token};return Session}(EventDispatcher_1.EventDispatcher);exports.Session=Session},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/VideoInsertMode":55,"../OpenViduInternal/Events/ConnectionEvent":56,"../OpenViduInternal/Events/ConnectionPropertyChangedEvent":57,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/FilterEvent":60,"../OpenViduInternal/Events/NetworkQualityLevelChangedEvent":61,"../OpenViduInternal/Events/RecordingEvent":63,"../OpenViduInternal/Events/SessionDisconnectedEvent":64,"../OpenViduInternal/Events/SignalEvent":65,"../OpenViduInternal/Events/SpeechToTextEvent":66,"../OpenViduInternal/Events/StreamEvent":67,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"./Connection":42,"./EventDispatcher":43,"./Filter":44,"./Subscriber":51,"semver/functions/major":15,"semver/functions/minor":16}],49:[function(require,module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0){if(!!this.inboundStreamOpts.filter.lastExecMethod&&Object.keys(this.inboundStreamOpts.filter.lastExecMethod).length===0){delete this.inboundStreamOpts.filter.lastExecMethod}this.filter=this.inboundStreamOpts.filter}}else{this.outboundStreamOpts=options;this.hasAudio=this.isSendAudio();this.hasVideo=this.isSendVideo();if(this.hasAudio){this.audioActive=!!this.outboundStreamOpts.publisherProperties.publishAudio}if(this.hasVideo){this.videoActive=!!this.outboundStreamOpts.publisherProperties.publishVideo;this.frameRate=this.outboundStreamOpts.publisherProperties.frameRate;if(typeof MediaStreamTrack!=="undefined"&&this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack){this.typeOfVideo=TypeOfVideo_1.TypeOfVideo.CUSTOM}else{this.typeOfVideo=this.isSendScreen()?TypeOfVideo_1.TypeOfVideo.SCREEN:TypeOfVideo_1.TypeOfVideo.CAMERA}}if(!!this.outboundStreamOpts.publisherProperties.filter){this.filter=this.outboundStreamOpts.publisherProperties.filter}}this.ee.on("mediastream-updated",(function(){var _a;_this.streamManager.updateMediaStream(_this.mediaStream);logger.debug("Video srcObject ["+((_a=_this.mediaStream)===null||_a===void 0?void 0:_a.id)+"] updated in stream ["+_this.streamId+"]")}))}Stream.prototype.reconnect=function(){return this.reconnectStream("API")};Stream.prototype.applyFilter=function(type,options){var _this=this;return new Promise((function(resolve,reject){return __awaiter(_this,void 0,void 0,(function(){var resolveApplyFilter,openviduToken_1,tokenParams_1,afterScriptLoaded_1,script,optionsString;var _this=this;return __generator(this,(function(_a){if(!!this.filter){return[2,reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"There is already a filter applied to Stream "+this.streamId))]}resolveApplyFilter=function(error,triggerEvent){if(error){logger.error("Error applying filter for Stream "+_this.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to apply a filter"))}else{return reject(error)}}else{logger.info("Filter successfully applied on Stream "+_this.streamId);var oldValue=_this.filter;_this.filter=new Filter_1.Filter(type,options);_this.filter.stream=_this;if(triggerEvent){_this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(_this.session,_this,"filter",_this.filter,oldValue,"applyFilter")]);_this.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(_this.streamManager,_this,"filter",_this.filter,oldValue,"applyFilter")])}return resolve(_this.filter)}};if(type.startsWith("VB:")){if(!this.hasVideo){return[2,reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"The Virtual Background filter requires a video track to be applied"))]}if(!this.mediaStream||this.streamManager.videos.length===0){return[2,reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"The StreamManager requires some video element to be attached to it in order to apply a Virtual Background filter"))]}if(!!this.session.token){openviduToken_1=this.session.token}else{openviduToken_1=options["token"]}if(!openviduToken_1){return[2,reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,'Virtual Background requires the client to be connected to a Session or to have a "token" property available in "options" parameter with a valid OpenVidu token'))]}tokenParams_1=this.session.getTokenParams(openviduToken_1);if(tokenParams_1.edition!=="pro"&&tokenParams_1.edition!=="enterprise"){return[2,reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,"OpenVidu Virtual Background API is available from OpenVidu Pro edition onwards"))]}openviduToken_1=encodeURIComponent(btoa(openviduToken_1));logger.info("Applying Virtual Background to stream "+this.streamId);afterScriptLoaded_1=function(){return __awaiter(_this,void 0,void 0,(function(){var id,mediaStreamClone,videoClone,VB,filteredVideo,_a,error_1;return __generator(this,(function(_b){switch(_b.label){case 0:_b.trys.push([0,8,,9]);id=this.streamId+"_"+(0,uuid_1.v4)();mediaStreamClone=this.mediaStream.clone();videoClone=this.streamManager.videos[0].video.cloneNode(false);videoClone.id=VirtualBackground.VirtualBackground.SOURCE_VIDEO_PREFIX+id;videoClone.srcObject=mediaStreamClone;videoClone.muted=true;this.virtualBackgroundSourceElements={videoClone:videoClone,mediaStreamClone:mediaStreamClone};VirtualBackground.VirtualBackground.hideHtmlElement(videoClone,false);VirtualBackground.VirtualBackground.appendHtmlElementToHiddenContainer(videoClone,id);return[4,videoClone.play()];case 1:_b.sent();VB=new VirtualBackground.VirtualBackground({id:id,openviduServerUrl:new URL(tokenParams_1.httpUri),openviduToken:openviduToken_1,inputVideo:videoClone,inputResolution:"160x96",outputFramerate:24});filteredVideo=void 0;_a=type;switch(_a){case"VB:blur":return[3,2];case"VB:image":return[3,4]}return[3,6];case 2:return[4,VB.backgroundBlur(options)];case 3:filteredVideo=_b.sent();return[3,7];case 4:return[4,VB.backgroundImage(options)];case 5:filteredVideo=_b.sent();return[3,7];case 6:throw new Error("Unknown Virtual Background filter: "+type);case 7:this.virtualBackgroundSinkElements={VB:VB,video:filteredVideo};videoClone.style.display="none";if(this.streamManager.remote){this.streamManager.replaceTrackInMediaStream(this.virtualBackgroundSinkElements.video.srcObject.getVideoTracks()[0],false)}else{this.streamManager.replaceTrackAux(this.virtualBackgroundSinkElements.video.srcObject.getVideoTracks()[0],false)}resolveApplyFilter(undefined,false);return[3,9];case 8:error_1=_b.sent();if(error_1.name===OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR){resolveApplyFilter(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.VIRTUAL_BACKGROUND_ERROR,error_1.message),false)}else{resolveApplyFilter(error_1,false)}return[3,9];case 9:return[2]}}))}))};if(typeof VirtualBackground==="undefined"){script=document.createElement("script");script.type="text/javascript";script.src=tokenParams_1.httpUri+"/openvidu/virtual-background/openvidu-virtual-background.js?token="+openviduToken_1;script.onload=function(){return __awaiter(_this,void 0,void 0,(function(){var error_2;return __generator(this,(function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);return[4,afterScriptLoaded_1()];case 1:_a.sent();resolve(new Filter_1.Filter(type,options));return[3,3];case 2:error_2=_a.sent();reject(error_2);return[3,3];case 3:return[2]}}))}))};document.body.appendChild(script)}else{afterScriptLoaded_1().then((function(){return resolve(new Filter_1.Filter(type,options))})).catch((function(error){return reject(error)}))}}else{if(!this.session.sessionConnected()){return[2,reject(this.session.notConnectedError())]}logger.info("Applying server filter to stream "+this.streamId);options=options!=null?options:{};optionsString=options;if(typeof optionsString!=="string"){optionsString=JSON.stringify(optionsString)}this.session.openvidu.sendRequest("applyFilter",{streamId:this.streamId,type:type,options:optionsString},(function(error,response){resolveApplyFilter(error,true)}))}return[2]}))}))}))};Stream.prototype.removeFilter=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a){switch(_a.label){case 0:return[4,this.removeFilterAux(false)];case 1:return[2,_a.sent()]}}))}))};Stream.prototype.getRTCPeerConnection=function(){return this.webRtcPeer.pc};Stream.prototype.getMediaStream=function(){return this.mediaStream};Stream.prototype.removeFilterAux=function(isDisposing){var _this=this;return new Promise((function(resolve,reject){return __awaiter(_this,void 0,void 0,(function(){var resolveRemoveFilter,mediaStreamClone,error_3;var _this=this;var _a;return __generator(this,(function(_b){switch(_b.label){case 0:resolveRemoveFilter=function(error,triggerEvent){if(error){delete _this.filter;logger.error("Error removing filter for Stream "+_this.streamId,error);if(error.code===401){return reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to remove a filter"))}else{return reject(error)}}else{logger.info("Filter successfully removed from Stream "+_this.streamId);var oldValue=_this.filter;delete _this.filter;if(triggerEvent){_this.session.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(_this.session,_this,"filter",_this.filter,oldValue,"applyFilter")]);_this.streamManager.emitEvent("streamPropertyChanged",[new StreamPropertyChangedEvent_1.StreamPropertyChangedEvent(_this.streamManager,_this,"filter",_this.filter,oldValue,"applyFilter")])}return resolve()}};if(!!!this.filter)return[3,11];if(!((_a=this.filter)===null||_a===void 0?void 0:_a.type.startsWith("VB:")))return[3,9];_b.label=1;case 1:_b.trys.push([1,7,,8]);mediaStreamClone=this.virtualBackgroundSourceElements.mediaStreamClone;if(!!isDisposing)return[3,5];if(!this.streamManager.remote)return[3,2];this.streamManager.replaceTrackInMediaStream(mediaStreamClone.getVideoTracks()[0],false);return[3,4];case 2:return[4,this.streamManager.replaceTrackAux(mediaStreamClone.getVideoTracks()[0],false)];case 3:_b.sent();_b.label=4;case 4:return[3,6];case 5:mediaStreamClone.getTracks().forEach((function(track){return track.stop()}));_b.label=6;case 6:this.virtualBackgroundSinkElements.VB.cleanUp();delete this.virtualBackgroundSinkElements;delete this.virtualBackgroundSourceElements;return[2,resolveRemoveFilter(undefined,false)];case 7:error_3=_b.sent();return[2,resolveRemoveFilter(error_3,false)];case 8:return[3,10];case 9:if(!this.session.sessionConnected()){return[2,reject(this.session.notConnectedError())]}logger.info("Removing filter of stream "+this.streamId);this.session.openvidu.sendRequest("removeFilter",{streamId:this.streamId},(function(error,response){return resolveRemoveFilter(error,true)}));_b.label=10;case 10:return[3,12];case 11:return[2,reject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.GENERIC_ERROR,"Stream "+this.streamId+" has no filter applied"))];case 12:return[2]}}))}))}))};Stream.prototype.setMediaStream=function(mediaStream){this.mediaStream=mediaStream};Stream.prototype.updateMediaStreamInVideos=function(){this.ee.emitEvent("mediastream-updated",[])};Stream.prototype.getWebRtcPeer=function(){return this.webRtcPeer};Stream.prototype.subscribeToMyRemote=function(value){this.isSubscribeToRemote=value};Stream.prototype.setOutboundStreamOptions=function(outboundStreamOpts){this.outboundStreamOpts=outboundStreamOpts};Stream.prototype.subscribe=function(){var _this=this;return new Promise((function(resolve,reject){_this.initWebRtcPeerReceive(false).then((function(){return resolve()})).catch((function(error){return reject(error)}))}))};Stream.prototype.publish=function(){var _this=this;return new Promise((function(resolve,reject){if(_this.isLocalStreamReadyToPublish){_this.initWebRtcPeerSend(false).then((function(){return resolve()})).catch((function(error){return reject(error)}))}else{_this.ee.once("stream-ready-to-publish",(function(){_this.publish().then((function(){return resolve()})).catch((function(error){return reject(error)}))}))}}))};Stream.prototype.disposeWebRtcPeer=function(){var webrtcId;if(!!this.webRtcPeer){this.webRtcPeer.dispose();webrtcId=this.webRtcPeer.getId()}this.stopWebRtcStats();logger.info((!!this.outboundStreamOpts?"Outbound ":"Inbound ")+"RTCPeerConnection with id ["+webrtcId+"] from 'Stream' with id ["+this.streamId+"] is now closed")};Stream.prototype.disposeMediaStream=function(){return __awaiter(this,void 0,void 0,(function(){var error_4;return __generator(this,(function(_a){switch(_a.label){case 0:if(!(!!this.filter&&this.filter.type.startsWith("VB:")))return[3,4];_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.removeFilterAux(true)];case 2:_a.sent();console.debug("Success removing Virtual Background filter for stream ".concat(this.streamId));return[3,4];case 3:error_4=_a.sent();console.error("Error removing Virtual Background filter for stream ".concat(this.streamId),error_4);return[3,4];case 4:if(this.mediaStream){this.mediaStream.getAudioTracks().forEach((function(track){track.stop()}));this.mediaStream.getVideoTracks().forEach((function(track){track.stop()}));delete this.mediaStream}if(this.localMediaStreamWhenSubscribedToRemote){this.localMediaStreamWhenSubscribedToRemote.getAudioTracks().forEach((function(track){track.stop()}));this.localMediaStreamWhenSubscribedToRemote.getVideoTracks().forEach((function(track){track.stop()}));delete this.localMediaStreamWhenSubscribedToRemote}if(!!this.speechEvent){if(!!this.speechEvent.stop){this.speechEvent.stop()}delete this.speechEvent}logger.info((!!this.outboundStreamOpts?"Local ":"Remote ")+"MediaStream from 'Stream' with id ["+this.streamId+"] is now disposed");return[2]}}))}))};Stream.prototype.displayMyRemote=function(){return this.isSubscribeToRemote};Stream.prototype.isSendAudio=function(){return!!this.outboundStreamOpts&&this.outboundStreamOpts.publisherProperties.audioSource!==null&&this.outboundStreamOpts.publisherProperties.audioSource!==false};Stream.prototype.isSendVideo=function(){return!!this.outboundStreamOpts&&this.outboundStreamOpts.publisherProperties.videoSource!==null&&this.outboundStreamOpts.publisherProperties.videoSource!==false};Stream.prototype.isSendScreen=function(){var screen=this.outboundStreamOpts.publisherProperties.videoSource==="screen";if(platform.isElectron()){screen=typeof this.outboundStreamOpts.publisherProperties.videoSource==="string"&&this.outboundStreamOpts.publisherProperties.videoSource.startsWith("screen:")}return!!this.outboundStreamOpts&&screen};Stream.prototype.enableHarkSpeakingEvent=function(){var _this=this;this.setHarkListenerIfNotExists();if(!this.harkSpeakingEnabled&&!!this.speechEvent){this.harkSpeakingEnabled=true;this.speechEvent.on("speaking",(function(){_this.session.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.session,"publisherStartSpeaking",_this.connection,_this.streamId)]);_this.streamManager.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.streamManager,"publisherStartSpeaking",_this.connection,_this.streamId)]);_this.harkSpeakingEnabledOnce=false}))}};Stream.prototype.enableOnceHarkSpeakingEvent=function(){var _this=this;this.setHarkListenerIfNotExists();if(!this.harkSpeakingEnabledOnce&&!!this.speechEvent){this.harkSpeakingEnabledOnce=true;this.speechEvent.once("speaking",(function(){if(_this.harkSpeakingEnabledOnce){_this.session.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.session,"publisherStartSpeaking",_this.connection,_this.streamId)]);_this.streamManager.emitEvent("publisherStartSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.streamManager,"publisherStartSpeaking",_this.connection,_this.streamId)])}_this.disableHarkSpeakingEvent(true)}))}};Stream.prototype.disableHarkSpeakingEvent=function(disabledByOnce){if(!!this.speechEvent){this.harkSpeakingEnabledOnce=false;if(disabledByOnce){if(this.harkSpeakingEnabled){return}}else{this.harkSpeakingEnabled=false}if(this.harkVolumeChangeEnabled||this.harkVolumeChangeEnabledOnce||this.harkStoppedSpeakingEnabled||this.harkStoppedSpeakingEnabledOnce){this.speechEvent.off("speaking")}else{this.speechEvent.stop();delete this.speechEvent}}};Stream.prototype.enableHarkStoppedSpeakingEvent=function(){var _this=this;this.setHarkListenerIfNotExists();if(!this.harkStoppedSpeakingEnabled&&!!this.speechEvent){this.harkStoppedSpeakingEnabled=true;this.speechEvent.on("stopped_speaking",(function(){_this.session.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.session,"publisherStopSpeaking",_this.connection,_this.streamId)]);_this.streamManager.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.streamManager,"publisherStopSpeaking",_this.connection,_this.streamId)]);_this.harkStoppedSpeakingEnabledOnce=false}))}};Stream.prototype.enableOnceHarkStoppedSpeakingEvent=function(){var _this=this;this.setHarkListenerIfNotExists();if(!this.harkStoppedSpeakingEnabledOnce&&!!this.speechEvent){this.harkStoppedSpeakingEnabledOnce=true;this.speechEvent.once("stopped_speaking",(function(){if(_this.harkStoppedSpeakingEnabledOnce){_this.session.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.session,"publisherStopSpeaking",_this.connection,_this.streamId)]);_this.streamManager.emitEvent("publisherStopSpeaking",[new PublisherSpeakingEvent_1.PublisherSpeakingEvent(_this.streamManager,"publisherStopSpeaking",_this.connection,_this.streamId)])}_this.disableHarkStoppedSpeakingEvent(true)}))}};Stream.prototype.disableHarkStoppedSpeakingEvent=function(disabledByOnce){if(!!this.speechEvent){this.harkStoppedSpeakingEnabledOnce=false;if(disabledByOnce){if(this.harkStoppedSpeakingEnabled){return}}else{this.harkStoppedSpeakingEnabled=false}if(this.harkVolumeChangeEnabled||this.harkVolumeChangeEnabledOnce||this.harkSpeakingEnabled||this.harkSpeakingEnabledOnce){this.speechEvent.off("stopped_speaking")}else{this.speechEvent.stop();delete this.speechEvent}}};Stream.prototype.enableHarkVolumeChangeEvent=function(force){var _this=this;if(this.setHarkListenerIfNotExists()){if(!this.harkVolumeChangeEnabled||force){this.harkVolumeChangeEnabled=true;this.speechEvent.on("volume_change",(function(harkEvent){var oldValue=_this.speechEvent.oldVolumeValue;var value={newValue:harkEvent,oldValue:oldValue};_this.speechEvent.oldVolumeValue=harkEvent;_this.streamManager.emitEvent("streamAudioVolumeChange",[new StreamManagerEvent_1.StreamManagerEvent(_this.streamManager,"streamAudioVolumeChange",value)])}))}}else{this.harkVolumeChangeEnabled=true}};Stream.prototype.enableOnceHarkVolumeChangeEvent=function(force){var _this=this;if(this.setHarkListenerIfNotExists()){if(!this.harkVolumeChangeEnabledOnce||force){this.harkVolumeChangeEnabledOnce=true;this.speechEvent.once("volume_change",(function(harkEvent){var oldValue=_this.speechEvent.oldVolumeValue;var value={newValue:harkEvent,oldValue:oldValue};_this.speechEvent.oldVolumeValue=harkEvent;_this.disableHarkVolumeChangeEvent(true);_this.streamManager.emitEvent("streamAudioVolumeChange",[new StreamManagerEvent_1.StreamManagerEvent(_this.streamManager,"streamAudioVolumeChange",value)])}))}}else{this.harkVolumeChangeEnabledOnce=true}};Stream.prototype.disableHarkVolumeChangeEvent=function(disabledByOnce){if(!!this.speechEvent){this.harkVolumeChangeEnabledOnce=false;if(disabledByOnce){if(this.harkVolumeChangeEnabled){return}}else{this.harkVolumeChangeEnabled=false}if(this.harkSpeakingEnabled||this.harkSpeakingEnabledOnce||this.harkStoppedSpeakingEnabled||this.harkStoppedSpeakingEnabledOnce){this.speechEvent.off("volume_change")}else{this.speechEvent.stop();delete this.speechEvent}}};Stream.prototype.isLocal=function(){return!this.inboundStreamOpts&&!!this.outboundStreamOpts};Stream.prototype.getSelectedIceCandidate=function(){var _this=this;return new Promise((function(resolve,reject){_this.webRtcStats.getSelectedIceCandidateInfo().then((function(report){return resolve(report)})).catch((function(error){return reject(error)}))}))};Stream.prototype.getRemoteIceCandidateList=function(){return this.webRtcPeer.remoteCandidatesQueue};Stream.prototype.getLocalIceCandidateList=function(){return this.webRtcPeer.localCandidatesQueue};Stream.prototype.streamIceConnectionStateBroken=function(){if(!this.getWebRtcPeer()||!this.getRTCPeerConnection()){return false}if(this.isLocal()&&!!this.session.openvidu.advancedConfiguration.forceMediaReconnectionAfterNetworkDrop){logger.warn('OpenVidu Browser advanced configuration option "forceMediaReconnectionAfterNetworkDrop" is enabled. Stream '.concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",") will force a reconnection"));return true}var iceConnectionState=this.getRTCPeerConnection().iceConnectionState;return iceConnectionState!=="connected"&&iceConnectionState!=="completed"};Stream.prototype.setHarkListenerIfNotExists=function(){if(!!this.mediaStream){if(!this.speechEvent){var harkOptions=!!this.harkOptions?this.harkOptions:this.session.openvidu.advancedConfiguration.publisherSpeakingEventsOptions||{};harkOptions.interval=typeof harkOptions.interval==="number"?harkOptions.interval:100;harkOptions.threshold=typeof harkOptions.threshold==="number"?harkOptions.threshold:-50;this.speechEvent=hark(this.mediaStream,harkOptions)}return true}return false};Stream.prototype.setupReconnectionEventEmitter=function(resolve,reject){if(this.reconnectionEventEmitter==undefined){this.reconnectionEventEmitter=new EventEmitter;return false}else{console.warn("Trying to reconnect stream ".concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",") but an ongoing reconnection process is active. Waiting for response..."));this.reconnectionEventEmitter.once("success",(function(){return resolve()}));this.reconnectionEventEmitter.once("error",(function(error){return reject(error)}));return true}};Stream.prototype.initWebRtcPeerSend=function(reconnect){var _this=this;return new Promise((function(resolve,reject){var _a;if(reconnect){if(_this.setupReconnectionEventEmitter(resolve,reject)){return}}else{_this.initHarkEvents()}var finalResolve=function(){var _a;if(reconnect){(_a=_this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("success");delete _this.reconnectionEventEmitter}return resolve()};var finalReject=function(error){var _a;if(reconnect){(_a=_this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("error",[error]);delete _this.reconnectionEventEmitter}return reject(error)};var successOfferCallback=function(sdpOfferParam){logger.debug("Sending SDP offer to publish as "+_this.streamId,sdpOfferParam);var method=reconnect?"reconnectStream":"publishVideo";var params;if(reconnect){params={stream:_this.streamId,sdpString:sdpOfferParam}}else{var typeOfVideo=void 0;if(_this.isSendVideo()){typeOfVideo=typeof MediaStreamTrack!=="undefined"&&_this.outboundStreamOpts.publisherProperties.videoSource instanceof MediaStreamTrack?TypeOfVideo_1.TypeOfVideo.CUSTOM:_this.isSendScreen()?TypeOfVideo_1.TypeOfVideo.SCREEN:TypeOfVideo_1.TypeOfVideo.CAMERA}params={doLoopback:_this.displayMyRemote()||false,hasAudio:_this.isSendAudio(),hasVideo:_this.isSendVideo(),audioActive:_this.audioActive,videoActive:_this.videoActive,typeOfVideo:typeOfVideo,frameRate:!!_this.frameRate?_this.frameRate:-1,videoDimensions:JSON.stringify(_this.videoDimensions),filter:_this.outboundStreamOpts.publisherProperties.filter,sdpOffer:sdpOfferParam}}_this.session.openvidu.sendRequest(method,params,(function(error,response){if(error){if(error.code===401){finalReject(new OpenViduError_1.OpenViduError(OpenViduError_1.OpenViduErrorName.OPENVIDU_PERMISSION_DENIED,"You don't have permissions to publish"))}else{finalReject("Error on publishVideo: "+JSON.stringify(error))}}else{_this.webRtcPeer.processRemoteAnswer(response.sdpAnswer).then((function(){_this.streamId=response.id;_this.creationTime=response.createdAt;_this.isLocalStreamPublished=true;_this.publishedOnce=true;if(_this.displayMyRemote()){_this.localMediaStreamWhenSubscribedToRemote=_this.mediaStream;_this.remotePeerSuccessfullyEstablished(reconnect)}if(reconnect){_this.ee.emitEvent("stream-reconnected-by-publisher",[])}else{_this.ee.emitEvent("stream-created-by-publisher",[])}_this.initWebRtcStats();logger.info("'Publisher' ("+_this.streamId+") successfully "+(reconnect?"reconnected":"published")+" to session");finalResolve()})).catch((function(error){finalReject(error)}))}}))};var config={mediaConstraints:{audio:_this.hasAudio,video:_this.hasVideo},simulcast:(_a=_this.outboundStreamOpts.publisherProperties.videoSimulcast)!==null&&_a!==void 0?_a:_this.session.openvidu.videoSimulcast,onIceCandidate:_this.connection.sendIceCandidate.bind(_this.connection),onIceConnectionStateException:_this.onIceConnectionStateExceptionHandler.bind(_this),iceServers:_this.getIceServersConf(),mediaStream:_this.mediaStream,mediaServer:_this.session.openvidu.mediaServer,typeOfVideo:_this.typeOfVideo?TypeOfVideo_1.TypeOfVideo[_this.typeOfVideo]:undefined};if(_this.session.openvidu.mediaServer!=="mediasoup"){config.simulcast=false}if(reconnect){_this.disposeWebRtcPeer()}if(_this.displayMyRemote()){_this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerSendrecv(config)}else{_this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerSendonly(config)}_this.webRtcPeer.addIceConnectionStateChangeListener("publisher of "+_this.connection.connectionId);_this.webRtcPeer.createOffer().then((function(sdpOffer){_this.webRtcPeer.processLocalOffer(sdpOffer).then((function(){successOfferCallback(sdpOffer.sdp)})).catch((function(error){finalReject(new Error("(publish) SDP process local offer error: "+JSON.stringify(error)))}))})).catch((function(error){finalReject(new Error("(publish) SDP create offer error: "+JSON.stringify(error)))}))}))};Stream.prototype.finalResolveForSubscription=function(reconnect,resolve){var _a;logger.info("'Subscriber' ("+this.streamId+") successfully "+(reconnect?"reconnected":"subscribed"));this.remotePeerSuccessfullyEstablished(reconnect);this.initWebRtcStats();if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("success");delete this.reconnectionEventEmitter}return resolve()};Stream.prototype.finalRejectForSubscription=function(reconnect,error,reject){var _a;logger.error("Error for 'Subscriber' ("+this.streamId+") while trying to "+(reconnect?"reconnect":"subscribe")+": "+error.toString());if(reconnect){(_a=this.reconnectionEventEmitter)===null||_a===void 0?void 0:_a.emitEvent("error",[error]);delete this.reconnectionEventEmitter}return reject(error)};Stream.prototype.initWebRtcPeerReceive=function(reconnect){var _this=this;return new Promise((function(resolve,reject){if(reconnect){if(_this.setupReconnectionEventEmitter(resolve,reject)){return}}if(_this.session.openvidu.mediaServer==="mediasoup"){_this.initWebRtcPeerReceiveFromServer(reconnect).then((function(){return _this.finalResolveForSubscription(reconnect,resolve)})).catch((function(error){return _this.finalRejectForSubscription(reconnect,error,reject)}))}else{_this.initWebRtcPeerReceiveFromClient(reconnect).then((function(){return _this.finalResolveForSubscription(reconnect,resolve)})).catch((function(error){return _this.finalRejectForSubscription(reconnect,error,reject)}))}}))};Stream.prototype.initWebRtcPeerReceiveFromClient=function(reconnect){var _this=this;return new Promise((function(resolve,reject){_this.completeWebRtcPeerReceive(reconnect,false).then((function(response){_this.webRtcPeer.processRemoteAnswer(response.sdpAnswer).then((function(){return resolve()})).catch((function(error){return reject(error)}))})).catch((function(error){return reject(error)}))}))};Stream.prototype.initWebRtcPeerReceiveFromServer=function(reconnect){var _this=this;return new Promise((function(resolve,reject){_this.session.openvidu.sendRequest("prepareReceiveVideoFrom",{sender:_this.streamId,reconnect:reconnect},(function(error,response){if(error){return reject(new Error("Error on prepareReceiveVideoFrom: "+JSON.stringify(error)))}else{_this.completeWebRtcPeerReceive(reconnect,false,response.sdpOffer).then((function(){return resolve()})).catch((function(error){return reject(error)}))}}))}))};Stream.prototype.completeWebRtcPeerReceive=function(reconnect,forciblyReconnect,sdpOfferByServer){var _this=this;return new Promise((function(resolve,reject){logger.debug("'Session.subscribe(Stream)' called");var sendSdpToServer=function(sdpString){logger.debug("Sending local SDP ".concat(!!sdpOfferByServer?"answer":"offer"," to subscribe to ").concat(_this.streamId),sdpString);var method=reconnect?"reconnectStream":"receiveVideoFrom";var params={};params[reconnect?"stream":"sender"]=_this.streamId;if(!!sdpOfferByServer){params[reconnect?"sdpString":"sdpAnswer"]=sdpString}else{params["sdpOffer"]=sdpString}if(reconnect){params["forciblyReconnect"]=forciblyReconnect}_this.session.openvidu.sendRequest(method,params,(function(error,response){if(error){return reject(new Error("Error on "+method+" : "+JSON.stringify(error)))}else{return resolve(response)}}))};var config={mediaConstraints:{audio:_this.hasAudio,video:_this.hasVideo},simulcast:false,onIceCandidate:_this.connection.sendIceCandidate.bind(_this.connection),onIceConnectionStateException:_this.onIceConnectionStateExceptionHandler.bind(_this),iceServers:_this.getIceServersConf(),mediaServer:_this.session.openvidu.mediaServer,typeOfVideo:_this.typeOfVideo?TypeOfVideo_1.TypeOfVideo[_this.typeOfVideo]:undefined};if(reconnect){_this.disposeWebRtcPeer()}_this.webRtcPeer=new WebRtcPeer_1.WebRtcPeerRecvonly(config);_this.webRtcPeer.addIceConnectionStateChangeListener(_this.streamId);if(!!sdpOfferByServer){_this.webRtcPeer.processRemoteOffer(sdpOfferByServer).then((function(){_this.webRtcPeer.createAnswer().then((function(sdpAnswer){_this.webRtcPeer.processLocalAnswer(sdpAnswer).then((function(){sendSdpToServer(sdpAnswer.sdp)})).catch((function(error){return reject(new Error("(subscribe) SDP process local answer error: "+JSON.stringify(error)))}))})).catch((function(error){return reject(new Error("(subscribe) SDP create answer error: "+JSON.stringify(error)))}))})).catch((function(error){return reject(new Error("(subscribe) SDP process remote offer error: "+JSON.stringify(error)))}))}else{_this.webRtcPeer.createOffer().then((function(sdpOffer){_this.webRtcPeer.processLocalOffer(sdpOffer).then((function(){sendSdpToServer(sdpOffer.sdp)})).catch((function(error){return reject(new Error("(subscribe) SDP process local offer error: "+JSON.stringify(error)))}))})).catch((function(error){return reject(new Error("(subscribe) SDP create offer error: "+JSON.stringify(error)))}))}}))};Stream.prototype.remotePeerSuccessfullyEstablished=function(reconnect){if(reconnect&&this.mediaStream!=null){this.disposeMediaStream()}this.mediaStream=new MediaStream;var receiver;for(var _i=0,_a=this.webRtcPeer.pc.getReceivers();_i<_a.length;_i++){receiver=_a[_i];if(!!receiver.track){this.mediaStream.addTrack(receiver.track)}}logger.debug("Peer remote stream",this.mediaStream);if(!!this.mediaStream){if(this.streamManager instanceof Subscriber_1.Subscriber){if(!!this.mediaStream.getAudioTracks()[0]){var enabled=reconnect?this.audioActive:!!this.streamManager.properties.subscribeToAudio;this.mediaStream.getAudioTracks()[0].enabled=enabled}if(!!this.mediaStream.getVideoTracks()[0]){var enabled=reconnect?this.videoActive:!!this.streamManager.properties.subscribeToVideo;this.mediaStream.getVideoTracks()[0].enabled=enabled}}this.updateMediaStreamInVideos();this.initHarkEvents()}};Stream.prototype.initHarkEvents=function(){if(!!this.mediaStream.getAudioTracks()[0]){if(this.session.anySpeechEventListenerEnabled("publisherStartSpeaking",true,this.streamManager)){this.enableOnceHarkSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStartSpeaking",false,this.streamManager)){this.enableHarkSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStopSpeaking",true,this.streamManager)){this.enableOnceHarkStoppedSpeakingEvent()}if(this.session.anySpeechEventListenerEnabled("publisherStopSpeaking",false,this.streamManager)){this.enableHarkStoppedSpeakingEvent()}if(this.harkVolumeChangeEnabledOnce){this.enableOnceHarkVolumeChangeEvent(true)}if(this.harkVolumeChangeEnabled){this.enableHarkVolumeChangeEvent(true)}}};Stream.prototype.onIceConnectionStateExceptionHandler=function(exceptionName,message,data){switch(exceptionName){case ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED:this.onIceConnectionFailed();break;case ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED:this.onIceConnectionDisconnected();break}this.session.emitEvent("exception",[new ExceptionEvent_1.ExceptionEvent(this.session,exceptionName,this,message,data)])};Stream.prototype.onIceConnectionFailed=function(){logger.log("[ICE_CONNECTION_FAILED] Handling ICE_CONNECTION_FAILED event. Reconnecting stream ".concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",")"));this.reconnectStreamAndLogResultingIceConnectionState(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_FAILED)};Stream.prototype.onIceConnectionDisconnected=function(){var _this=this;logger.log("[ICE_CONNECTION_DISCONNECTED] Handling ICE_CONNECTION_DISCONNECTED event. Waiting for ICE to be restored and reconnect stream ".concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",") if not possible"));var timeout=this.session.openvidu.advancedConfiguration.iceConnectionDisconnectedExceptionTimeout||4e3;this.awaitWebRtcPeerConnectionState(timeout).then((function(state){switch(state){case"failed":logger.warn("[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ".concat(_this.streamId," (").concat(_this.isLocal()?"Publisher":"Subscriber",") is now failed after ICE_CONNECTION_DISCONNECTED"));break;case"connected":case"completed":logger.log("[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ".concat(_this.streamId," (").concat(_this.isLocal()?"Publisher":"Subscriber",") automatically restored after ICE_CONNECTION_DISCONNECTED. Current ICE connection state: ").concat(state));break;case"closed":case"checking":case"new":case"disconnected":logger.warn("[ICE_CONNECTION_DISCONNECTED] ICE connection of stream ".concat(_this.streamId," (").concat(_this.isLocal()?"Publisher":"Subscriber",") couldn't be restored after ICE_CONNECTION_DISCONNECTED event. Current ICE connection state after ").concat(timeout," ms: ").concat(state));_this.reconnectStreamAndLogResultingIceConnectionState(ExceptionEvent_1.ExceptionEventName.ICE_CONNECTION_DISCONNECTED);break}}))};Stream.prototype.reconnectStreamAndLogResultingIceConnectionState=function(event){return __awaiter(this,void 0,void 0,(function(){var finalIceStateAfterReconnection,error_5;return __generator(this,(function(_a){switch(_a.label){case 0:_a.trys.push([0,2,,3]);return[4,this.reconnectStreamAndReturnIceConnectionState(event)];case 1:finalIceStateAfterReconnection=_a.sent();switch(finalIceStateAfterReconnection){case"connected":case"completed":logger.log("[".concat(event,"] Stream ").concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",") successfully reconnected after ").concat(event,". Current ICE connection state: ").concat(finalIceStateAfterReconnection));break;default:logger.error("[".concat(event,"] Stream ").concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",") failed to reconnect after ").concat(event,". Current ICE connection state: ").concat(finalIceStateAfterReconnection));break}return[3,3];case 2:error_5=_a.sent();logger.error("[".concat(event,"] Error reconnecting stream ").concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",") after ").concat(event,": ").concat(error_5));return[3,3];case 3:return[2]}}))}))};Stream.prototype.reconnectStreamAndReturnIceConnectionState=function(event){return __awaiter(this,void 0,void 0,(function(){var timeout,error_6;return __generator(this,(function(_a){switch(_a.label){case 0:logger.log("[".concat(event,"] Reconnecting stream ").concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber",") after event ").concat(event));_a.label=1;case 1:_a.trys.push([1,3,,4]);return[4,this.reconnectStream(event)];case 2:_a.sent();timeout=this.session.openvidu.advancedConfiguration.iceConnectionDisconnectedExceptionTimeout||4e3;return[2,this.awaitWebRtcPeerConnectionState(timeout)];case 3:error_6=_a.sent();logger.warn("[".concat(event,"] Error reconnecting stream ").concat(this.streamId," (").concat(this.isLocal()?"Publisher":"Subscriber","). Reason: ").concat(error_6));return[2,this.awaitWebRtcPeerConnectionState(1)];case 4:return[2]}}))}))};Stream.prototype.awaitWebRtcPeerConnectionState=function(timeout){return __awaiter(this,void 0,void 0,(function(){var state,interval,intervals,i;return __generator(this,(function(_a){switch(_a.label){case 0:state=this.getRTCPeerConnection().iceConnectionState;interval=150;intervals=Math.ceil(timeout/interval);i=0;_a.label=1;case 1:if(!(i0};return Stream}();exports.Stream=Stream},{"../OpenViduInternal/Enums/OpenViduError":53,"../OpenViduInternal/Enums/TypeOfVideo":54,"../OpenViduInternal/Events/ExceptionEvent":59,"../OpenViduInternal/Events/PublisherSpeakingEvent":62,"../OpenViduInternal/Events/StreamManagerEvent":68,"../OpenViduInternal/Events/StreamPropertyChangedEvent":69,"../OpenViduInternal/Logger/OpenViduLogger":81,"../OpenViduInternal/Utils/Platform":85,"../OpenViduInternal/WebRtcPeer/WebRtcPeer":86,"../OpenViduInternal/WebRtcStats/WebRtcStats":87,"./Filter":44,"./Subscriber":51,hark:5,uuid:22,"wolfy87-eventemitter":39}],50:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:true});exports.StreamManager=void 0;var EventDispatcher_1=require("./EventDispatcher");var StreamManagerEvent_1=require("../OpenViduInternal/Events/StreamManagerEvent");var VideoElementEvent_1=require("../OpenViduInternal/Events/VideoElementEvent");var ExceptionEvent_1=require("../OpenViduInternal/Events/ExceptionEvent");var VideoInsertMode_1=require("../OpenViduInternal/Enums/VideoInsertMode");var OpenViduLogger_1=require("../OpenViduInternal/Logger/OpenViduLogger");var Platform_1=require("../OpenViduInternal/Utils/Platform");var logger=OpenViduLogger_1.OpenViduLogger.getInstance();var platform;var StreamManager=function(_super){__extends(StreamManager,_super);function StreamManager(stream,targetElement){var _this=_super.call(this)||this;_this.videos=[];_this.lazyLaunchVideoElementCreatedEvent=false;platform=Platform_1.PlatformUtils.getInstance();_this.stream=stream;_this.stream.streamManager=_this;_this.remote=!_this.stream.isLocal();if(!!targetElement){var targEl=void 0;if(typeof targetElement==="string"){targEl=document.getElementById(targetElement)}else if(targetElement instanceof HTMLElement){targEl=targetElement}if(!!targEl){_this.firstVideoElement={targetElement:targEl,video:document.createElement("video"),id:"",canplayListenerAdded:false};if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){_this.firstVideoElement.video.playsInline=true}_this.targetElement=targEl;_this.element=targEl}}_this.canPlayListener=function(){_this.deactivateStreamPlayingEventExceptionTimeout();_this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(_this,"streamPlaying",undefined)])};return _this}StreamManager.prototype.on=function(type,handler){_super.prototype.onAux.call(this,type,"Event '"+type+"' triggered by '"+(this.remote?"Subscriber":"Publisher")+"'",handler);if(type==="videoElementCreated"){if(!!this.stream&&this.lazyLaunchVideoElementCreatedEvent){this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(this.videos[0].video,this,"videoElementCreated")]);this.lazyLaunchVideoElementCreatedEvent=false}}if(type==="streamPlaying"){if(this.videos[0]&&this.videos[0].video&&this.videos[0].video.currentTime>0&&this.videos[0].video.paused===false&&this.videos[0].video.ended===false&&this.videos[0].video.readyState===4){this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}if(this.stream.hasAudio){if(type==="publisherStartSpeaking"){this.stream.enableHarkSpeakingEvent()}if(type==="publisherStopSpeaking"){this.stream.enableHarkStoppedSpeakingEvent()}if(type==="streamAudioVolumeChange"){this.stream.enableHarkVolumeChangeEvent(false)}}return this};StreamManager.prototype.once=function(type,handler){_super.prototype.onceAux.call(this,type,"Event '"+type+"' triggered once by '"+(this.remote?"Subscriber":"Publisher")+"'",handler);if(type==="videoElementCreated"){if(!!this.stream&&this.lazyLaunchVideoElementCreatedEvent){this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(this.videos[0].video,this,"videoElementCreated")])}}if(type==="streamPlaying"){if(this.videos[0]&&this.videos[0].video&&this.videos[0].video.currentTime>0&&this.videos[0].video.paused===false&&this.videos[0].video.ended===false&&this.videos[0].video.readyState===4){this.ee.emitEvent("streamPlaying",[new StreamManagerEvent_1.StreamManagerEvent(this,"streamPlaying",undefined)])}}if(this.stream.hasAudio){if(type==="publisherStartSpeaking"){this.stream.enableOnceHarkSpeakingEvent()}if(type==="publisherStopSpeaking"){this.stream.enableOnceHarkStoppedSpeakingEvent()}if(type==="streamAudioVolumeChange"){this.stream.enableOnceHarkVolumeChangeEvent(false)}}return this};StreamManager.prototype.off=function(type,handler){_super.prototype.offAux.call(this,type,handler);if(type==="publisherStartSpeaking"){var remainingStartSpeakingEventListeners=this.ee.getListeners(type).length+this.stream.session.ee.getListeners(type).length;if(remainingStartSpeakingEventListeners===0){this.stream.disableHarkSpeakingEvent(false)}}if(type==="publisherStopSpeaking"){var remainingStopSpeakingEventListeners=this.ee.getListeners(type).length+this.stream.session.ee.getListeners(type).length;if(remainingStopSpeakingEventListeners===0){this.stream.disableHarkStoppedSpeakingEvent(false)}}if(type==="streamAudioVolumeChange"){var remainingVolumeEventListeners=this.ee.getListeners(type).length;if(remainingVolumeEventListeners===0){this.stream.disableHarkVolumeChangeEvent(false)}}return this};StreamManager.prototype.addVideoElement=function(video){this.initializeVideoProperties(video);if(!this.remote&&this.stream.displayMyRemote()){if(video.srcObject!==this.stream.getMediaStream()){video.srcObject=this.stream.getMediaStream()}}for(var _i=0,_a=this.videos;_i<_a.length;_i++){var v=_a[_i];if(v.video===video){return 0}}var returnNumber=1;for(var _b=0,_c=this.stream.session.streamManagers;_b<_c.length;_b++){var streamManager=_c[_b];if(streamManager.disassociateVideo(video)){returnNumber=-1;break}}this.stream.session.streamManagers.forEach((function(streamManager){streamManager.disassociateVideo(video)}));this.pushNewStreamManagerVideo({video:video,id:video.id,canplayListenerAdded:false});logger.info("New video element associated to ",this);return returnNumber};StreamManager.prototype.createVideoElement=function(targetElement,insertMode){var targEl;if(typeof targetElement==="string"){targEl=document.getElementById(targetElement);if(!targEl){throw new Error("The provided 'targetElement' couldn't be resolved to any HTML element: "+targetElement)}}else if(targetElement instanceof HTMLElement){targEl=targetElement}else{throw new Error("The provided 'targetElement' couldn't be resolved to any HTML element: "+targetElement)}var video=this.createVideo();this.initializeVideoProperties(video);var insMode=!!insertMode?insertMode:VideoInsertMode_1.VideoInsertMode.APPEND;switch(insMode){case VideoInsertMode_1.VideoInsertMode.AFTER:targEl.parentNode.insertBefore(video,targEl.nextSibling);break;case VideoInsertMode_1.VideoInsertMode.APPEND:targEl.appendChild(video);break;case VideoInsertMode_1.VideoInsertMode.BEFORE:targEl.parentNode.insertBefore(video,targEl);break;case VideoInsertMode_1.VideoInsertMode.PREPEND:targEl.insertBefore(video,targEl.childNodes[0]);break;case VideoInsertMode_1.VideoInsertMode.REPLACE:targEl.parentNode.replaceChild(video,targEl);break;default:insMode=VideoInsertMode_1.VideoInsertMode.APPEND;targEl.appendChild(video);break}var v={targetElement:targEl,video:video,insertMode:insMode,id:video.id,canplayListenerAdded:false};this.pushNewStreamManagerVideo(v);this.ee.emitEvent("videoElementCreated",[new VideoElementEvent_1.VideoElementEvent(v.video,this,"videoElementCreated")]);this.lazyLaunchVideoElementCreatedEvent=!!this.firstVideoElement;return video};StreamManager.prototype.updatePublisherSpeakingEventsOptions=function(publisherSpeakingEventsOptions){var currentHarkOptions=!!this.stream.harkOptions?this.stream.harkOptions:this.stream.session.openvidu.advancedConfiguration.publisherSpeakingEventsOptions||{};var newInterval=typeof publisherSpeakingEventsOptions.interval==="number"?publisherSpeakingEventsOptions.interval:typeof currentHarkOptions.interval==="number"?currentHarkOptions.interval:100;var newThreshold=typeof publisherSpeakingEventsOptions.threshold==="number"?publisherSpeakingEventsOptions.threshold:typeof currentHarkOptions.threshold==="number"?currentHarkOptions.threshold:-50;this.stream.harkOptions={interval:newInterval,threshold:newThreshold};if(!!this.stream.speechEvent){this.stream.speechEvent.setInterval(newInterval);this.stream.speechEvent.setThreshold(newThreshold)}};StreamManager.prototype.initializeVideoProperties=function(video){if(!(!this.remote&&this.stream.displayMyRemote())){if(video.srcObject!==this.stream.getMediaStream()){video.srcObject=this.stream.getMediaStream()}}video.autoplay=true;video.controls=false;if(platform.isSafariBrowser()||platform.isIPhoneOrIPad()&&(platform.isChromeMobileBrowser()||platform.isEdgeMobileBrowser()||platform.isOperaMobileBrowser()||platform.isFirefoxMobileBrowser())){video.playsInline=true}if(!video.id){video.id=(this.remote?"remote-":"local-")+"video-"+this.stream.streamId;if(!this.id&&!!this.targetElement){this.id=video.id}}if(this.remote&&this.isMirroredVideo(video)){this.removeMirrorVideo(video)}else if(!this.remote&&!this.stream.displayMyRemote()){video.muted=true;if(this.isMirroredVideo(video)&&!this.stream.outboundStreamOpts.publisherProperties.mirror){this.removeMirrorVideo(video)}else if(this.stream.outboundStreamOpts.publisherProperties.mirror&&!this.stream.isSendScreen()){this.mirrorVideo(video)}}};StreamManager.prototype.removeAllVideos=function(){var _this=this;for(var i=this.stream.session.streamManagers.length-1;i>=0;--i){if(this.stream.session.streamManagers[i]===this){this.stream.session.streamManagers.splice(i,1)}}this.videos.forEach((function(streamManagerVideo){if(!!streamManagerVideo.video&&!!streamManagerVideo.video.removeEventListener){streamManagerVideo.video.removeEventListener("canplay",_this.canPlayListener)}streamManagerVideo.canplayListenerAdded=false;if(!!streamManagerVideo.targetElement){streamManagerVideo.video.parentNode.removeChild(streamManagerVideo.video);_this.ee.emitEvent("videoElementDestroyed",[new VideoElementEvent_1.VideoElementEvent(streamManagerVideo.video,_this,"videoElementDestroyed")])}_this.removeSrcObject(streamManagerVideo);_this.videos.filter((function(v){return!v.targetElement}))}))};StreamManager.prototype.disassociateVideo=function(video){var disassociated=false;for(var i=0;i=0;--i){if(streamOptionsServer[i].id===this.stream.streamId){streamOptionsServer.splice(i,1)}}}}};return StreamEvent}(Event_1.Event);exports.StreamEvent=StreamEvent},{"../../OpenVidu/Publisher":47,"../../OpenVidu/Session":48,"../Logger/OpenViduLogger":81,"./Event":58}],68:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:true});exports.StreamManagerEvent=void 0;var Event_1=require("./Event");var StreamManagerEvent=function(_super){__extends(StreamManagerEvent,_super);function StreamManagerEvent(target,type,value){var _this=_super.call(this,false,target,type)||this;_this.value=value;return _this}StreamManagerEvent.prototype.callDefaultBehavior=function(){};return StreamManagerEvent}(Event_1.Event);exports.StreamManagerEvent=StreamManagerEvent},{"./Event":58}],69:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:true});exports.StreamPropertyChangedEvent=void 0;var Event_1=require("./Event");var StreamPropertyChangedEvent=function(_super){__extends(StreamPropertyChangedEvent,_super);function StreamPropertyChangedEvent(target,stream,changedProperty,newValue,oldValue,reason){var _this=_super.call(this,false,target,"streamPropertyChanged")||this;_this.stream=stream;_this.changedProperty=changedProperty;_this.newValue=newValue;_this.oldValue=oldValue;_this.reason=reason;return _this}StreamPropertyChangedEvent.prototype.callDefaultBehavior=function(){};return StreamPropertyChangedEvent}(Event_1.Event);exports.StreamPropertyChangedEvent=StreamPropertyChangedEvent},{"./Event":58}],70:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();Object.defineProperty(exports,"__esModule",{value:true});exports.VideoElementEvent=void 0;var Event_1=require("./Event");var VideoElementEvent=function(_super){__extends(VideoElementEvent,_super);function VideoElementEvent(element,target,type){var _this=_super.call(this,false,target,type)||this;_this.element=element;return _this}VideoElementEvent.prototype.callDefaultBehavior=function(){};return VideoElementEvent}(Event_1.Event);exports.VideoElementEvent=VideoElementEvent},{"./Event":58}],71:[function(require,module,exports){function Mapper(){var sources={};this.forEach=function(callback){for(var key in sources){var source=sources[key];for(var key2 in source)callback(source[key2])}};this.get=function(id,source){var ids=sources[source];if(ids==undefined)return undefined;return ids[id]};this.remove=function(id,source){var ids=sources[source];if(ids==undefined)return;delete ids[id];for(var i in ids){return false}delete sources[source]};this.set=function(value,id,source){if(value==undefined)return this.remove(id,source);var ids=sources[source];if(ids==undefined)sources[source]=ids={};ids[id]=value}}Mapper.prototype.pop=function(id,source){var value=this.get(id,source);if(value==undefined)return undefined;this.remove(id,source);return value};module.exports=Mapper},{}],72:[function(require,module,exports){var JsonRpcClient=require("./jsonrpcclient");exports.JsonRpcClient=JsonRpcClient},{"./jsonrpcclient":73}],73:[function(require,module,exports){var RpcBuilder=require("../");var WebSocketWithReconnection=require("./transports/webSocketWithReconnection");var OpenViduLogger=require("../../../Logger/OpenViduLogger").OpenViduLogger;Date.now=Date.now||function(){return+new Date};var PING_INTERVAL=5e3;var RECONNECTING="RECONNECTING";var CONNECTED="CONNECTED";var DISCONNECTED="DISCONNECTED";var Logger=OpenViduLogger.getInstance();function JsonRpcClient(configuration){var self=this;var wsConfig=configuration.ws;var notReconnectIfNumLessThan=-1;var pingNextNum=0;var enabledPings=true;var pingPongStarted=false;var pingInterval;var status=DISCONNECTED;var onreconnecting=wsConfig.onreconnecting;var onreconnected=wsConfig.onreconnected;var onconnected=wsConfig.onconnected;var onerror=wsConfig.onerror;configuration.rpc.pull=function(params,request){request.reply(null,"push")};wsConfig.onreconnecting=function(){Logger.debug("--------- ONRECONNECTING -----------");if(status===RECONNECTING){Logger.error("Websocket already in RECONNECTING state when receiving a new ONRECONNECTING message. Ignoring it");return}stopPing();status=RECONNECTING;if(onreconnecting){onreconnecting()}};wsConfig.onreconnected=function(){Logger.debug("--------- ONRECONNECTED -----------");if(status===CONNECTED){Logger.error("Websocket already in CONNECTED state when receiving a new ONRECONNECTED message. Ignoring it");return}status=CONNECTED;updateNotReconnectIfLessThan();if(onreconnected){onreconnected()}};wsConfig.onconnected=function(){Logger.debug("--------- ONCONNECTED -----------");if(status===CONNECTED){Logger.error("Websocket already in CONNECTED state when receiving a new ONCONNECTED message. Ignoring it");return}status=CONNECTED;enabledPings=true;usePing();if(onconnected){onconnected()}};wsConfig.onerror=function(error){Logger.debug("--------- ONERROR -----------");status=DISCONNECTED;stopPing();if(onerror){onerror(error)}};var ws=new WebSocketWithReconnection(wsConfig);Logger.debug("Connecting websocket to URI: "+wsConfig.uri);var rpcBuilderOptions={request_timeout:configuration.rpc.requestTimeout,ping_request_timeout:configuration.rpc.heartbeatRequestTimeout};var rpc=new RpcBuilder(RpcBuilder.packers.JsonRPC,rpcBuilderOptions,ws,(function(request){Logger.debug("Received request: "+JSON.stringify(request));try{var func=configuration.rpc[request.method];if(func===undefined){Logger.error("Method "+request.method+" not registered in client")}else{func(request.params,request)}}catch(err){Logger.error("Exception processing request: "+JSON.stringify(request));Logger.error(err)}}));this.send=function(method,params,callback){var requestTime=Date.now();rpc.encode(method,params,(function(error,result){if(error){try{Logger.error("ERROR:"+error.message+" in Request: method:"+method+" params:"+JSON.stringify(params)+" request:"+error.request);if(error.data){Logger.error("ERROR DATA:"+JSON.stringify(error.data))}}catch(e){}error.requestTime=requestTime}if(callback){if(result!=undefined&&result.value!=="pong"){Logger.debug("Response: "+JSON.stringify(result))}callback(error,result)}}))};function updateNotReconnectIfLessThan(){Logger.debug("notReconnectIfNumLessThan = "+pingNextNum+" (old="+notReconnectIfNumLessThan+")");notReconnectIfNumLessThan=pingNextNum}function sendPing(){if(enabledPings){var params=null;if(pingNextNum==0||pingNextNum==notReconnectIfNumLessThan){params={interval:configuration.heartbeat||PING_INTERVAL}}pingNextNum++;self.send("ping",params,function(pingNum){return function(error,result){if(error){Logger.debug("Error in ping request #"+pingNum+" ("+error.message+")");if(pingNum>notReconnectIfNumLessThan){enabledPings=false;updateNotReconnectIfLessThan();Logger.debug("Server did not respond to ping message #"+pingNum+". Reconnecting... ");ws.reconnectWs()}}}}(pingNextNum))}else{Logger.debug("Trying to send ping, but ping is not enabled")}}function usePing(){if(!pingPongStarted){Logger.debug("Starting ping (if configured)");pingPongStarted=true;if(configuration.heartbeat!=undefined){pingInterval=setInterval(sendPing,configuration.heartbeat);sendPing()}}}function stopPing(){clearInterval(pingInterval);pingPongStarted=false;enabledPings=false;pingNextNum=-1;rpc.cancel()}this.close=function(code,reason){Logger.debug("Closing with code: "+code+" because: "+reason);if(pingInterval!=undefined){Logger.debug("Clearing ping interval");clearInterval(pingInterval)}pingPongStarted=false;enabledPings=false;ws.close(code,reason)};this.reconnect=function(){ws.reconnectWs()};this.resetPing=function(){enabledPings=true;pingNextNum=0;usePing()};this.getReadyState=function(){return ws.getReadyState()}}module.exports=JsonRpcClient},{"../":76,"../../../Logger/OpenViduLogger":81,"./transports/webSocketWithReconnection":75}],74:[function(require,module,exports){var WebSocketWithReconnection=require("./webSocketWithReconnection");exports.WebSocketWithReconnection=WebSocketWithReconnection},{"./webSocketWithReconnection":75}],75:[function(require,module,exports){"use strict";var OpenViduLogger=require("../../../../Logger/OpenViduLogger").OpenViduLogger;var Logger=OpenViduLogger.getInstance();var MAX_RETRIES=2e3;var RETRY_TIME_MS=3e3;var CONNECTING=0;var OPEN=1;var CLOSING=2;var CLOSED=3;function WebSocketWithReconnection(config){var closing=false;var registerMessageHandler;var wsUri=config.uri;var reconnecting=false;var ws=new WebSocket(wsUri);ws.onopen=function(){Logger.debug("WebSocket connected to "+wsUri);if(config.onconnected){config.onconnected()}};ws.onerror=function(error){Logger.error("Could not connect to "+wsUri+" (invoking onerror if defined)",error);if(config.onerror){config.onerror(error)}};var reconnectionOnClose=function(){if(ws.readyState===CLOSED){if(closing){Logger.debug("Connection closed by user")}else{if(config.ismasternodecrashed()){Logger.error("Master Node has crashed. Stopping reconnection process")}else{Logger.debug("Connection closed unexpectedly. Reconnecting...");reconnect(MAX_RETRIES,1)}}}else{Logger.debug("Close callback from previous websocket. Ignoring it")}};ws.onclose=reconnectionOnClose;function reconnect(maxRetries,numRetries){Logger.debug("reconnect (attempt #"+numRetries+", max="+maxRetries+")");if(numRetries===1){if(reconnecting){Logger.warn("Trying to reconnect when already reconnecting... Ignoring this reconnection.");return}else{reconnecting=true}if(config.onreconnecting){config.onreconnecting()}}reconnectAux(maxRetries,numRetries)}function addReconnectionQueryParamsIfMissing(uriString){var searchParams=new URLSearchParams(new URL(uriString).search);if(!searchParams.has("reconnect")){uriString=Array.from(searchParams).length>0?uriString+"&reconnect=true":uriString+"?reconnect=true"}return uriString}function reconnectAux(maxRetries,numRetries){Logger.debug("Reconnection attempt #"+numRetries);ws.close(4104,"Connection closed for reconnection");wsUri=addReconnectionQueryParamsIfMissing(wsUri);ws=new WebSocket(wsUri);ws.onopen=function(){Logger.debug("Reconnected to "+wsUri+" after "+numRetries+" attempts...");reconnecting=false;registerMessageHandler();if(config.onreconnected()){config.onreconnected()}ws.onclose=reconnectionOnClose};ws.onerror=function(error){Logger.warn("Reconnection error: ",error);if(numRetries===maxRetries){if(config.ondisconnect){config.ondisconnect()}}else{setTimeout((function(){reconnect(maxRetries,numRetries+1)}),RETRY_TIME_MS)}}}this.close=function(code,reason){closing=true;ws.close(code,reason)};this.reconnectWs=function(){Logger.debug("reconnectWs");reconnect(MAX_RETRIES,1)};this.send=function(message){ws.send(message)};this.addEventListener=function(type,callback){registerMessageHandler=function(){ws.addEventListener(type,callback)};registerMessageHandler()};this.getReadyState=function(){return ws.readyState}}module.exports=WebSocketWithReconnection},{"../../../../Logger/OpenViduLogger":81}],76:[function(require,module,exports){var defineProperty_IE8=false;if(Object.defineProperty){try{Object.defineProperty({},"x",{})}catch(e){defineProperty_IE8=true}}if(!Function.prototype.bind){Function.prototype.bind=function(oThis){if(typeof this!=="function"){throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable")}var aArgs=Array.prototype.slice.call(arguments,1),fToBind=this,fNOP=function(){},fBound=function(){return fToBind.apply(this instanceof fNOP&&oThis?this:oThis,aArgs.concat(Array.prototype.slice.call(arguments)))};fNOP.prototype=this.prototype;fBound.prototype=new fNOP;return fBound}}var EventEmitter=require("events").EventEmitter;var inherits=require("inherits");var packers=require("./packers");var Mapper=require("./Mapper");var BASE_TIMEOUT=5e3;function unifyResponseMethods(responseMethods){if(!responseMethods)return{};for(var key in responseMethods){var value=responseMethods[key];if(typeof value=="string")responseMethods[key]={response:value}}return responseMethods}function unifyTransport(transport){if(!transport)return;if(transport instanceof Function)return{send:transport};if(transport.send instanceof Function)return transport;if(transport.postMessage instanceof Function){transport.send=transport.postMessage;return transport}if(transport.write instanceof Function){transport.send=transport.write;return transport}if(transport.onmessage!==undefined)return;if(transport.pause instanceof Function)return;throw new SyntaxError("Transport is not a function nor a valid object")}function RpcNotification(method,params){if(defineProperty_IE8){this.method=method;this.params=params}else{Object.defineProperty(this,"method",{value:method,enumerable:true});Object.defineProperty(this,"params",{value:params,enumerable:true})}}function RpcBuilder(packer,options,transport,onRequest){var self=this;if(!packer)throw new SyntaxError("Packer is not defined");if(!packer.pack||!packer.unpack)throw new SyntaxError("Packer is invalid");var responseMethods=unifyResponseMethods(packer.responseMethods);if(options instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after onRequest");onRequest=options;transport=undefined;options=undefined}if(options&&options.send instanceof Function){if(transport&&!(transport instanceof Function))throw new SyntaxError("Only a function can be after transport");onRequest=transport;transport=options;options=undefined}if(transport instanceof Function){if(onRequest!=undefined)throw new SyntaxError("There can't be parameters after onRequest");onRequest=transport;transport=undefined}if(transport&&transport.send instanceof Function)if(onRequest&&!(onRequest instanceof Function))throw new SyntaxError("Only a function can be after transport");options=options||{};EventEmitter.call(this);if(onRequest)this.on("request",onRequest);if(defineProperty_IE8)this.peerID=options.peerID;else Object.defineProperty(this,"peerID",{value:options.peerID});var max_retries=options.max_retries||0;function transportMessage(event){self.decode(event.data||event)}this.getTransport=function(){return transport};this.setTransport=function(value){if(transport){if(transport.removeEventListener)transport.removeEventListener("message",transportMessage);else if(transport.removeListener)transport.removeListener("data",transportMessage)}if(value){if(value.addEventListener)value.addEventListener("message",transportMessage);else if(value.addListener)value.addListener("data",transportMessage)}transport=unifyTransport(value)};if(!defineProperty_IE8)Object.defineProperty(this,"transport",{get:this.getTransport.bind(this),set:this.setTransport.bind(this)});this.setTransport(transport);var request_timeout=options.request_timeout||BASE_TIMEOUT;var ping_request_timeout=options.ping_request_timeout||request_timeout;var response_timeout=options.response_timeout||BASE_TIMEOUT;var duplicates_timeout=options.duplicates_timeout||BASE_TIMEOUT;var requestID=0;var requests=new Mapper;var responses=new Mapper;var processedResponses=new Mapper;var message2Key={};function storeResponse(message,id,dest){var response={message:message,timeout:setTimeout((function(){responses.remove(id,dest)}),response_timeout)};responses.set(response,id,dest)}function storeProcessedResponse(ack,from){var timeout=setTimeout((function(){processedResponses.remove(ack,from)}),duplicates_timeout);processedResponses.set(timeout,ack,from)}function RpcRequest(method,params,id,from,transport){RpcNotification.call(this,method,params);this.getTransport=function(){return transport};this.setTransport=function(value){transport=unifyTransport(value)};if(!defineProperty_IE8)Object.defineProperty(this,"transport",{get:this.getTransport.bind(this),set:this.setTransport.bind(this)});var response=responses.get(id,from);if(!(transport||self.getTransport())){if(defineProperty_IE8)this.duplicated=Boolean(response);else Object.defineProperty(this,"duplicated",{value:Boolean(response)})}var responseMethod=responseMethods[method];this.pack=packer.pack.bind(packer,this,id);this.reply=function(error,result,transport){if(error instanceof Function||error&&error.send instanceof Function){if(result!=undefined)throw new SyntaxError("There can't be parameters after callback");transport=error;result=null;error=undefined}else if(result instanceof Function||result&&result.send instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after callback");transport=result;result=null}transport=unifyTransport(transport);if(response)clearTimeout(response.timeout);if(from!=undefined){if(error)error.dest=from;if(result)result.dest=from}var message;if(error||result!=undefined){if(self.peerID!=undefined){if(error)error.from=self.peerID;else result.from=self.peerID}if(responseMethod){if(responseMethod.error==undefined&&error)message={error:error};else{var method=error?responseMethod.error:responseMethod.response;message={method:method,params:error||result}}}else message={error:error,result:result};message=packer.pack(message,id)}else if(response)message=response.message;else message=packer.pack({result:null},id);storeResponse(message,id,from);transport=transport||this.getTransport()||self.getTransport();if(transport)return transport.send(message);return message}}inherits(RpcRequest,RpcNotification);function cancel(message){var key=message2Key[message];if(!key)return;delete message2Key[message];var request=requests.pop(key.id,key.dest);if(!request)return;clearTimeout(request.timeout);storeProcessedResponse(key.id,key.dest)}this.cancel=function(message){if(message)return cancel(message);for(var message in message2Key)cancel(message)};this.close=function(){var transport=this.getTransport();if(transport&&transport.close)transport.close(4003,"Cancel request");this.cancel();processedResponses.forEach(clearTimeout);responses.forEach((function(response){clearTimeout(response.timeout)}))};this.encode=function(method,params,dest,transport,callback){if(params instanceof Function){if(dest!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=params;transport=undefined;dest=undefined;params=undefined}else if(dest instanceof Function){if(transport!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=dest;transport=undefined;dest=undefined}else if(transport instanceof Function){if(callback!=undefined)throw new SyntaxError("There can't be parameters after callback");callback=transport;transport=undefined}if(self.peerID!=undefined){params=params||{};params.from=self.peerID}if(dest!=undefined){params=params||{};params.dest=dest}var message={method:method,params:params};if(callback){var id=requestID++;var retried=0;message=packer.pack(message,id);function dispatchCallback(error,result){self.cancel(message);callback(error,result)}var request={message:message,callback:dispatchCallback,responseMethods:responseMethods[method]||{}};var encode_transport=unifyTransport(transport);function sendRequest(transport){var rt=method==="ping"?ping_request_timeout:request_timeout;request.timeout=setTimeout(timeout,rt*Math.pow(2,retried++));message2Key[message]={id:id,dest:dest};requests.set(request,id,dest);transport=transport||encode_transport||self.getTransport();if(transport)return transport.send(message);return message}function retry(transport){transport=unifyTransport(transport);console.warn(retried+" retry for request message:",message);var timeout=processedResponses.pop(id,dest);clearTimeout(timeout);return sendRequest(transport)}function timeout(){if(retried_this.instance.MAX_LENGTH_STRING_JSON){stringifyJson="".concat(stringifyJson.substring(0,_this.instance.MAX_LENGTH_STRING_JSON),"...")}if(globalThis["LOG_JSNLOG_RESULTS"]){console.log(stringifyJson)}return stringifyJson};jsnlog_1.JL.setOptions({defaultAjaxUrl:openVidu.httpUri+this.instance.JSNLOG_URL,serialize:logSerializer,enabled:true});(0,jsnlog_1.JL)().setOptions({appenders:[this.instance.currentAppender]});this.instance.isJSNLogSetup=true;this.instance.loggingSessionId=sessionId_1;this.instance.info("JSNLog configured.")}}catch(e){console.error("Error configuring JSNLog: ");console.error(e);this.instance.disableLogger()}};OpenViduLogger.getInstance=function(){if(!OpenViduLogger.instance){OpenViduLogger.instance=new OpenViduLogger}return OpenViduLogger.instance};OpenViduLogger.isInvalidResponse=function(xhr){return xhr.status==401||xhr.status==403||xhr.status==404||xhr.status==0};OpenViduLogger.prototype.canConfigureJSNLog=function(openVidu,logger){return openVidu.session.sessionId!=logger.loggingSessionId};OpenViduLogger.prototype.isOpenViduBrowserLogsDebugActive=function(openVidu){return openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug||openVidu.sendBrowserLogs===OpenViduLoggerConfiguration_1.OpenViduLoggerConfiguration.debug_app};OpenViduLogger.prototype.getConsoleWithJSNLog=function(){return function(openViduLogger){return{log:function(){var args=[];for(var _i=0;_i1920?globalThis.screen.width:1920,maxHeight:globalThis.screen.height>1080?globalThis.screen.height:1080},optional:[]}};if(!!canRequestAudioTrack){screen_constraints.audio={mandatory:{chromeMediaSource:error?"screen":"desktop"},optional:[]}}if(sourceId){screen_constraints.video.mandatory.chromeMediaSourceId=sourceId;if(screen_constraints.audio&&screen_constraints.audio.mandatory){screen_constraints.audio.mandatory.chromeMediaSourceId=sourceId}}return screen_constraints}function postGetSourceIdMessage(custom_parameter){if(!iframe){loadIFrame((function(){postGetSourceIdMessage(custom_parameter)}));return}if(!iframe.isLoaded){setTimeout((function(){postGetSourceIdMessage(custom_parameter)}),100);return}if(!custom_parameter){iframe.contentWindow.postMessage({captureSourceId:true},"*")}else if(!!custom_parameter.forEach){iframe.contentWindow.postMessage({captureCustomSourceId:custom_parameter},"*")}else{iframe.contentWindow.postMessage({captureSourceIdWithAudio:true},"*")}}var iframe;globalThis.getScreenConstraints=function(callback){loadIFrame((function(){getScreenId((function(error,sourceId,screen_constraints){if(!screen_constraints){screen_constraints={video:true}}callback(error,screen_constraints.video)}))}))};function loadIFrame(loadCallback){if(iframe){loadCallback();return}iframe=document.createElement("iframe");iframe.onload=function(){iframe.isLoaded=true;loadCallback()};iframe.src="https://openvidu.github.io/openvidu-screen-sharing-chrome-extension/";iframe.style.display="none";(document.body||document.documentElement).appendChild(iframe)}globalThis.getChromeExtensionStatus=function(callback){if(!!navigator.mozGetUserMedia){callback("installed-enabled");return}globalThis.addEventListener("message",onIFrameCallback);function onIFrameCallback(event){if(!event.data)return;if(event.data.chromeExtensionStatus){callback(event.data.chromeExtensionStatus);globalThis.removeEventListener("message",onIFrameCallback)}}setTimeout(postGetChromeExtensionStatusMessage,100)};function postGetChromeExtensionStatusMessage(){if(!iframe){loadIFrame(postGetChromeExtensionStatusMessage);return}if(!iframe.isLoaded){setTimeout(postGetChromeExtensionStatusMessage,100);return}iframe.contentWindow.postMessage({getChromeExtensionStatus:true},"*")}exports.getScreenId=globalThis.getScreenId},{}],84:[function(require,module,exports){var chromeMediaSource="screen";var sourceId;var screenCallback;if(typeof window!=="undefined"&&typeof navigator!=="undefined"&&typeof navigator.userAgent!=="undefined"){var isFirefox=typeof window.InstallTrigger!=="undefined";var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0;var isChrome=!!window.chrome&&!isOpera;window.addEventListener("message",(function(event){if(event.origin!=window.location.origin){return}onMessageCallback(event.data)}))}function onMessageCallback(data){if(data=="PermissionDeniedError"){if(screenCallback)return screenCallback("PermissionDeniedError");else throw new Error("PermissionDeniedError")}if(data=="rtcmulticonnection-extension-loaded"){chromeMediaSource="desktop"}if(data.sourceId&&screenCallback){screenCallback(sourceId=data.sourceId,data.canRequestAudioTrack===true)}}function isChromeExtensionAvailable(callback){if(!callback)return;if(chromeMediaSource=="desktop")return callback(true);window.postMessage("are-you-there","*");setTimeout((function(){if(chromeMediaSource=="screen"){callback(false)}else callback(true)}),2e3)}function getSourceId(callback){if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage("get-sourceId","*")}function getCustomSourceId(arr,callback){if(!arr||!arr.forEach)throw'"arr" parameter is mandatory and it must be an array.';if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage({"get-custom-sourceId":arr},"*")}function getSourceIdWithAudio(callback){if(!callback)throw'"callback" parameter is mandatory.';if(sourceId)return callback(sourceId);screenCallback=callback;window.postMessage("audio-plus-tab","*")}function getChromeExtensionStatus(extensionid,callback){if(isFirefox)return callback("not-chrome");if(arguments.length!=2){callback=extensionid;extensionid="lfcgfepafnobdloecchnfaclibenjold"}var image=document.createElement("img");image.src="chrome-extension://"+extensionid+"/icon.png";image.onload=function(){chromeMediaSource="screen";window.postMessage("are-you-there","*");setTimeout((function(){if(chromeMediaSource=="screen"){callback("installed-disabled")}else callback("installed-enabled")}),2e3)};image.onerror=function(){callback("not-installed")}}function getScreenConstraintsWithAudio(callback){getScreenConstraints(callback,true)}function getScreenConstraints(callback,captureSourceIdWithAudio){sourceId="";var firefoxScreenConstraints={mozMediaSource:"window",mediaSource:"window"};if(isFirefox)return callback(null,firefoxScreenConstraints);var screen_constraints={mandatory:{chromeMediaSource:chromeMediaSource,maxWidth:screen.width>1920?screen.width:1920,maxHeight:screen.height>1080?screen.height:1080},optional:[]};if(chromeMediaSource=="desktop"&&!sourceId){if(captureSourceIdWithAudio){getSourceIdWithAudio((function(sourceId,canRequestAudioTrack){screen_constraints.mandatory.chromeMediaSourceId=sourceId;if(canRequestAudioTrack){screen_constraints.canRequestAudioTrack=true}callback(sourceId=="PermissionDeniedError"?sourceId:null,screen_constraints)}))}else{getSourceId((function(sourceId){screen_constraints.mandatory.chromeMediaSourceId=sourceId;callback(sourceId=="PermissionDeniedError"?sourceId:null,screen_constraints)}))}return}if(chromeMediaSource=="desktop"){screen_constraints.mandatory.chromeMediaSourceId=sourceId}callback(null,screen_constraints)}exports.getScreenConstraints=getScreenConstraints;exports.getScreenConstraintsWithAudio=getScreenConstraintsWithAudio;exports.isChromeExtensionAvailable=isChromeExtensionAvailable;exports.getChromeExtensionStatus=getChromeExtensionStatus;exports.getSourceId=getSourceId},{}],85:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PlatformUtils=void 0;var platform=require("platform");var PlatformUtils=function(){function PlatformUtils(){}PlatformUtils.getInstance=function(){if(!this.instance){this.instance=new PlatformUtils}return PlatformUtils.instance};PlatformUtils.prototype.isChromeBrowser=function(){return platform.name==="Chrome"};PlatformUtils.prototype.isSafariBrowser=function(){return platform.name==="Safari"};PlatformUtils.prototype.isChromeMobileBrowser=function(){return platform.name==="Chrome Mobile"};PlatformUtils.prototype.isFirefoxBrowser=function(){return platform.name==="Firefox"};PlatformUtils.prototype.isFirefoxMobileBrowser=function(){return platform.name==="Firefox Mobile"||platform.name==="Firefox for iOS"};PlatformUtils.prototype.isOperaBrowser=function(){return platform.name==="Opera"};PlatformUtils.prototype.isOperaMobileBrowser=function(){return platform.name==="Opera Mobile"};PlatformUtils.prototype.isEdgeBrowser=function(){var version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;return platform.name==="Microsoft Edge"&&version>=80};PlatformUtils.prototype.isEdgeMobileBrowser=function(){var _a,_b;var version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;return platform.name==="Microsoft Edge"&&(((_a=platform.os)===null||_a===void 0?void 0:_a.family)==="Android"||((_b=platform.os)===null||_b===void 0?void 0:_b.family)==="iOS")&&version>45};PlatformUtils.prototype.isAndroidBrowser=function(){return platform.name==="Android Browser"};PlatformUtils.prototype.isElectron=function(){return platform.name==="Electron"};PlatformUtils.prototype.isNodeJs=function(){return platform.name==="Node.js"};PlatformUtils.prototype.isSamsungBrowser=function(){return platform.name==="Samsung Internet Mobile"||platform.name==="Samsung Internet"};PlatformUtils.prototype.isIPhoneOrIPad=function(){var userAgent=!!platform.ua?platform.ua:navigator.userAgent;var isTouchable="ontouchend"in document;var isIPad=/\b(\w*Macintosh\w*)\b/.test(userAgent)&&isTouchable;var isIPhone=/\b(\w*iPhone\w*)\b/.test(userAgent)&&/\b(\w*Mobile\w*)\b/.test(userAgent)&&isTouchable;return isIPad||isIPhone};PlatformUtils.prototype.isIOSWithSafari=function(){var userAgent=!!platform.ua?platform.ua:navigator.userAgent;return this.isIPhoneOrIPad()&&/\b(\w*Apple\w*)\b/.test(navigator.vendor)&&/\b(\w*Safari\w*)\b/.test(userAgent)&&!/\b(\w*CriOS\w*)\b/.test(userAgent)&&!/\b(\w*FxiOS\w*)\b/.test(userAgent)};PlatformUtils.prototype.isIonicIos=function(){return this.isIPhoneOrIPad()&&platform.ua.indexOf("Safari")===-1};PlatformUtils.prototype.isIonicAndroid=function(){return platform.os.family==="Android"&&platform.name=="Android Browser"};PlatformUtils.prototype.isMobileDevice=function(){return platform.os.family==="iOS"||platform.os.family==="Android"};PlatformUtils.prototype.isReactNative=function(){return false};PlatformUtils.prototype.isChromium=function(){return this.isChromeBrowser()||this.isChromeMobileBrowser()||this.isOperaBrowser()||this.isOperaMobileBrowser()||this.isEdgeBrowser()||this.isEdgeMobileBrowser()||this.isSamsungBrowser()||this.isIonicAndroid()||this.isIonicIos()||this.isElectron()};PlatformUtils.prototype.canScreenShare=function(){var version=(platform===null||platform===void 0?void 0:platform.version)?parseFloat(platform.version):-1;if(this.isMobileDevice()){return false}return this.isChromeBrowser()||this.isFirefoxBrowser()||this.isOperaBrowser()||this.isElectron()||this.isEdgeBrowser()||this.isSafariBrowser()&&version>=13};PlatformUtils.prototype.getName=function(){return platform.name||""};PlatformUtils.prototype.getVersion=function(){return platform.version||""};PlatformUtils.prototype.getFamily=function(){return platform.os.family||""};PlatformUtils.prototype.getDescription=function(){return platform.description||""};return PlatformUtils}();exports.PlatformUtils=PlatformUtils},{platform:12}],86:[function(require,module,exports){"use strict";var __extends=this&&this.__extends||function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}}();var __assign=this&&this.__assign||function(){__assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]0?configuration.iceServers:freeice(),mediaStream:configuration.mediaStream!==undefined?configuration.mediaStream:null,mode:!!configuration.mode?configuration.mode:"sendrecv",id:!!configuration.id?configuration.id:this.generateUniqueId()});logger.debug("[WebRtcPeer] configuration:\n".concat(JSON.stringify(this.configuration,null,2)));this.pc=new RTCPeerConnection({iceServers:this.configuration.iceServers});this.pc.addEventListener("icecandidate",(function(event){if(event.candidate!==null){var candidateInit=event.candidate;var iceCandidate=new RTCIceCandidate(candidateInit);_this.configuration.onIceCandidate(iceCandidate);if(iceCandidate.candidate!==""){_this.localCandidatesQueue.push(iceCandidate)}}}));this.pc.addEventListener("signalingstatechange",(function(){return __awaiter(_this,void 0,void 0,(function(){var candidate,error_1;return __generator(this,(function(_a){switch(_a.label){case 0:if(!(this.pc.signalingState==="stable"))return[3,6];_a.label=1;case 1:if(!(this.iceCandidateList.length>0))return[3,6];candidate=this.iceCandidateList.shift();_a.label=2;case 2:_a.trys.push([2,4,,5]);return[4,this.pc.addIceCandidate(candidate)];case 3:_a.sent();return[3,5];case 4:error_1=_a.sent();logger.error("Error when calling RTCPeerConnection#addIceCandidate for RTCPeerConnection "+this.getId(),error_1);return[3,5];case 5:return[3,1];case 6:return[2]}}))}))}))}WebRtcPeer.prototype.getId=function(){return this.configuration.id};WebRtcPeer.prototype.dispose=function(){logger.debug("Disposing WebRtcPeer");if(this.pc){if(this.pc.signalingState==="closed"){return}this.pc.close();this.remoteCandidatesQueue=[];this.localCandidatesQueue=[]}};WebRtcPeer.prototype.createOfferLegacy=function(){if(!!this.configuration.mediaStream){this.deprecatedPeerConnectionTrackApi()}var hasAudio=this.configuration.mediaConstraints.audio;var hasVideo=this.configuration.mediaConstraints.video;var options={offerToReceiveAudio:this.configuration.mode!=="sendonly"&&hasAudio,offerToReceiveVideo:this.configuration.mode!=="sendonly"&&hasVideo};logger.debug("[createOfferLegacy] RTCPeerConnection.createOffer() options:",JSON.stringify(options));return this.pc.createOffer(options)};WebRtcPeer.prototype.createOffer=function(){var _a,_b,_c,_d,_e,_f,_g,_h;return __awaiter(this,void 0,void 0,(function(){var _i,_j,track,tcInit,trackSettings,trackConsts,trackWidth,trackHeight,trackPixels,maxLayers,l,layerDiv,encoding,tc,sendParams,needSetParams,error_2,message,_k,_l,kind,sdpOffer,error_3,message;return __generator(this,(function(_m){switch(_m.label){case 0:if(!("addTransceiver"in this.pc)){logger.warn("[createOffer] Method RTCPeerConnection.addTransceiver() is NOT available; using LEGACY offerToReceive{Audio,Video}");return[2,this.createOfferLegacy()]}else{logger.debug("[createOffer] Method RTCPeerConnection.addTransceiver() is available; using it")}if(!(this.configuration.mode!=="recvonly"))return[3,7];if(!this.configuration.mediaStream){throw new Error("[WebRtcPeer.createOffer] Direction is '".concat(this.configuration.mode,"', but no stream was configured to be sent"))}_i=0,_j=this.configuration.mediaStream.getTracks();_m.label=1;case 1:if(!(_i<_j.length))return[3,6];track=_j[_i];tcInit={direction:this.configuration.mode,streams:[this.configuration.mediaStream]};if(track.kind==="video"&&this.configuration.simulcast){trackSettings=track.getSettings();trackConsts=track.getConstraints();trackWidth=(_c=(_b=(_a=trackSettings.width)!==null&&_a!==void 0?_a:trackConsts.width.ideal)!==null&&_b!==void 0?_b:trackConsts.width)!==null&&_c!==void 0?_c:0;trackHeight=(_f=(_e=(_d=trackSettings.height)!==null&&_d!==void 0?_d:trackConsts.height.ideal)!==null&&_e!==void 0?_e:trackConsts.height)!==null&&_f!==void 0?_f:0;logger.info("[createOffer] Video track dimensions: ".concat(trackWidth,"x").concat(trackHeight));trackPixels=trackWidth*trackHeight;maxLayers=0;if(trackPixels>=960*540){maxLayers=3}else if(trackPixels>=480*270){maxLayers=2}else{maxLayers=1}tcInit.sendEncodings=[];for(l=0;l0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]=0||c.candidate.indexOf(finalLocalCandidate.address)>=0)&&c.candidate.indexOf(finalLocalCandidate.port)>=0}));finalLocalCandidate.raw=[];for(_i=0,cand_1=cand;_i=0||c.candidate.indexOf(finalRemoteCandidate.address)>=0)&&c.candidate.indexOf(finalRemoteCandidate.port)>=0}));finalRemoteCandidate.raw=[];for(_a=0,cand_2=cand;_a-1){mediaType="video"}if(direction!=null&&mediaType!=null&&key!=null&&response_1[direction][mediaType]!=null){response_1[direction][mediaType][key]=Number(stat[key])}else if(direction!=null&&key!=null&&candidatePairStats_1.includes(key)){response_1[direction][key]=Number(stat[key])}}};switch(stat.type){case"outbound-rtp":addStat("outbound","bytesSent");addStat("outbound","packetsSent");addStat("outbound","framesEncoded");addStat("outbound","nackCount");addStat("outbound","firCount");addStat("outbound","pliCount");addStat("outbound","qpSum");break;case"inbound-rtp":addStat("inbound","bytesReceived");addStat("inbound","packetsReceived");addStat("inbound","packetsLost");addStat("inbound","jitter");addStat("inbound","framesDecoded");addStat("inbound","nackCount");addStat("inbound","firCount");addStat("inbound","pliCount");break;case"track":addStat("inbound","jitterBufferDelay");addStat("inbound","framesReceived");addStat("outbound","framesDropped");addStat("outbound","framesSent");addStat(_this.stream.isLocal()?"outbound":"inbound","frameHeight");addStat(_this.stream.isLocal()?"outbound":"inbound","frameWidth");break;case"candidate-pair":addStat("candidatepair","currentRoundTripTime");addStat("candidatepair","availableOutgoingBitrate");break}}));if(!(response_1===null||response_1===void 0?void 0:response_1.candidatepair)||Object.keys(response_1.candidatepair).length===0){delete response_1.candidatepair}return[2,resolve(response_1)];case 2:error_3=_a.sent();logger.error("Error getting common stats: ",error_3);return[2,reject(error_3)];case 3:return[2]}}))}))}))]}))}))};WebRtcStats.prototype.generateJSONStatsResponse=function(stats){return{"@timestamp":(new Date).toISOString(),participant_id:this.stream.connection.data,session_id:this.stream.session.sessionId,platform:platform.getName(),platform_description:platform.getDescription(),stream:"webRTC",webrtc_stats:stats}};WebRtcStats.prototype.getWebRtcStatsResponseOutline=function(){if(this.stream.isLocal()){return{outbound:{audio:{},video:{}},candidatepair:{}}}else{return{inbound:{audio:{},video:{}}}}};return WebRtcStats}();exports.WebRtcStats=WebRtcStats},{"../Logger/OpenViduLogger":81,"../Utils/Platform":85}]},{},[41]);