@vizbeetv/sdk 7.8.58 → 7.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- if(window.VizbeeSDK||(window.VizbeeSDK={}),!window.VizbeeSDK.logger){var e=function(){};window.VizbeeSDK.logger={debug:e,info:e,warn:e,error:e,d:e,i:e,w:e,e,critical:e,verbose:e}}const t="UNKNOWN",i="onEnd",n="subtitle",r="audio",s="bitmovin",o="videojs",a="theo",d="shaka";class l{constructor(e){if("Platform"===this.constructor.name)throw new TypeError("Platform::constructor() - Abstract class.");this.config=e||{},this.launchParams=void 0,this.isAppExitInProgress=!1}setConfig(e){this.config=e}get cloudPlatformName(){throw new TypeError("Platform::cloudPlatformName() - Abstract method.")}uniqueDeviceID(e,t){this.deviceId.uniqueDeviceID(e,t)}set deviceIDAlgorithm(e){}get deviceIDAlgorithm(){return this.deviceId.algorithm}get platformModel(){}get deviceInfo(){}get platformVersion(){}get networkInfo(){}get adId(){}get isAdTrackingDisabled(){}createInputDevice(){throw new TypeError("Platform::createInputDevice() - Abstract method.")}enableScreenSaver(e){}get defaultAppletAppId(){throw new TypeError("Platform::defaultAppletAppId() - Abstract method.")}get launchParamsDeferral(){return this.launchParams}get appLifeCycleManager(){}exit(){VizbeeTV.logger.i("BasePlatform","exit"),this.appLifeCycleManager&&this.appLifeCycleManager.emit(i)}set isAppExiting(e){this.isAppExitInProgress=e}get isAppExiting(){return this.isAppExitInProgress}createPlayer(){throw new TypeError("Platform::createPlayer() - Abstract method.")}}class c{constructor(e,t){if("BaseEvent"===this.constructor.name)throw new TypeError("BaseEvent::constructor() - Abstract class.");this.nativeEvent=e,this.source=t}}class u extends c{constructor(e,t){super(e,t)}}class p extends u{constructor(e,t){if(!(t instanceof w))throw new TypeError("TVRemoteEvent::constructor() - source must be an instance of BaseTVRemote.");super(e,t),this.keyCode=t.keyCodeMap[e.keyCode],this.keyName=t.keyNameMap[this.keyCode]}}class h{constructor(){if("BaseEventDispatcher"===this.constructor.name)throw new TypeError("BaseEventDispatcher::constructor() - Abstract class.");this.eventType=void 0,this._eventHandlers=[],this.registerListener()}registerListener(){throw new TypeError("BaseEventDispatcher::registerListener() - Abstract method.")}set onevent(e){if(void 0===e)this._eventHandlers=[];else{if(!(e instanceof Function))throw new TypeError("BaseEventDispatcher::onevent setter - callback must be an instance of Function.");this._eventHandlers.push(e)}}dispatchEvent(e){if(!(e instanceof c))throw new TypeError("BaseEventDispatcher::dispatchEvent() - event must be instance of BaseEvent.");this._eventHandlers.forEach(t=>{t instanceof Function&&t(e)})}reset(){this._eventHandlers=[]}}class g extends h{constructor(){if(super(),"BaseInputDevice"===this.constructor.name)throw new TypeError("BaseInputDevice::constructor() - Abstract class.")}}var f,v,y,m={exports:{}},b=m.exports;function S(){return f||(f=1,e=m,function(t){var i=setTimeout;function n(){}var r="function"==typeof setImmediate&&setImmediate||function(e){i(e,1)},s=function(e){"undefined"!=typeof console&&console},o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function a(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],h(e,this)}function d(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,r(function(){var i=1===e._state?t.onFulfilled:t.onRejected;if(null!==i){var n;try{n=i(e._value)}catch(e){return void c(t.promise,e)}l(t.promise,n)}else(1===e._state?l:c)(t.promise,e._value)})):e._deferreds.push(t)}function l(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var i=t.then;if(t instanceof a)return e._state=3,e._value=t,void u(e);if("function"==typeof i)return void h((n=i,r=t,function(){n.apply(r,arguments)}),e)}e._state=1,e._value=t,u(e)}catch(t){c(e,t)}var n,r}function c(e,t){e._state=2,e._value=t,u(e)}function u(e){2===e._state&&0===e._deferreds.length&&setTimeout(function(){e._handled||s(e._value)},1);for(var t=0,i=e._deferreds.length;t<i;t++)d(e,e._deferreds[t]);e._deferreds=null}function p(e,t,i){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=i}function h(e,t){var i=!1;try{e(function(e){i||(i=!0,l(t,e))},function(e){i||(i=!0,c(t,e))})}catch(e){if(i)return;i=!0,c(t,e)}}a.prototype.catch=function(e){return this.then(null,e)},a.prototype.then=function(e,t){var i=new a(n);return d(this,new p(e,t,i)),i},a.all=function(){var e=Array.prototype.slice.call(1===arguments.length&&o(arguments[0])?arguments[0]:arguments);return new a(function(t,i){if(0===e.length)return t([]);var n=e.length;function r(s,o){try{if(o&&("object"==typeof o||"function"==typeof o)){var a=o.then;if("function"==typeof a)return void a.call(o,function(e){r(s,e)},i)}e[s]=o,0===--n&&t(e)}catch(e){i(e)}}for(var s=0;s<e.length;s++)r(s,e[s])})},a.resolve=function(e){return e&&"object"==typeof e&&e.constructor===a?e:new a(function(t){t(e)})},a.reject=function(e){return new a(function(t,i){i(e)})},a.race=function(e){return new a(function(t,i){for(var n=0,r=e.length;n<r;n++)e[n].then(t,i)})},a._setImmediateFn=function(e){r=e},a._setUnhandledRejectionFn=function(e){s=e},e.exports?e.exports=a:t.Promise||(t.Promise=a)}(b)),m.exports;var e}function _(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function I(){if(y)return v;y=1;var e={get:function(e,t,i){for(var n=Array.isArray(t)?t:[t],r=e,s=0;s<n.length;s++){if(null==r)return i;r=r[n[s]]}return void 0===r?i:r},extend:function(e){if(null==e)return e;for(var t=1;t<arguments.length;t++){var i=arguments[t];if(null!=i)for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},isObject:function(e){return null!==e&&"object"==typeof e},find:function(e,t){if(null!=e){if(Array.isArray(e))return e.find(t);for(var i=Object.keys(e),n=0;n<i.length;n++){var r=e[i[n]];if(t(r,i[n],e))return r}}},keys:function(e){return Object.keys(e)},isString:function(e){return"string"==typeof e},filter:function(e,t){return Array.isArray(e)?e.filter(t):Object.keys(e).reduce(function(i,n){return t(e[n],n,e)&&i.push(e[n]),i},[])},omit:function(e){var t=Array.isArray(arguments[1])?arguments[1]:Array.prototype.slice.call(arguments,1),i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&-1===t.indexOf(n)&&(i[n]=e[n]);return i},isUndefined:function(e){return void 0===e},isNumber:function(e){return"number"==typeof e},isArray:function(e){return Array.isArray(e)},each:function(e,t){return Array.isArray(e)?e.forEach(t):null!=e&&Object.keys(e).forEach(function(i){t(e[i],i,e)}),e},contains:function(e,t){return-1!==e.indexOf(t)},values:function(e){return Object.keys(e).map(function(t){return e[t]})},isFunction:function(e){return"function"==typeof e},isEmpty:function(e){return null==e||(Array.isArray(e)||"string"==typeof e?0===e.length:0===Object.keys(e).length)},clone:function(t){return Array.isArray(t)?t.slice():e.extend({},t)},reject:function(e,t){return Array.isArray(e)?e.filter(function(e){return!t(e)}):Object.keys(e).reduce(function(i,n){return t(e[n],n,e)||i.push(e[n]),i},[])},reduce:function(e,t,i){return Array.isArray(e)?e.reduce(t,i):(Object.keys(e).forEach(function(n){i=t(i,e[n],n,e)}),i)},isBoolean:function(e){return!0===e||!1===e},isNaN:function(e){return"number"==typeof e&&e!=e},isEqual:function(e,t){return JSON.stringify(e)===JSON.stringify(t)},pluck:function(e,t){return e.map(function(e){return e[t]})},findIndex:function(e,t){var i="function"==typeof t?t:function(e){return null!=e&&Object.keys(t).every(function(i){return e[i]===t[i]})};return e.findIndex(i)},findLastIndex:function(e,t){for(var i="function"==typeof t?t:function(e){return null!=e&&Object.keys(t).every(function(i){return e[i]===t[i]})},n=e.length-1;n>=0;n--)if(i(e[n],n,e))return n;return-1},findWhere:function(e,t){return e.find(function(e){return null!=e&&Object.keys(t).every(function(i){return e[i]===t[i]})})},without:function(e){var t=Array.prototype.slice.call(arguments,1);return e.filter(function(e){return-1===t.indexOf(e)})},sortBy:function(e,t){var i="function"==typeof t?t:function(e){return e[t]};return e.slice().sort(function(e,t){var n=i(e),r=i(t);return n<r?-1:n>r?1:0})},rest:function(e,t){return e.slice(void 0===t?1:t)},indexOf:function(e,t){return e.indexOf(t)},intersection:function(){var e=Array.prototype.slice.call(arguments);return e[0].filter(function(t){return e.every(function(e){return-1!==e.indexOf(t)})})}};return v=e}var T=_(I());let E=[],V=[],P=[],A=document.getElementsByTagName("HEAD")[0],C=document.getElementsByTagName("BODY")[0];class D{static xchangeHLSUrl(e,t,i,n,r,s){var o="unknown",a="unknown";t&&(o=t),i&&(a=i);var d="https://hlsxchange.claspws.tv/"+o+"/"+a;return e&&e.indexOf(d)>=0?e:(n&&r&&s&&(d+="/"+n+"/"+r+"/"+s),d+="/x.m3u8?hlsurl="+e)}static getRandomIntInclusive(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}static buildErrorEvent(e,t,i){return{code:e,reason:t,data:i}}static loadStyleSheet(e){if(!e||!(e instanceof String||"string"==typeof e))throw new TypeError("Util::loadStyleSheet - Url must be a string.");var t=document.createElement("link");t.setAttribute("rel","stylesheet"),t.setAttribute("type","text/css"),A.appendChild(t),P.push(t),t.setAttribute("href",e)}static loadSynchronousScripts(e){var t=t||void 0;if(t||(t=S()),void 0===D.loadSynchronousScripts.scripts&&(D.loadSynchronousScripts.scripts=[],D.loadSynchronousScripts.index=-1,D.loadSynchronousScripts.loading=!1,D.loadSynchronousScripts.next=function(){if(!D.loadSynchronousScripts.loading){D.loadSynchronousScripts.loading=!0;var e=D.loadSynchronousScripts.scripts[++D.loadSynchronousScripts.index],t=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.src=e.src,i.onload=()=>{D.loadSynchronousScripts.loading=!1,D.loadSynchronousScripts.index<D.loadSynchronousScripts.scripts.length-1&&D.loadSynchronousScripts.next(),e.resolve()},t.appendChild(i)}}),e){for(var i=0;i<D.loadSynchronousScripts.scripts.length;i++)if(D.loadSynchronousScripts.scripts[i].src==e)return D.loadSynchronousScripts.scripts[i].promise;var n={src:e};n.promise=new t(e=>{n.resolve=e}),D.loadSynchronousScripts.scripts.push(n),D.loadSynchronousScripts.next()}return D.loadSynchronousScripts.scripts[D.loadSynchronousScripts.scripts.length-1].promise}static loadScript(e,t,i){if(!e||!(e instanceof String||"string"==typeof e))throw new TypeError("Util::loadScript - Url must be a string.");t=!(!t&&void 0!==t);var n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("async",t),n.onload=i||(()=>{}),A.appendChild(n),E.push(n),n.setAttribute("src",e)}static loadScriptToBody(e,t,i){if(!e||!(e instanceof String||"string"==typeof e))throw new TypeError("Util::loadScript - Url must be a string.");t=!(!t&&void 0!==t);var n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("async",t),n.onload=i||(()=>{}),C.appendChild(n),V.push(n),n.setAttribute("src",e)}static clearLoadedScripts(){for(let e=0;e<E.length;e++)E[e]&&E[e]instanceof Node&&(A.removeChild(E[e]),delete E[e])}static clearBodyLoadedScripts(){for(let e=0;e<V.length;e++)V[e]&&V[e]instanceof Node&&(C.removeChild(V[e]),delete V[e])}static clearLoadedStyleSheets(){for(let e=0;e<P.length;e++)P[e]&&P[e]instanceof Node&&(P[e].disabled=!0,A.removeChild(P[e]),delete P[e])}static clearAllLoadedScriptsAndStyleSheets(){D.clearLoadedScripts(),D.clearLoadedStyleSheets()}static addClass(e,t){if(t){var i=t.className;if(-1!=i.indexOf(e))return;""!=i&&(e=" "+e),t.className=i+e}}static removeClass(e,t){if(t){var i=t.className,n=new RegExp(e,"g");i=i.replace(n,""),t.className=i}}static hasClass(e,t){return(" "+e.className+" ").indexOf(" "+t+" ")>-1}static elementInViewport(e,t,i){var n=e.getBoundingClientRect(),r=n.top,s=n.bottom,o=n.left,a=n.right,d=document.documentElement.clientHeight,l=document.documentElement.clientWidth,c=window.innerHeight,u=window.innerWidth;return i&&(r-=i),t?r>=0&&s<=window.innerHeight:r>=0&&r<=(c||d)&&o>=0&&o<=(u||l)||s>=0&&s<=(c||d)&&a>=0&&a<=(u||l)}static smoothScroll(e,t){var i=e,n=e;do{if(!(i=i.parentNode))return;i.scrollTop+=1}while(0==i.scrollTop);var r=0;do{if(e==i)break;r+=e.offsetTop}while(e=e.offsetParent);D.myscroll(n,t,i,i.scrollTop,r-t,0)}static myscroll(e,t,i,n,r,s){++s>10||e.children.length>0&&D.elementInViewport(e.children.item(0),!0,t)||(i.scrollTop=n+(r-n)/10*s,setTimeout(function(){D.myscroll(e,t,i,n,r,s)},20))}static xhr(e){var t=t||void 0;return t||(t=S()),new t(function(t,i){var n=0===e.retries?0:e.retries||3;!function r(){var s=new XMLHttpRequest;e.disableSSL||(e.url=e.url.replace(/^http:\/\//i,"https://")),s.open(e.method||"GET",e.url,!0),Object.keys(e.headers||{}).forEach(function(t){s.setRequestHeader(t,e.headers[t])});var o=void 0;s.onreadystatechange=function(a){var d,l;if(2==s.readyState&&(d=s.getAllResponseHeaders().trim().split(/[\r\n]+/),l={},d.forEach(function(e){var t=e.split(": "),i=t.shift(),n=t.join(": ");l[i]=n}),o=l),4===s.readyState)if(-1===[200,201,202,203,204,304].indexOf(s.status))n>0?(n--,r()):e.isFullResponse?i(s):i(new Error("Server responded with a status of "+s.status));else try{var c=a.target;e.format=e.format||"json","json"===e.format?(c=c.response?JSON.parse(c.response):{}).headers?Object.assign(c.headers,o):c.headers=o:"xml"===e.format&&(c=c.responseXML),e.isFullResponse?t({xhr:a.target,data:c,headers:o}):t(c)}catch(a){n>0?(n--,r()):e.isFullResponse?i(s):i("JSON parse error with Server response")}},e.timeout&&(s.timeout=e.timeout,s.ontimeout=function(t){n>0?(n--,r()):i(new Error("Server timeout "+e.timeout+"ms"))}),s.send(e.data)}()})}static timeSnapToMs(e){e.split(".").length<=1&&(e+=".000");let t=e.split(":"),i=t.pop().split("."),n=1e3*Number(i[0])+Number(i[1]);return n+=1e3*Number(t.pop())*60,n+=1e3*Number(t.pop())*60*60,n}static millisecondsToString(e,t){var i="",n=Math.floor(e%31536e3%86400%3600%60);i=isNaN(n)||n<=0?":00":n<10?":0"+n:":"+n;var r=Math.floor(e%31536e3%86400%3600/60);i=isNaN(r)||r<=0?"00"+i:r<10?"0"+r+i:r+i;var s=Math.floor(e%31536e3%86400/3600);return t?i=isNaN(s)||s<=0?"00:"+i:s<10?"0"+s+":"+i:s+":"+i:s>0&&(i=s+":"+i),i}static getUrlVars(e=window.location.href){for(var t,i={},n=e.slice(e.indexOf("?")+1).split("&"),r=0;r<n.length;r++)i[(t=n[r].split("="))[0]]=decodeURIComponent(t[1]);return i}static updateUrlQueryParams(e,t){if(!e)return VizbeeUtils.logger.warn("Util::updateUrlQueryParams - INVALID inputUrl, doing nothing"),e;if(T.isEmpty(t))return VizbeeUtils.logger.warn("Util::updateUrlQueryParams - INVALID inputParams, doing nothing"),e;try{let i=new URL(e),n=new URLSearchParams(i.search);Object.keys(t).forEach(e=>n.set(e,t[e])),i.search=n.toString();let r=i.toString();return VizbeeUtils.logger.debug("Util::updateUrlQueryParams - updated url="+r),r}catch(t){return VizbeeUtils.logger.error("Util::updateUrlQueryParams - failed to update query params for url="+e),e}}static get docCookies(){return{getItem:function(e){return e&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null},setItem:function(e,t,i,n,r,s){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e))return!1;var o="";if(i)switch(i.constructor){case Number:o=i===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+i;break;case String:o="; expires="+i;break;case Date:o="; expires="+i.toUTCString()}return document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+o+(r?"; domain="+r:"")+(n?"; path="+n:"")+(s?"; secure":""),!0},removeItem:function(e,t,i){return!!this.hasItem(e)&&(document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"+(i?"; domain="+i:"")+(t?"; path="+t:""),!0)},hasItem:function(e){return!!e&&new RegExp("(?:^|;\\s*)"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:function(){for(var e=document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:\=[^;]*)?;\s*/),t=e.length,i=0;i<t;i++)e[i]=decodeURIComponent(e[i]);return e},eraseCookieFromAllPaths:function(e){var t=location.pathname.split("/"),i=" path=";document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;";for(var n=0;n<t.length;n++)i+=("/"!=i.substr(-1)?"/":"")+t[n],document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;"+i+";"}}}static invert(e){for(var t={},i=Object.keys(e),n=0,r=i.length;n<r;n++)t[e[i[n]]]=i[n];return t}static deepMerge(e,t){var i=Array.isArray(t),n=i&&[]||{};return i?(e=e||[],n=n.concat(e),t.forEach(function(t,i){void 0===n[i]?n[i]=t:"object"==typeof t?n[i]=D.deepMerge(e[i],t):-1===e.indexOf(t)&&n.push(t)})):("object"==typeof e&&null!==e&&Object.keys(e).forEach(function(t){n[t]=e[t]}),Object.keys(t).forEach(function(i){"object"==typeof t[i]&&t[i]&&e[i]?n[i]=D.deepMerge(e[i],t[i]):n[i]=t[i]})),n}static isEqual(e,t){return T.isEqual(e,t)}static flatten(e){var t={};return function e(i,n){if(Object(i)!==i)t[n]=i;else if(Array.isArray(i)){for(var r=0,s=i.length;r<s;r++)e(i[r],n+"["+r+"]");0==s&&(t[n]=[])}else{var o=!0;for(var a in i)o=!1,e(i[a],n?n+"."+a:a);o&&n&&(t[n]={})}}(e,""),t}static unflatten(e){if(Object(e)!==e||Array.isArray(e))return e;var t=/\.?([^.\[\]]+)|\[(\d+)\]/g,i={};for(var n in e){for(var r,s=i,o="";r=t.exec(n);)s=s[o]||(s[o]=r[2]?[]:{}),o=r[2]||r[1];s[o]=e[n]}return i[""]||i}static decodeB64Recurse(e,t){if(!e||!t)return e;for(var i in e){var n=e[i];if("object"==typeof n)D.decodeB64Recurse(n,t);else if(i.indexOf(t)>-1){var r=i.replace(t,"");if(e[r]=e[i],delete e[i],"string"==typeof e[r]){var s=decodeURIComponent(escape(atob(e[r])));e[r]=D.parseFunction(s)}}}return e}static parseFunction(e){var t=e.indexOf("{"),i=e.substring(t+1,e.lastIndexOf("}")),n=e.substring(0,t),r=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).split(",");function s(){return Function.apply(this,r)}return r.push(i),s.prototype=Function.prototype,new s}static padStart(e,t,i){return t|=0,i=String(void 0!==i?i:" "),e.length>t?String(e):((t-=e.length)>i.length&&(i+=D.repeat(i,t/i.length)),i.slice(0,t)+String(e))}static padEnd(e,t,i){return t|=0,i=String(void 0!==i?i:" "),e.length>t?String(e):((t-=e.length)>i.length&&(i+=D.repeat(i,t/i.length)),String(e)+i.slice(0,t))}static repeat(e,t){if(!e)throw new TypeError("can't convert "+e+" to object");var i=""+e;if((t=+t)!=t&&(t=0),t<0)throw new RangeError("repeat count must be non-negative");if(t==1/0)throw new RangeError("repeat count must be less than infinity");if(t=Math.floor(t),0==i.length||0==t)return"";if(i.length*t>=1<<28)throw new RangeError("repeat count must not overflow maximum string size");var n=i.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)i+=i,t--;return i+i.substring(0,n-i.length)}static getShortString(e,t){if(!T.isString(t))return e;if(!T.isString(e))return e;if(-1!=e.indexOf(t)){let i=e.trim().split(t);return T.reduce(i,(e,t)=>e+t.charAt(0),"")}return e}static toCamelCase(e){return void 0===e?e:(e=e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))).charAt(0).toLowerCase()+e.slice(1)}static matchStringWithRegex(e,t){return null!=t&&null!=e&&new RegExp(e,"i").test(t)}static isValidIPv4Address(e){return null!=e&&D.matchStringWithRegex(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,e)}static convertObjectsToString(e){if(!e)return e;if(!Array.isArray(e))return e;for(let t=0;t<e.length;t++){let i=e[t];try{"object"==typeof i&&(i=JSON.stringify(i))}catch(e){}e[t]=i}return e}static getUpdatedStringWithReplacedValues(e,t){return T.isString(e)?!t||Array.isArray(t)||"object"!=typeof t?(VizbeeUtils.logger.d("Util","getUpdatedStringWithReplacedValues","INVALID input json, NOT updating input string"),e):(Object.keys(t).forEach(i=>{e=e.replace(new RegExp(i,"gi"),t[i])}),e):(VizbeeUtils.logger.warn("Util::getUpdatedStringWithReplacedValues - INVALID inputString, NOT updating input string"),e)}static uuidv4(){return crypto&&crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)):Math.floor(1e10*Math.random()).toString()}static checkIfImageExists(e){var t=t||void 0;return t||(t=S()),new t(function(t,i){const n=new Image;n.src=e,n.complete?t(!0):(n.onload=()=>{t(!0)},n.onerror=()=>{t(!1)})})}static getFormEncodedUriFormat(e){if(T.isObject(e)){var t=[];for(var i in e){var n=encodeURIComponent(i),r=encodeURIComponent(e[i]);t.push(n+"="+r)}return t.join("&")}}}let k=!1;class w extends g{constructor(e){if(super(),VizbeeTV.logger.debug("constructing BaseTVRemote"),this.eventType=p,!(e&&e instanceof l))throw new Error("BaseTVRemote::constructor() -- platform cannot be empty or invalid.");this.platform=e}static get keys(){return{up:1,down:2,left:3,right:4,select:5,play:6,pause:7,stop:8,ffw:9,rw:10,back:11,exit:12,play_pause:13,alt_up:14,alt_down:15,alt_left:16,alt_right:17,skip_next:18,skip_prev:19}}get keyNameMap(){return{1:"up",2:"down",3:"left",4:"right",5:"select",6:"play",7:"pause",8:"stop",9:"fast-forward",10:"rewind",11:"back",12:"exit",13:"play-pause",14:"alt_up",15:"alt_down",16:"alt_left",17:"alt_right",18:"skip_next",19:"skip_prev"}}get keyCodeMap(){throw new TypeError("Abstract method - BaseTVRemote::keyMap getter.")}registerListener(){try{k=!0;let e="keydown";document.addEventListener(e,e=>{this.dispatchEvent(new p(e,this))})}catch(e){VizbeeTV.logger.error("registerListener error - ",e.message,e)}}sendKeyEvent(e){try{var t=D.invert(this.keyCodeMap)[e],i=new Event("keydown");i.keyCode=t,i.charCode=t,document.dispatchEvent(i)}catch(e){VizbeeTV.logger.error("sendKeyEvent error ",e.message,e)}}sendPlay(){this.sendKeyEvent(w.keys.play)}sendPause(){this.sendKeyEvent(w.keys.pause)}sendStop(){this.sendKeyEvent(w.keys.stop)}}class N extends w{get keyCodeMap(){return{38:w.keys.up,40:w.keys.down,37:w.keys.left,39:w.keys.right,13:w.keys.select,415:w.keys.play,19:w.keys.pause,413:w.keys.stop,417:w.keys.ffw,412:w.keys.rw,461:w.keys.back,1e3:w.keys.exit}}}class M{init(){this.player=void 0}setPlayer(e){this.player=e}getPlayer(){return this.player}getTracks(e){return[]}getEnabledTracks(e){return[]}enableTracks(e=[]){}disableTracks(e){}}class O{static getInstance(e,t){}}class x extends M{constructor(){super(),this.init()}init(){this.subtitleInstance=void 0,this.playerType=void 0,this.subtitleType=void 0,this.videoPlayer=void 0}setPlayerWithType(e,t){e?t?(this.playerType=e,this.playerType==s?this.videoPlayer=t.bitmovinPlayer:this.playerType==o?this.videoPlayer=t.playerElement:this.playerType==a?this.videoPlayer=t.playerInstance:this.playerType==d?this.videoPlayer=t.shakaPlayer:this.videoPlayer=t,this._setSubtitleInstance()):VizbeeTV.logger.warn("VirtualSubtitle::setPlayer - invalid parameter 'videoPlayer'"):VizbeeTV.logger.warn("VirtualSubtitle::setPlayer - invalid parameter 'playerType'")}getPlayer(){return this.videoPlayer}setSubtitleType(e){this.subtitleType=e,this._setSubtitleInstance()}_setSubtitleInstance(){this.playerType&&this.videoPlayer&&this.subtitleType&&(this.subtitleInstance=O.getInstance(this.playerType,this.subtitleType),this.subtitleInstance&&(this.subtitleInstance.init(),this.subtitleInstance.setPlayer(this.videoPlayer)))}isReady(){return!!this.subtitleInstance}getTracks(e){return VizbeeTV.logger.verbose("VirtualSubtitle::getTracks - trackType = ",e),this.subtitleInstance?this.subtitleInstance.getTracks(e):(VizbeeTV.logger.verbose("VirtualSubtitle::getTracks - sending empty data as there is no valid subtitle instance"),[])}getEnabledTracks(e){return VizbeeTV.logger.verbose("VirtualSubtitle::getTracks - trackType = ",e),this.subtitleInstance?this.subtitleInstance.getEnabledTracks(e):(VizbeeTV.logger.verbose("VirtualSubtitle::getEnabledTracks - sending empty data as there is no valid subtitle instance"),[])}enableTracks(e=[]){this.subtitleInstance&&this.subtitleInstance.enableTracks(e)}disableTracks(e){this.subtitleInstance&&this.subtitleInstance.disableTracks(e)}}const L={en:"English","en-US":"English (United States)","en-GB":"English (United Kingdom)","en-CA":"English (Canada)","en-AU":"English (Australia)",es:"Spanish","es-ES":"Spanish (Spain)","es-MX":"Spanish (Mexico)",fr:"French","fr-FR":"French (France)","fr-CA":"French (Canada)","fr-BE":"French (Belgium)",de:"German","de-DE":"German (Germany)","de-AT":"German (Austria)","de-CH":"German (Switzerland)",it:"Italian","it-IT":"Italian (Italy)",pt:"Portuguese","pt-PT":"Portuguese (Portugal)","pt-BR":"Portuguese (Brazil)",ru:"Russian","ru-RU":"Russian (Russia)",zh:"Chinese","zh-CN":"Chinese (Simplified)","zh-TW":"Chinese (Traditional)",ja:"Japanese",ko:"Korean",ar:"Arabic","ar-SA":"Arabic (Saudi Arabia)","ar-EG":"Arabic (Egypt)",hi:"Hindi",bn:"Bengali",pa:"Punjabi",mr:"Marathi",te:"Telugu",tr:"Turkish",vi:"Vietnamese",th:"Thai",id:"Indonesian",ms:"Malay",tl:"Tagalog",sw:"Swahili",fi:"Finnish",sv:"Swedish",no:"Norwegian",da:"Danish",pl:"Polish",hu:"Hungarian",cs:"Czech",sk:"Slovak",el:"Greek",ro:"Romanian",bg:"Bulgarian",sr:"Serbian",hr:"Croatian",uk:"Ukrainian",he:"Hebrew",ur:"Urdu",fa:"Persian",gu:"Gujarati",kn:"Kannada",ml:"Malayalam",ta:"Tamil",si:"Sinhalese",cy:"Welsh",sq:"Albanian",mk:"Macedonian",bs:"Bosnian",et:"Estonian",lv:"Latvian",lt:"Lithuanian",ka:"Georgian",am:"Amharic",yo:"Yoruba",ig:"Igbo",zu:"Zulu",xh:"Xhosa",ne:"Nepali",ms:"Malay","hi-IN":"Hindi (India)","bn-IN":"Bengali (India)","pa-IN":"Punjabi (India)"};class z{init(){this.player=void 0,this._reset()}setPlayer(e){this.player=e}getPlayer(){return this.player}getTracks(e){return[]}getEnabledTracks(e){return[]}setActiveTrack(e){}_setTrackIdStringToNumberMap(e){if(!this.trackIdStringToNumberMap[e]){let t=parseInt(e);T.isNaN(t)&&(t=Object.keys(this.trackIdStringToNumberMap).length+1),this.trackIdStringToNumberMap[e]=t,VizbeeTV.logger.verbose("BaseAudio::_setTrackIdStringToNumberMap - updated trackIdStringToNumberMap = ",this.trackIdStringToNumberMap)}}_setTrackLanguageCodeToNameMap(e){!e&&this.trackLanguageCodeToNameMap[e]||(this.trackLanguageCodeToNameMap[e]=L[e]||e,VizbeeTV.logger.verbose("BaseAudio::_setTrackLanguageCodeToNameMap - updated _setTrackLanguageCodeToNameMap = ",this.trackLanguageCodeToNameMap))}_reset(){this.trackIdStringToNumberMap={},this.trackLanguageCodeToNameMap={}}}class R{static getInstance(e){}}class K extends z{constructor(){super(),this.init()}init(){this.audioInstance=void 0,this.playerType=void 0,this.videoPlayer=void 0}setPlayerWithType(e,t){VizbeeTV.logger.debug("VirtualAudio::setPlayerWithType - playerType = ",e,", playerInstance = ",t),e?t?(this.playerType=e,this.playerType==s?this.videoPlayer=t.bitmovinPlayer:this.playerType==o?this.videoPlayer=t.playerElement:this.playerType==d?this.videoPlayer=t.shakaPlayer:this.videoPlayer=t,this._setAudioInstance()):VizbeeTV.logger.warn("VirtualAudio::setPlayerWithType - invalid parameter 'videoPlayer'"):VizbeeTV.logger.warn("VirtualAudio::setPlayerWithType - invalid parameter 'playerType'")}getPlayer(){return this.videoPlayer}_setAudioInstance(){this.playerType&&this.videoPlayer&&(VizbeeTV.logger.debug("VirtualAudio::_setAudioInstance - playerType = ",this.playerType),VizbeeTV.logger.debug("VirtualAudio::_setAudioInstance - videoPlayer = ",this.videoPlayer),this.audioInstance=R.getInstance(this.playerType),this.audioInstance&&(VizbeeTV.logger.debug("VirtualAudio::_setAudioInstance - setting audio instance"),this.audioInstance.init(),this.audioInstance.setPlayer(this.videoPlayer)))}isReady(){return!!this.audioInstance}getTracks(e){return VizbeeTV.logger.verbose("VirtualAudio::getTracks - trackType = ",e),this.audioInstance?this.audioInstance.getTracks(e):(VizbeeTV.logger.verbose("VirtualAudio::getTracks - sending empty data as there is no valid audio instance"),[])}getEnabledTracks(e){return VizbeeTV.logger.verbose("VirtualAudio::getEnabledTracks - trackType = ",e),this.audioInstance?this.audioInstance.getEnabledTracks(e):(VizbeeTV.logger.verbose("VirtualAudio::getEnabledTracks - sending empty data as there is no valid audio instance"),[])}setActiveTrack(e){this.audioInstance&&this.audioInstance.setActiveTrack(e)}}class U{constructor(){this.adPodStartedTimeInMs=0,this.adPodEndedTimeInMs=0,this.loadReceivedByAppTimeInMs=0,this.loadReceivedByPlayerTimeInMs=0,this.metadataLoadedTimeInMs=0,this.playerReadyToPlayTimeInMs=0,this.playbackStartedTimeInMs=0}toJSON(){return{adPodStartedTimeInMs:this._adPodStartedTimeInMs,adPodEndedTimeInMs:this._adPodEndedTimeInMs,loadReceivedByAppTimeInMs:this._loadReceivedByAppTimeInMs,loadReceivedByPlayerTimeInMs:this._loadReceivedByPlayerTimeInMs,metadataLoadedTimeInMs:this._metadataLoadedTimeInMs,playerReadyToPlayTimeInMs:this._playerReadyToPlayTimeInMs,playbackStartedTimeInMs:this._playbackStartedTimeInMs}}fromJSON(e){e&&(e.adPodStartedTimeInMs&&(this.adPodStartedTimeInMs=e.adPodStartedTimeInMs),e.adPodEndedTimeInMs&&(this.adPodEndedTimeInMs=e.adPodEndedTimeInMs),e.loadReceivedByAppTimeInMs&&(this.loadReceivedByAppTimeInMs=e.loadReceivedByAppTimeInMs),e.loadReceivedByPlayerTimeInMs&&(this.loadReceivedByPlayerTimeInMs=e.loadReceivedByPlayerTimeInMs),e.metadataLoadedTimeInMs&&(this.metadataLoadedTimeInMs=e.metadataLoadedTimeInMs),e.playerReadyToPlayTimeInMs&&(this.playerReadyToPlayTimeInMs=e.playerReadyToPlayTimeInMs),e.playbackStartedTimeInMs&&(this.playbackStartedTimeInMs=e.playbackStartedTimeInMs))}reset(){this.adPodStartedTimeInMs=0,this.adPodEndedTimeInMs=0,this.loadReceivedByAppTimeInMs=0,this.loadReceivedByPlayerTimeInMs=0,this.metadataLoadedTimeInMs=0,this.playerReadyToPlayTimeInMs=0,this.playbackStartedTimeInMs=0}set adPodStartedTimeInMs(e){this._adPodStartedTimeInMs=e}get adPodStartedTimeInMs(){return this._adPodStartedTimeInMs}set adPodEndedTimeInMs(e){this._adPodEndedTimeInMs=e}get adPodEndedTimeInMs(){return this._adPodEndedTimeInMs}set loadReceivedByAppTimeInMs(e){this._loadReceivedByAppTimeInMs=e}get loadReceivedByAppTimeInMs(){return this._loadReceivedByAppTimeInMs}set loadReceivedByPlayerTimeInMs(e){this._loadReceivedByPlayerTimeInMs=e}get loadReceivedByPlayerTimeInMs(){return this._loadReceivedByPlayerTimeInMs}set metadataLoadedTimeInMs(e){this._metadataLoadedTimeInMs=e}get metadataLoadedTimeInMs(){return this._metadataLoadedTimeInMs}set playerReadyToPlayTimeInMs(e){this._playerReadyToPlayTimeInMs=e}get playerReadyToPlayTimeInMs(){return this._playerReadyToPlayTimeInMs}set playbackStartedTimeInMs(e){this._playbackStartedTimeInMs=e}get playbackStartedTimeInMs(){return this._playbackStartedTimeInMs}}class B{constructor(e){if(VizbeeTV.logger.debug("BasePlayer::constructor() platform =",e),"BasePlayer"===this.constructor.name)throw new TypeError("BasePlayer::constructor() -- Abstract class.");if(!(e&&e instanceof l))throw new Error("BasePlayer::constructor() -- platform cannot be empty or invalid.");this.playerState={IDLE:"idle",PREPARING:"preparing",LOADING:"loading",STARTED:"started",PLAYING:"playing",PAUSED:"paused",BUFFERING:"buffering",INTERRUPTED:"interrupted",ENDED:"ended",ERROR:"error"},this.currentState=this.playerState.IDLE,this.platform=e,this.platformConfig=e.config,this.videoInfo={},this.hlsxchange=!0,this.currentSrc="",this.startVideoTimestampInMS=0,this.onStartedTimestampInMS=0,this.resetListeners(),this.subtitlesDelegate=new x,this.audioDelegate=new K,this.streamQualityInfo=new U}reconstruct(e){}set enableHLSExchange(e){this.hlsxchange=e}set onLoading(e){"function"==typeof e&&this._loadingListeners.push(e)}dispatchOnLoading(){this.currentState=this.playerState.LOADING;for(var e=this._loadingListeners.length-1;e>-1;e--)if(this._loadingListeners[e]())return}set onStarted(e){"function"==typeof e&&this._startedListeners.push(e)}dispatchOnStarted(){this.onStartedTimestampInMS=(new Date).getTime(),this.currentState=this.playerState.STARTED;for(var e=this._startedListeners.length-1;e>-1;e--)if(this._startedListeners[e]())return}set onPlaying(e){"function"==typeof e&&this._playingListeners.push(e)}dispatchOnPlaying(){this.currentState=this.playerState.PLAYING;for(var e=this._playingListeners.length-1;e>-1;e--)if(this._playingListeners[e]())return}set onPaused(e){"function"==typeof e&&this._pausedListeners.push(e)}dispatchOnPaused(){this.currentState=this.playerState.PAUSED;for(var e=this._pausedListeners.length-1;e>-1;e--)if(this._pausedListeners[e]())return}set onTimeUpdate(e){"function"==typeof e&&this._timeupdateListeners.push(e)}dispatchOnTimeUpdate(e){this.currentState=this.playerState.PLAYING;for(var t=this._timeupdateListeners.length-1;t>-1;t--)if(this._timeupdateListeners[t](e))return}set onBuffering(e){"function"==typeof e&&this._bufferingListeners.push(e)}dispatchOnBuffering(e){this.currentState=this.playerState.BUFFERING;for(var t=this._bufferingListeners.length-1;t>-1;t--)if(this._bufferingListeners[t](e))return}set onBufferingComplete(e){"function"==typeof e&&this._bufferingCompleteListeners.push(e)}dispatchOnBufferingComplete(e){for(var t=this._bufferingCompleteListeners.length-1;t>-1;t--)if(this._bufferingCompleteListeners[t](e))return}set onEnded(e){"function"==typeof e&&this._endedListeners.push(e)}dispatchOnEnded(){VizbeeTV.logger.info(this.constructor.name+"::dispatchOnEnded ["+this.currentState+"] sending ended"),this.currentState=this.playerState.ENDED;for(var e=this._endedListeners.length-1;e>-1;e--)if(this._endedListeners[e]())return;this.currentState=this.playerState.IDLE}set onInterrupted(e){"function"==typeof e&&this._interruptedListeners.push(e)}dispatchOnInterrupted(e){if(!this._canBeInterrupted())return VizbeeTV.logger.warn(this.constructor.name+"::dispatchOnInterrupted ["+this.currentState+"] tried to send interrupted in wrong state ",e),!1;VizbeeTV.logger.info(this.constructor.name+"::dispatchOnInterrupted ["+this.currentState+"] sending interrupted ",e),this.currentState=this.playerState.INTERRUPTED;for(var t=this._interruptedListeners.length-1;t>-1;t--)if(this._interruptedListeners[t](e))return;return this.currentState=this.playerState.IDLE,!0}_canBeInterrupted(){return this.currentState==this.playerState.STARTED||this.currentState==this.playerState.PLAYING||this.currentState==this.playerState.PAUSED||this.currentState==this.playerState.BUFFERING}set onError(e){"function"==typeof e&&this._errorListeners.push(e)}dispatchOnError(e){if(!this._canBeErrored())return VizbeeTV.logger.warn(this.constructor.name+"::dispatchOnError ["+this.currentState+"] tried to send error in wrong state ",e),!1;VizbeeTV.logger.info(this.constructor.name+"::dispatchOnError ["+this.currentState+"] sending error ",e),this.currentState=this.playerState.ERROR;for(var t=this._errorListeners.length-1;t>-1;t--)if(this._errorListeners[t](e))return;return this.currentState=this.playerState.IDLE,!0}_canBeErrored(){return this.currentState!=this.playerState.IDLE}set onEvent(e){"function"==typeof e&&this._eventListeners.push(e)}dispatchOnEvent(e){for(var t=this._eventListeners.length-1;t>-1;t--)if(this._eventListeners[t](e))return}resetListeners(){this._startedListeners=[],this._loadingListeners=[],this._playingListeners=[],this._pausedListeners=[],this._timeupdateListeners=[],this._bufferingListeners=[],this._bufferingCompleteListeners=[],this._endedListeners=[],this._interruptedListeners=[],this._errorListeners=[],this._eventListeners=[]}start(e){VizbeeTV.logger.debug(this.constructor.name+"::Start() BEGINNING - CURRENT_PLAYER_STATE -- ",this.currentState),this.videoInfo=e,this.currentState=this.playerState.PREPARING,this.startVideoTimestampInMS=(new Date).getTime(),this.subtitlesDelegate.init();let t=this.getPlayerType();this.subtitlesDelegate.setPlayerWithType(t,this);let i=this.getSubtitleTypeFromVideoInfo(e);this.subtitlesDelegate.setSubtitleType(i),this.audioDelegate.init(),this.audioDelegate.setPlayerWithType(t,this),VizbeeTV.logger.debug(this.constructor.name+"::Start() ENDING - CURRENT_PLAYER_STATE -- ",this.currentState)}play(){throw new TypeError(this.constructor.name+"::play() - Abstract method.")}pause(){throw new TypeError(this.constructor.name+"::pause() - Abstract method.")}togglePlayPause(){throw new TypeError(this.constructor.name+"::togglePlayPause() - Abstract method.")}seek(e){throw new TypeError(this.constructor.name+"::seek() - Abstract method.")}stop(e){throw new TypeError(this.constructor.name+"::stop() - Abstract method.")}currentTime(){throw new TypeError(this.constructor.name+"::currentTime() - Abstract method.")}getDuration(){throw new TypeError(this.constructor.name+"::getDuration() - Abstract method.")}getStartTime(){return this.startVideoTimestampInMS>0&&this.onStartedTimestampInMS>this.startVideoTimestampInMS?this.onStartedTimestampInMS-this.startVideoTimestampInMS:0}getBufferLevel(){return{current:0,target:0}}getAudioBufferLevel(){return{current:0,target:0,didDetectSeparateAudio:!1}}getCurrentState(){return this.currentState}getName(){return this.constructor.name}getPlayerType(){let e,t=this.getName().toLowerCase();return-1!=t.indexOf("bitmovin")?e=s:-1!=t.indexOf("videojs")?e=o:-1!=t.indexOf("theo")?e=a:-1!=t.indexOf("shaka")?e=d:-1!=t.indexOf("avplayer")&&(e="avplayer"),e}getCurrentVersion(){return""}getHlsxchangeUrl(){return this.hlsxchange&&(this.videoInfo.src.lastIndexOf(".m3u8")>=0||this.videoInfo.src.lastIndexOf("m3u")>=0)?D.xchangeHLSUrl(this.videoInfo.src,this.videoInfo.appID,this.platform.cloudPlatformName,this.videoInfo.minBitrate,this.videoInfo.maxBitrate,1):this.videoInfo.src}getAppVideoStartErrorInfo(e,t){let i,n;if(this.videoInfo&&this.videoInfo.videourl&&-1!=this.videoInfo.videourl.indexOf("start_video_failure")){let e=D.getUrlVars(this.videoInfo.videourl);i=e.errorCode,n=e.errorReason}return i&&n?{errorCode:i,errorReason:n}:{errorCode:e,errorReason:t}}buildErrorEvent(e,t,i){return{player:this.constructor.name,code:e,reason:t,data:i}}doAction(e){}reset(){this.resetListeners()}destroy(){this.resetListeners()}getTracks(e){return e==n?this.subtitlesDelegate&&this.subtitlesDelegate.isReady()?this.subtitlesDelegate.getTracks(e):[]:e==r&&this.audioDelegate&&this.audioDelegate.isReady()?this.audioDelegate.getTracks(e):[]}getEnabledTracks(e){return e==n?this.subtitlesDelegate&&this.subtitlesDelegate.isReady()?this.subtitlesDelegate.getEnabledTracks(e):[]:e==r&&this.audioDelegate&&this.audioDelegate.isReady()?this.audioDelegate.getEnabledTracks(e):[]}getSubtitleTypeFromVideoInfo(e){return"any"}enableTracks(e){this.subtitlesDelegate.isReady()&&this.subtitlesDelegate.enableTracks(e)}disableTracks(e){this.subtitlesDelegate.isReady()&&this.subtitlesDelegate.disableTracks(e)}changeAudioTrack(e){this.audioDelegate.isReady()?this.audioDelegate.setActiveTrack(e):VizbeeTV.logger.warn(this.constructor.name+"::changeAudioTrack - audio delegate is not ready")}getStreamQualityInfo(){return this.streamQualityInfo&&this.streamQualityInfo.toJSON()}setStreamQualityInfo(e){this.streamQualityInfo&&this.streamQualityInfo.fromJSON(e)}resetStreamQualityInfo(){this.streamQualityInfo&&this.streamQualityInfo.reset()}setTracks(e){}getCurrentTrack(){var e;return this.videoInfo.tracks&&this.videoInfo.tracks.length>0&&isFinite(this.videoInfo.activeTrackId)&&(e=this.videoInfo.tracks.find(e=>this.videoInfo.activeTrackId==e.trackId)),e}}class F extends B{constructor(e){super(e),this._positionMs=-1,this._durationMs=-1}setPositionMs(e){this._positionMs="number"==typeof e&&e>=0?e:-1}setDurationMs(e){this._durationMs="number"==typeof e&&e>=0?e:-1}currentTime(){return this._positionMs>=0?this._positionMs/1e3:0}getDuration(){return this._durationMs>=0?this._durationMs/1e3:0}getStartTime(){return 0}dispatchOnTimeUpdate(e){for(var t=this._timeupdateListeners.length-1;t>-1;t--)if(this._timeupdateListeners[t](e))return}_canBeInterrupted(){return!0}_canBeErrored(){return!0}start(e){this.videoInfo=e||{},this.currentState=this.playerState.PREPARING}play(){}pause(){}togglePlayPause(){}seek(){}stop(){}setTracks(){}getTracks(){return[]}getEnabledTracks(){return[]}enableTracks(){}disableTracks(){}changeAudioTrack(){}wrapAVPlayerListener(e){return e}getName(){return this.platformConfig&&this.platformConfig.playerType||"VirtualPlayer"}getCurrentVersion(){return""}destroy(){super.destroy(),this._positionMs=-1,this._durationMs=-1}}var G=null,H=null,W=null,j=null,q=null;class Y extends B{extend(){throw new TypeError("BasePlayerExtensible::extend() - Abstract method.")}beforeStart(){throw new TypeError("BasePlayerExtensible::beforeStart() - Abstract method.")}}class J extends Y{constructor(e,t){if(super(e),!t)throw ReferenceError("LGDynamicPlayerSelector::constructor | platformPlayers is not passed.");this.nativePlayerClass=t.nativePlayer,this.htmlPlayerClass=t.htmlPlayer,this.currentPlayer=void 0,this.nativePlayer=void 0,this.htmlPlayer=void 0;let i=e.config.vtvPlayerListConfig||[{type:"native"}];i.forEach(e=>{this._createPlayer(e)}),this._selectPlayer(i[0])}reconstruct(e){this.platform.config=e,e.standalone&&this._destroyAllPlayers();let t=!e.vtvPlayerListConfig||Array.isArray(e.vtvPlayerListConfig)&&0===e.vtvPlayerListConfig.length?[{type:"native"}]:e.vtvPlayerListConfig;t.forEach(e=>{this._createPlayer(e)}),this._selectPlayer(t[0])}_destroyAllPlayers(){this.nativePlayer&&(this.nativePlayer.destroy(),this.nativePlayer=void 0),this.htmlPlayer&&(this.htmlPlayer.destroy(),this.htmlPlayer=void 0),this.currentPlayer=void 0}_createPlayer(e){"html"===(e&&e.type)?void 0===this.htmlPlayer&&(this.htmlPlayer=new this.htmlPlayerClass(this.platform)):void 0===this.nativePlayer&&(this.nativePlayer=new this.nativePlayerClass(this.platform))}_selectPlayer(e){e&&e.type?"html"===e.type?this._preparePlayer(this.htmlPlayer):this._preparePlayer(this.nativePlayer):void 0===this.currentPlayer&&this._preparePlayer(this.nativePlayer)}_preparePlayer(e){e&&(this.currentPlayer&&this.currentPlayer.constructor.name===e.constructor.name||(this.currentPlayer&&this.currentPlayer.constructor.name!==e.constructor.name&&this._removePlayerListeners(this.currentPlayer),this.currentPlayer=e,this._addPlayerListeners(this.currentPlayer)))}beforeStart(e){super.start(e)}start(e){this.beforeStart(e),e.vtvPlayerConfig&&(this._createPlayer(e.vtvPlayerConfig),this._selectPlayer(e.vtvPlayerConfig)),this.currentPlayer.enableHLSExchange=e.useHLSExchange,this.currentPlayer.start(e)}play(){this.currentPlayer&&this.currentPlayer.play()}pause(){this.currentPlayer&&this.currentPlayer.pause()}togglePlayPause(){this.currentPlayer&&this.currentPlayer.togglePlayPause()}stop(e){this.currentPlayer&&this.currentPlayer.stop(e)}seek(e){this.currentPlayer&&this.currentPlayer.seek(e)}currentTime(){return this.currentPlayer?this.currentPlayer.currentTime():-1}getDuration(){return this.currentPlayer?this.currentPlayer.getDuration():-1}getStartTime(){return this.currentPlayer?this.currentPlayer.getStartTime():-1}getCurrentState(){return this.currentPlayer?this.currentPlayer.getCurrentState():"IDLE"}getBufferLevel(){return this.currentPlayer?this.currentPlayer.getBufferLevel():{current:0,target:0}}getAudioBufferLevel(){return this.currentPlayer?this.currentPlayer.getAudioBufferLevel():{current:0,target:0,didDetectSeparateAudio:!1}}getName(){return this.currentPlayer.getName()}getCurrentVersion(){return this.currentPlayer.getCurrentVersion()}doAction(e){return this.currentPlayer.doAction(e)}wrapAVPlayerListener(e){return this.currentPlayer.wrapAVPlayerListener(e)}setTracks(e){if(this.currentPlayer)return this.currentPlayer.setTracks(e)}getTracks(e){return this.currentPlayer?this.currentPlayer.getTracks(e):[]}getEnabledTracks(e){return this.currentPlayer?this.currentPlayer.getEnabledTracks(e):[]}enableTracks(e){this.currentPlayer&&this.currentPlayer.enableTracks(e)}disableTracks(e){this.currentPlayer&&this.currentPlayer.disableTracks(e)}changeAudioTrack(e){this.currentPlayer&&this.currentPlayer.changeAudioTrack(e)}getStreamQualityInfo(){return this.currentPlayer?this.currentPlayer.getStreamQualityInfo():{}}setStreamQualityInfo(e){this.currentPlayer&&this.currentPlayer.setStreamQualityInfo(e)}resetStreamQualityInfo(){this.currentPlayer&&this.currentPlayer.resetStreamQualityInfo()}destroy(){super.destroy(),this._destroyAllPlayers()}_addPlayerListeners(e){e.onLoading=e=>{this.dispatchOnLoading.call(this,e)},e.onStarted=e=>{this.dispatchOnStarted.call(this,e)},e.onPlaying=e=>{this.dispatchOnPlaying.call(this,e)},e.onPaused=e=>{this.dispatchOnPaused.call(this,e)},e.onBuffering=e=>{this.dispatchOnBuffering.call(this,e)},e.onBufferingComplete=e=>{this.dispatchOnBufferingComplete.call(this,e)},e.onTimeUpdate=e=>{this.dispatchOnTimeUpdate.call(this,e)},e.onInterrupted=e=>{this.dispatchOnInterrupted.call(this,e)},e.onEnded=e=>{this.dispatchOnEnded.call(this,e)},e.onError=e=>{this.dispatchOnError.call(this,e)},e.onEvent=e=>{this.dispatchOnEvent.call(this,e)}}_removePlayerListeners(e){e.resetListeners()}}class ${constructor(){if("BaseDeviceID"===this.constructor.name)throw new TypeError("BaseDeviceID::constructor() - Abstract class.");this.deviceIdAlgorithm="VTV_DEFAULT",this.deviceIdKey="deviceid"}uniqueDeviceID(e,t){VizbeeTV.logger.error("BaseDeviceID::uniqueDeviceID - subclass did not override; no deviceId available"),t()}get algorithm(){return this.deviceIdAlgorithm}}class Q extends ${constructor(){super(),this.deviceIdAlgorithm="VTV_URL_PARAMS",this.storageDeviceIdKey="VTV_"+this.deviceIdKey}uniqueDeviceID(e,t){var i=(D.getUrlVars()||{})[this.deviceIdKey];if(i)D.docCookies.setItem(this.storageDeviceIdKey,i,1/0,"/");else{var n=D.docCookies.getItem(this.storageDeviceIdKey);if(!n)return VizbeeTV.logger.error("URLParamsDeviceID::uniqueDeviceID - didn't find deviceID in URL or storage"),void t();i=n}e(i)}}class Z{constructor(){}isLaunchedbyVizbee(){throw new TypeError("BaseLaunchParams::isLaunchedbyVizbee() - Abstract method. This method must be implemented by derived classes.")}getLaunchParams(e){}setLaunchParams(e){}waitUntilReady(){return this._readyPromise||Promise.resolve()}}class X extends Z{constructor(){super()}isLaunchedbyVizbee(){let e=this.getLaunchParams();return e?(VizbeeTV.logger.debug("URLLaunchParams::isLaunchedbyVizbee() - params present",e),"y"==e.vzb):(VizbeeTV.logger.debug("URLLaunchParams::isLaunchedbyVizbee() - params not present"),!1)}getLaunchParams(){let e,t={};if(e=window.location.href,!this.isValidUrl(e))return;let i=!1,n=e.indexOf("?");if(n>=0){let r=e.slice(n+1).split("&");for(let e=0;e<r.length;e++){let n,s;n=r[e].split("="),2==n.length&&n[0].length&&n[1].length&&(i=!0,s=n[0],t[s]=n[1])}}return i?t:void 0}isValidUrl(e){return/(http|https):\/\//.test(e)}}class ee{constructor(){var e,t,i,n,r;this._uaParser=(e=navigator.userAgent,i={name:"",version:""},n={name:"",version:""},r={name:"",version:""},(t=/Web0S(?:\.TV)?(?:[;\s/]*([\d.]+))?/i.exec(e))?(i.name="webOS",i.version=t[1]||""):(t=/Windows\s*(?:NT\s*)?([\d.]+)?/i.exec(e))?(i.name="Windows",i.version=t[1]||""):(t=/Mac OS X\s*([\d_.]+)?/i.exec(e))?(i.name="Mac OS",i.version=(t[1]||"").replace(/_/g,".")):(t=/CrOS[\s/]*([\w.]+)?/i.exec(e))?(i.name="Chromium OS",i.version=t[1]||""):(t=/Android\s*([\d.]+)?/i.exec(e))?(i.name="Android",i.version=t[1]||""):(t=/(?:iPhone|iPad).*OS\s*([\d_]+)/i.exec(e))?(i.name="iOS",i.version=(t[1]||"").replace(/_/g,".")):(t=/Linux/i.exec(e))&&(i.name="Linux"),(t=/(?:Edg|EdgA|EdgIOS)\/([\d.]+)/i.exec(e))?(n.name="Edge",n.version=t[1]):(t=/OPR\/([\d.]+)/i.exec(e))?(n.name="Opera",n.version=t[1]):(t=/Firefox\/([\d.]+)/i.exec(e))?(n.name="Firefox",n.version=t[1]):(t=/Chrome\/([\d.]+)/i.exec(e))?(n.name="Chrome",n.version=t[1]):(t=/Safari\/([\d.]+)/i.exec(e))&&/Version\/([\d.]+)/.test(e)&&(n.name="Safari",n.version=/Version\/([\d.]+)/.exec(e)[1]),(t=/AppleWebKit\/([\d.]+)/i.exec(e))?(r.name="WebKit",r.version=t[1]):(t=/Gecko\/([\d.]+)/i.exec(e))?(r.name="Gecko",r.version=t[1]):(t=/Trident\/([\d.]+)/i.exec(e))&&(r.name="Trident",r.version=t[1]),{os:i,browser:n,engine:r})}get deviceId(){return t}get make(){return t}get model(){return t}get modelYear(){return t}get serialNumber(){return t}get friendlyName(){return t}get macAddress(){return t}get userAgent(){return navigator.userAgent}get os(){return{name:this._uaParser.os.name,sdkVersion:this._uaParser.os.version,version:this._uaParser.os.version}}get browser(){return{name:this._uaParser.browser.name,version:this._uaParser.browser.version,engine_name:this._uaParser.engine.name,engine_version:this._uaParser.engine.version}}get screen(){return{height:document.body.clientHeight,width:document.body.clientWidth}}}const te={6:"webOS TV 6.0",7:"webOS TV 22",8:"webOS TV 23",9:"webOS TV 24"};class ie extends ee{constructor(){super(),this._deviceInfo={};try{setTimeout(()=>{window.webOS&&webOS.deviceInfo(e=>{e&&(setTimeout(()=>{},1e4),this._deviceInfo=T.extend({},this._deviceInfo,e))})},1e4)}catch(e){setTimeout(()=>{VizbeeTV.logger.warn("LGWebOSDeviceInfo::constructor - failed to fetch deviceId and modelName",e)},1e4)}}get deviceId(){return this._deviceInfo.id||t}get model(){return this._deviceInfo.modelName||t}get make(){return this._deviceInfo.manufacturer||t}get modelYear(){return t}get friendlyName(){return t}get macAddress(){return t}get os(){return{name:"WebOS",sdkVersion:this._deviceInfo.sdkVersion||t,version:te[(this._deviceInfo.sdkVersion||t).split(".")[0]]||t}}}class ne{constructor(){}get internalIP(){return t}get externalIP(){return t}get isWifiConnected(){return!0}get connectionType(){return t}get bssid(){return t}get ssid(){return t}}class re extends ne{constructor(){super()}}class se{constructor(){this.eventMap={}}addHandler(e,t){this.eventMap[e]||(this.eventMap[e]=[]),this.eventMap[e].push(t)}removeHandler(e,t){if(this.eventMap&&this.eventMap[e]){let i,n=this.eventMap[e];if(n&&n.length&&(i=n.reduce((e,i,n)=>this._isFunction(i)&&i==t?e=n:e,-1),i>-1))return n.splice(i,1),this.eventMap[e]=n,!0}return!1}emit(e,t){e&&(VizbeeTV.logger.i("BaseAppLifeCycleManager","emit","eventName=",e,"; eventData=",t),this.eventMap&&this.eventMap[e]&&this.eventMap[e].forEach(i=>{VizbeeTV.logger.i("BaseAppLifeCycleManager","emit","calling handler for event=",e),i.apply({},t)}))}reset(){this.eventMap={}}_isFunction(e){return"function"==typeof e||!1}}class oe extends se{constructor(){super(),this._didBackgroundOnce=!1,this._didEnd=!1}init(){document&&this._listen()}_listen(){let e;void 0!==document.hidden?e="visibilitychange":void 0!==document.webkitHidden&&(e="webkitvisibilitychange"),document.addEventListener(e,()=>{try{document.hidden?(VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_listen - application is in background"),this._emitOnBackground()):(VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_listen - application is in foreground"),this._emitOnForeground())}catch(e){VizbeeTV.logger.error("LGWebOSAppLifeCycleManager::_listen - error reading lifecycle events",e)}}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("pagehide",e=>{e&&e.persisted||this._emitOnEnd()}),window.addEventListener("beforeunload",()=>{this._emitOnEnd()}))}_emitOnEnd(){this._didEnd||(this._didEnd=!0,VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnEnd - application is exiting"),this.emit(i,[{isTeardown:!0}]))}_emitOnBackground(){this._didBackgroundOnce=!0,this.eventMap.onBackground.forEach(e=>{VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnBackground"),e.apply({})})}_emitOnForeground(){this._didBackgroundOnce&&this.eventMap.onForeground.forEach(e=>{VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnForeground"),e.apply({})})}}class ae extends l{constructor(e){super(e),this.deviceId=new Q,this.launchParams=new X,this._deviceInfo=new ie,this._networkInfo=new re,this.lgWebOSAppLifeCycleManager=new oe,this.lgWebOSAppLifeCycleManager.init()}createPlayer(){let e={};return navigator.userAgent.indexOf("webOS.TV-2014")>-1?(VizbeeTV.logger.d("LGWebOS","createPlayer","WebOS 2014 detected - using webOS player"),e.nativePlayer=F,e.htmlPlayer=F):(VizbeeTV.logger.d("LGWebOS","createPlayer","WebOS 2014 detected - using html player"),e={nativePlayer:F,htmlPlayer:F,bitmovinPlayer:H,modularBitmovinPlayer:H,videoJSPlayer:W,theoPlayer:j,shakaPlayer:q,topPlayer:G}),this.player=new J(this,e),this.player}createInputDevice(){let e=new N(this);return this.inputDevice=e,e}exit(){VizbeeTV.tv.player.stop(),super.exit(),"function"==typeof window.NetCastBack?window.NetCastBack():"function"==typeof window.NetCastExit?window.NetCastExit():window.close()}get defaultAppletAppId(){return"vzb0000001"}get cloudPlatformName(){return"lg_webos"}get launchParamsDeferral(){return this.launchParams}get deviceInfo(){return this._deviceInfo}get networkInfo(){return this._networkInfo}get appLifeCycleManager(){return this.lgWebOSAppLifeCycleManager}}class de extends ${constructor(){super(),this.deviceIdAlgorithm="VTV_INTERNAL_IP"}}class le extends de{constructor(){super()}uniqueDeviceID(e,t){let i,n;const r=()=>{if(void 0!==n&&(clearTimeout(n),n=void 0),i){try{i.close()}catch(e){}i=void 0}};try{const s=new Promise((e,t)=>{n=setTimeout(()=>{t(new Error("WebRTC IP detection timed out after 5 seconds"))},5e3)}),o=new Promise((e,t)=>{i=this._getInternalIPWithWebRTC(i=>{if(i&&i.length>0){for(var n="",r=0;r<i.length;r++)if(D.isValidIPv4Address(i[r])){n=i[r];break}if(!n)return void t(new Error("No valid IPv4 address found in WebRTC candidates"));e(n)}else t(new Error("No IP addresses found"))})});Promise.race([o,s]).then(t=>{r(),e(t)}).catch(e=>{r(),VizbeeTV.logger.error("IPWithWebRTCDeviceID::uniqueDeviceID - error fetching IPAddress:",e.message),t()})}catch(e){r(),VizbeeTV.logger.error("IPWithWebRTCDeviceID::uniqueDeviceID - error fetching network info",e),t()}}_getInternalIPWithWebRTC(e){var t=[],i=new(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection)({iceServers:[]});return i.createDataChannel(""),i.onicecandidate=function(n){if(n.candidate){var r=/^candidate:.+ (\S+) \d+ typ/.exec(n.candidate.candidate)[1];-1==t.indexOf(r)&&t.push(r)}else{try{i.close()}catch(e){}e(t)}},i.createOffer(function(e){i.setLocalDescription(e)},function(){}),i}}class ce extends Z{constructor(){super()}isLaunchedbyVizbee(){let e=this.getLaunchParams();return!(!e||void 0===e.vzb)}getLaunchParams(){return window.webOSDev?webOSDev.launchParams():void 0}}const ue={6:"webOS TV 6.0",7:"webOS TV 22",8:"webOS TV 23",9:"webOS TV 24"};class pe extends ee{constructor(){super(),this._deviceInfo={};try{window.webOS&&(webOS.service.request("luna://com.webos.service.sm",{method:"deviceid/getIDs",parameters:{idType:["LGUDID"]},onSuccess:e=>{e&&e.idList&&e.idList[0]&&(this._deviceInfo.id=e.idList[0].idValue,VizbeeTV.logger.debug("LGWebOSNativeDeviceInfo::constructor - got deviceId",this._deviceInfo.id))},onFailure:e=>{VizbeeTV.logger.warn('LGWebOSNativeDeviceInfo::constructor - "deviceid/getIDs" failed to fetch deviceId')}}),webOS.service.request("luna://com.webos.service.tv.systemproperty",{method:"getSystemInfo",parameters:{keys:["modelName","firmwareVersion","UHD","sdkVersion"]},onComplete:e=>{e.returnValue?this._deviceInfo=T.extend({},this._deviceInfo,e):VizbeeTV.logger.warn('LGWebOSNativeDeviceInfo::constructor - "getSystemInfo" failed to fetch deviceInfo')}}),webOS.deviceInfo(e=>{e&&(this._deviceInfo=T.extend({},this._deviceInfo,e))}))}catch(e){VizbeeTV.logger.warn('LGWebOSNativeDeviceInfo::constructor - "webOS.deviceInfo" failed to fetch deviceInfo')}}get deviceId(){return this._deviceInfo.id||t}get model(){return this._deviceInfo.modelName||t}get make(){return this._deviceInfo.manufacturer||t}get modelYear(){return t}get friendlyName(){return t}get macAddress(){return t}get os(){return{name:"WebOS",sdkVersion:this._deviceInfo.sdkVersion||t,version:ue[(this._deviceInfo.sdkVersion||t).split(".")[0]]||t}}}class he extends ne{constructor(){super(),this._networkInfo={},window.webOS&&window.webOS.service&&webOS.service.request("luna://com.webos.service.connectionmanager",{method:"getStatus",parameters:{},onSuccess:e=>{this._networkInfo=e},onFailure:e=>{}})}get connectionType(){let e=t;return"connected"===T.get(this._networkInfo,["wifi","state"])?e="WIFI":"connected"===T.get(this._networkInfo,["wired","state"])&&(e="WIRED"),e}get isWifiConnected(){return"connected"===T.get(this._networkInfo,["wifi","state"])}get internalIP(){return T.get(this._networkInfo,["wifi","ipAddress"],t)}get ssid(){return T.get(this._networkInfo,["wifi","ssid"],t)}}class ge extends l{constructor(e){super(e),this.deviceId=new le,this.launchParams=new ce,this._deviceInfo=new pe,this._networkInfo=new he,this.lgWebOSAppLifeCycleManager=new oe,this.lgWebOSAppLifeCycleManager.init()}createPlayer(){let e={};return navigator.userAgent.indexOf("webOS.TV-2014")>-1?(VizbeeTV.logger.debug("LGWebOSNative::Factory::createPlayer() - WebOS 2014 detected - using webOS player"),e.nativePlayer=F,e.htmlPlayer=F):(VizbeeTV.logger.debug("LGWebOSNative::Factory::createPlayer() > WebOS 2014 detected - using html player"),e={nativePlayer:F,htmlPlayer:F,bitmovinPlayer:H,modularBitmovinPlayer:H,videoJSPlayer:W,theoPlayer:j,shakaPlayer:q,topPlayer:G}),this.player=new J(this,e),this.player}createInputDevice(){let e=new N(this);return this.inputDevice=e,e}exit(){super.exit(),window.close()}get defaultAppletAppId(){return"vzb0000001"}get cloudPlatformName(){return"lg_webos"}get launchParamsDeferral(){return this.launchParams}get deviceInfo(){return this._deviceInfo}get networkInfo(){return this._networkInfo}get appLifeCycleManager(){return this.lgWebOSAppLifeCycleManager}}class fe extends l{constructor(e){super(e);const t=this._loadWebOSLibrary();let i=fe.getPlatformType().toLowerCase();this.__platform="lgwebosnative"==i?new ge(e):new ae(e),this.__platform.launchParamsDeferral&&(this.__platform.launchParamsDeferral._readyPromise=t)}get cloudPlatformName(){return this.__platform.cloudPlatformName}uniqueDeviceID(e,t){this.__platform.uniqueDeviceID(e,t)}set deviceIDAlgorithm(e){return this.__platform.deviceIDAlgorithm=e}get deviceIDAlgorithm(){return this.__platform.deviceIDAlgorithm}get platformModel(){return this.__platform.platformModel}get deviceInfo(){return this.__platform.deviceInfo}get platformVersion(){return this.__platform.platformVersion}get networkInfo(){return this.__platform.networkInfo}get adId(){return this.__platform.adId}get isAdTrackingDisabled(){return this.__platform.isAdTrackingDisabled}createInputDevice(){return this.__platform.createInputDevice()}get inputDevice(){return this.__platform.inputDevice}set screenSaverEnabled(e){e=e||!1,void 0!==this.__platform&&this.__platform.enableScreenSaver&&(VizbeeTV.logger.d("LGWebOSVirtualPlatform","creatInputDevice","screenSaverEnabled = "+e),this.__platform.enableScreenSaver(e))}get defaultAppletAppId(){return this.__platform.defaultAppletAppId}get launchParamsDeferral(){return this.__platform.launchParamsDeferral}get appLifeCycleManager(){return this.__platform.appLifeCycleManager}exit(){VizbeeTV.logger.d("LGWebOSVirtualPlatform","exit","exiting the application"),void 0!==this.__platform&&this.__platform.exit&&this.__platform.exit()}set isAppExiting(e){this.__platform.isAppExiting=e}get isAppExiting(){return this.__platform.isAppExiting}reset(){this.__platform.reset()}createPlayer(){return this.__platform.createPlayer()}get player(){return this.__platform.player}set player(e){e&&(this.__platform.player=e)}destroyPlayer(){this.__platform.destroyPlayer()}static getPlatformType(){return window.PalmServiceBridge?"LGWebOSNative":"LGWebOS"}set enableHLSExchange(e){this.__platform.enableHLSExchange=e}_loadWebOSLibrary(){var e=[];return window.webOS||e.push("https://sdk.claspws.tv/libs/webos/webOSTV_1.2.11.js"),window.webOSDev||e.push("https://sdk.claspws.tv/libs/webos/webOSTV_dev_1.2.12.js"),0===e.length?Promise.resolve():e.reduce((e,t)=>e.then(()=>new Promise((e,i)=>{var n=document.createElement("script");n.setAttribute("type","text/javascript"),n.onload=e,n.onerror=i,document.head.appendChild(n),n.setAttribute("src",t)})).catch(e=>{throw VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - FAILED to load library",e),e}),Promise.resolve()).then(()=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - SUCCESS to load library")}).catch(e=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - library load failed, proceeding without it",e)})}}class ve extends de{constructor(){super()}uniqueDeviceID(e,t){var i=this.deviceAPIID||"lg_netcast_device",n=document.getElementById(i);n&&n.net_isConnected?e(n.net_ipAddress):(VizbeeTV.logger.error("LGNetCastDeviceID::uniqueDeviceID - didn't find device API or device not connected"),t())}}class ye extends ee{constructor(){super()}}class me extends ne{constructor(){super()}}const be={lgwebos:fe,lgnetcast:class extends l{constructor(e){super(e),this.deviceId=new ve,this.deviceId.deviceAPIID=e.deviceAPIID,this.launchParams=new X,this._deviceInfo=new ye,this._networkInfo=new me}createPlayer(){VizbeeTV.logger.debug("LGNetCast::Factory::createPlayer() - creating LG HTML Player");let e={nativePlayer:F,htmlPlayer:F,bitmovinPlayer:H,modularBitmovinPlayer:H,videoJSPlayer:W,theoPlayer:j,shakaPlayer:q,topPlayer:G};return this.player=new J(this,e),this.player}createInputDevice(){let e=new N(this);return this.inputDevice=e,e}exit(){"function"==typeof window.NetCastBack?window.NetCastBack():"function"==typeof window.NetCastExit?window.NetCastExit():window.close()}get defaultAppletAppId(){return"vzb0000000"}get cloudPlatformName(){return"lg_netcast"}get launchParamsDeferral(){return this.launchParams}get deviceInfo(){return this._deviceInfo}get networkInfo(){return this._networkInfo}}};let Se,_e;class Ie extends l{constructor(e,t){if(super(t),e=e.toLowerCase(),!be[e])throw new TypeError("LGVirtualPlatform::constructor() - platform "+e+" does not exist.");this.__platform=new be[e](t),this.player,this.inputDevice}static getPlatformType(){if((window.navigator&&window.navigator.userAgent||"").toLowerCase().indexOf("webos.tv")>-1||window.PalmServiceBridge)return"LGWebOS"}static detectPlatformWhenReady(e){e(Ie.getPlatformType())}reset(){Se&&(Se.stop(),VizbeeTV.logger.debug("player reset",Se)),_e&&(_e.reset(),_e=void 0)}uniqueDeviceID(e,t){this.__platform.uniqueDeviceID(e,t)}set enableHLSExchange(e){Se.enableHLSExchange=e}set deviceIDAlgorithm(e){return this.__platform.deviceIDAlgorithm=e}get deviceIDAlgorithm(){return this.__platform.deviceIDAlgorithm}get player(){return void 0===Se&&(Se=this.__platform.createPlayer()),Se}set player(e){e&&(Se=e)}destroyPlayer(){Se.destroy().then(()=>{Se=void 0})}get inputDevice(){return void 0===_e&&(_e=this.__platform.createInputDevice()),_e}set screenSaverEnabled(e){e=e||!1,void 0!==this.__platform&&this.__platform.enableScreenSaver&&(VizbeeTV.logger.debug("LGVirtualPlatform::screenSaverEnabled = "+e),this.__platform.enableScreenSaver(e))}exit(){void 0!==this.__platform&&this.__platform.exit&&this.__platform.exit()}set isAppExiting(e){this.__platform.isAppExiting=e}get isAppExiting(){return this.__platform.isAppExiting}get defaultAppletAppId(){return this.__platform.defaultAppletAppId}get cloudPlatformName(){return this.__platform.cloudPlatformName}get platformModel(){return this.__platform.platformModel}get platformVersion(){return this.__platform.platformVersion}get adId(){return this.__platform.adId}get isAdTrackingDisabled(){return this.__platform.isAdTrackingDisabled}get appLifeCycleManager(){return this.__platform.appLifeCycleManager}get launchParamsDeferral(){return this.__platform.launchParamsDeferral}get deviceInfo(){return this.__platform.deviceInfo}get networkInfo(){return this.__platform.networkInfo}}class Te extends Ie{constructor(e,t){super(e,t),this.setUIStyleConfig("transparent","white","black")}extendPlayer(e,t){VizbeeTV.logger.debug("ExtendPlayer - ",this.player.constructor.name),this.player=new e(this.player,t)}unextendPlayer(){try{if(this.player.extendedPlayer){var e=this.player.extendedPlayer;this.player.reset(),this.player=e}}catch(e){VizbeeTV.logger.error("Error while unextending Player",e,this.player,this.player.extendedPlayer)}}wrapExtension(e,t){this.extendPlayer(e,t)}unwrapExtensionToBasePlayer(){for(;this.player.extendedPlayer;)this.unextendPlayer();this.player.reset()}unwrapExtensionToStandardPlayerControls(){for(;!(this.player instanceof StandardPlayerControls);)this.unextendPlayer()}setUIStyleConfig(e,t,i){this.config.primaryColor=e||this.config.primaryColor,this.config.secondaryColor=t||this.config.secondaryColor,this.config.tertiaryColor=i||this.config.tertiaryColor}}class Ee{constructor(){this.currentLevel=this.LEVEL.CRITICAL,this.enableLogging=!0,this.logPrefix=""}static enableRemoteLogging(e,t){window.console.log=window.console.info=window.console.error=window.console.warn=window.console.debug=function(){let i=new XMLHttpRequest;try{let n=Array.prototype.slice.call(arguments);n=D.convertObjectsToString(n);let r=[t];Array.prototype.push.apply(r,n);let s=encodeURIComponent(JSON.stringify({data:r.join(" ")}));i.open("GET",e+s,!0),i.send(null)}catch(e){}}}get LEVEL(){return{CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4,VERBOSE:5}}setLevel(e){this.currentLevel=e}setPrefix(e){this.logPrefix=e}enable(){this.enableLogging=!0}disable(){this.enableLogging=!1}c(){let e=this._getLogArguments.apply(this,arguments);e&&this.critical.apply(this,e)}critical(){if(this.shouldLog(this.LEVEL.CRITICAL)){var e=Array.prototype.slice.call(arguments);e=D.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [CRITICAL]:"];Array.prototype.push.apply(t,e),console.error.apply(console,t)}}e(){let e=this._getLogArguments.apply(this,arguments);e&&this.error.apply(this,e)}error(){if(this.shouldLog(this.LEVEL.ERROR)){var e=Array.prototype.slice.call(arguments);e=D.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [ERROR]:"];Array.prototype.push.apply(t,e),console.error.apply(console,t)}}w(){let e=this._getLogArguments.apply(this,arguments);e&&this.warn.apply(this,e)}warn(){if(this.shouldLog(this.LEVEL.WARN)){var e=Array.prototype.slice.call(arguments);e=D.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [WARN]:"];Array.prototype.push.apply(t,e),console.warn.apply(console,t)}}i(){let e=this._getLogArguments.apply(this,arguments);e&&this.info.apply(this,e)}info(){if(this.shouldLog(this.LEVEL.INFO)){var e=Array.prototype.slice.call(arguments);e=D.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [INFO]:"];Array.prototype.push.apply(t,e),console.info.apply(console,t)}}d(){let e=this._getLogArguments.apply(this,arguments);e&&this.debug.apply(this,e)}debug(){if(this.shouldLog(this.LEVEL.DEBUG)){var e=Array.prototype.slice.call(arguments);e=D.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [DEBUG]:"];Array.prototype.push.apply(t,e),console.log.apply(console,t)}}v(){let e=this._getLogArguments.apply(this,arguments);e&&this.verbose.apply(this,e)}verbose(){if(this.shouldLog(this.LEVEL.VERBOSE)){var e=Array.prototype.slice.call(arguments);e=D.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [VERBOSE]:"];Array.prototype.push.apply(t,e),console.log.apply(console,t)}}shouldLog(e){return!!this.enableLogging&&e<=this.currentLevel}_getLogArguments(){let e=Array.prototype.slice.call(arguments);if(e&&e.length>=2){let t=[this._getClassAndMethodNamePrefix(e[0],e[1])],i=Array.prototype.slice.call(arguments,2);return Array.prototype.push.apply(t,i),t}}_getClassAndMethodNamePrefix(e,t){return e&&t?D.padEnd(e+"::",40," ")+D.padEnd(t,30," ")+" - ":""}getCurrentTimeString(){return"["+(new Date).toISOString()+"]"}}class Ve extends Ee{constructor(){super()}critical(){try{super.critical(...arguments);let e=Array.prototype.slice.call(arguments);if(e.length>0){let t=e[e.length-1],i=window.Raven||window.Sentry;this._shouldLogException()&&i&&(T.isObject(t)||T.isString(t))&&i.captureException(t)}}catch(e){}}_shouldLogException(){return!0}}var Pe,Ae,Ce,De;function ke(){if(Ae)return Pe;Ae=1;var e,t={getItem:function(e){return e&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null},setItem:function(e,t,i,n,r,s){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e))return!1;var o="";if(i)switch(i.constructor){case Number:o=i===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+i;break;case String:o="; expires="+i;break;case Date:o="; expires="+i.toUTCString()}return document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+o+(r?"; domain="+r:"")+(n?"; path="+n:"")+(s?"; secure":""),!0},removeItem:function(e,t,i){return!!this.hasItem(e)&&(document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"+(i?"; domain="+i:"")+(t?"; path="+t:""),!0)},hasItem:function(e){return!!e&&new RegExp("(?:^|;\\s*)"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:function(){for(var e=document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:\=[^;]*)?;\s*/),t=e.length,i=0;i<t;i++)e[i]=decodeURIComponent(e[i]);return e},eraseCookieFromAllPaths:function(e){var t=location.pathname.split("/"),i=" path=";document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;";for(var n=0;n<t.length;n++)i+=("/"!=i.substr(-1)?"/":"")+t[n],document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;"+i+";"}},i=(e=function(){for(var e,t={},i=decodeURIComponent(window.location.href),n=i.slice(i.indexOf("?")+1).split("&"),r=0;r<n.length;r++)t[(e=n[r].split("="))[0]]=e[1];return t}()||{},{getQueryParamForKey:function(t){return e[t]||!1},getQueryParams:function(){return e}});return Pe={chain:function(e,t){return e?function(){e.call(this,arguments),t.call(this,arguments)}:t},xhr:function(e){return new Promise(function(t,i){var n=e.retries||2;!function r(){var s=new XMLHttpRequest;e.url=e.url.replace(/^http:\/\//i,"https://"),s.open(e.method||"GET",e.url,!0),Object.keys(e.headers||{}).forEach(function(t){s.setRequestHeader(t,e.headers[t])}),s.onreadystatechange=function(o){if(4===s.readyState)if(-1===[200,304].indexOf(s.status))VizbeeSDK.logger.error("xhr error",o),n>0?(n--,r()):i(new Error("Server responded with a status of "+s.status));else try{e.format=e.format||"json";var a=o.target;"json"===e.format?a=JSON.parse(a.response):"xml"===e.format&&(a=a.responseXML),VizbeeSDK.logger.debug("Util::xhr() -- response object --",a),t(a)}catch(o){n>0?(n--,r()):i("JSON parse error with Server response")}},e.timeout&&(s.timeout=e.timeout,s.ontimeout=function(t){n>0?(n--,r()):i(new Error("Server timeout "+e.timeout+"ms"))}),s.send(e.data)}()})},log:function(){var e=Array.prototype.slice.call(arguments);e.unshift("VIZBEE [LOG]"),console.log.apply(console,e)},docCookies:t,urlParser:i},Pe}window.VizbeeTV={logger:function(){const e=new Ve;return e.setPrefix("[VTVLIB]"),e}(),init:function(e,t,i){this.logger=new Ve,this.logger.setPrefix("[VTVLIB]"),this.Util=D,i?this.tv instanceof Te?this.tv.config=T.extend(this.tv.config,t):this.tv=new Te(e,t):this.tv instanceof Ie?this.tv.config=T.extend(this.tv.config,t):this.tv=new Ie(e,t)}};var we,Ne,Me,Oe,xe={getIpv6Address:function(e){D.xhr({url:"https://ip.claspws.tv",timeout:5e3,retries:3}).then(t=>{var i=t&&t.headers&&t.headers["x-vzb-client-ip"];i?(VizbeeSDK.logger.debug("Ipv6::getIpv6Address - ipv6Address=",i),e(i)):(VizbeeSDK.logger.warn("Ipv6::getIpv6Address - ipv6Address=empty"),e())}).catch(t=>{VizbeeSDK.logger.warn("Ipv6::getIpv6Address - failed",t),e()})}};function Le(){if(Ne)return we;function e(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function t(e){return"function"==typeof e}function i(e){return"object"==typeof e&&null!==e}function n(e){return void 0===e}return Ne=1,we=e,e.EventEmitter=e,e.prototype._events=void 0,e.prototype._maxListeners=void 0,e.defaultMaxListeners=10,e.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},e.prototype.emit=function(e){var r,s,o,a,d,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((r=arguments[1])instanceof Error)throw r;var c=new Error('Uncaught, unspecified "error" event. ('+r+")");throw c.context=r,c}if(n(s=this._events[e]))return!1;if(t(s))switch(arguments.length){case 1:s.call(this);break;case 2:s.call(this,arguments[1]);break;case 3:s.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),s.apply(this,a)}else if(i(s))for(a=Array.prototype.slice.call(arguments,1),o=(l=s.slice()).length,d=0;d<o;d++)l[d].apply(this,a);return!0},e.prototype.addListener=function(r,s){var o;if(!t(s))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",r,t(s.listener)?s.listener:s),this._events[r]?i(this._events[r])?this._events[r].push(s):this._events[r]=[this._events[r],s]:this._events[r]=s,i(this._events[r])&&!this._events[r].warned&&(o=n(this._maxListeners)?e.defaultMaxListeners:this._maxListeners)&&o>0&&this._events[r].length>o&&(this._events[r].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[r].length),"function"==typeof console.trace&&console.trace()),this},e.prototype.on=e.prototype.addListener,e.prototype.once=function(e,i){if(!t(i))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,i.apply(this,arguments))}return r.listener=i,this.on(e,r),this},e.prototype.removeListener=function(e,n){var r,s,o,a;if(!t(n))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(o=(r=this._events[e]).length,s=-1,r===n||t(r.listener)&&r.listener===n)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,n);else if(i(r)){for(a=o;a-- >0;)if(r[a]===n||r[a].listener&&r[a].listener===n){s=a;break}if(s<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(s,1),this._events.removeListener&&this.emit("removeListener",e,n)}return this},e.prototype.removeAllListeners=function(e){var i,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(i in this._events)"removeListener"!==i&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events={},this}if(t(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},e.prototype.listeners=function(e){return this._events&&this._events[e]?t(this._events[e])?[this._events[e]]:this._events[e].slice():[]},e.prototype.listenerCount=function(e){if(this._events){var i=this._events[e];if(t(i))return 1;if(i)return i.length}return 0},e.listenerCount=function(e,t){return e.listenerCount(t)},we}function ze(){if(Oe)return Me;Oe=1;var e,t=new(0,Le().EventEmitter);return Me={reset:function(){e=void 0},getApp:function(){return e},setApp:function(i){i&&(e=i,VizbeeSDK.logger.debug("AppAdapter::setApp in setApp"),t.emit("app",{type:"app",obj:i}))},isAppSet:function(){return!!e},preInit:function(){VizbeeSDK.logger.debug("AppAdapter::preInit() called"),e&&e.preInit?e.preInit():VizbeeSDK.logger.error("AppAdapter::preInit() - app.preInit() callback not provided by host app")},willStartVideo:function(t,i){e&&e.willStartVideo?e.willStartVideo(t,i):VizbeeSDK.logger.info("AppAdapter::willStartVideo() - app.willStartVideo() callback not provided by host app")},startVideo:function(t){e&&e.startVideo?e.startVideo(t):VizbeeSDK.logger.info("AppAdapter::StartVideo() - app.startVideo() callback not provided by host app")},playVideo:function(){return VizbeeSDK.logger.info("AppAdapter::PlayVideo() called"),e&&e.playVideo?e.playVideo():(VizbeeSDK.logger.info("AppAdapter::PlayVideo() - app.playVideo() callback not provided by host app"),!1)},pauseVideo:function(){return VizbeeSDK.logger.info("AppAdapter::PauseVideo() called"),e&&e.pauseVideo?e.pauseVideo():(VizbeeSDK.logger.info("AppAdapter::PauseVideo() - app.pauseVideo() callback not provided by host app"),!1)},stopVideo:function(t){return VizbeeSDK.logger.info("AppAdapter::StopVideo() called",t,e),VizbeeSDK.logger.debug("AppAdapter::StopVideo() called"),e&&e.stopVideo?(VizbeeSDK.logger.info("AppAdapter::StopVideo() called",t),e.stopVideo(t)):(VizbeeSDK.logger.info("AppAdapter::StopVideo() - app.stopVideo() callback not provided by host app"),!1)},seekVideo:function(t){return VizbeeSDK.logger.info("AppAdapter::SeekVideo() called",t),e&&e.seekVideo?e.seekVideo(t):(VizbeeSDK.logger.info("AppAdapter::SeekVideo() - app.seekVideo() callback not provided by host app"),!1)},getVideoInfo:function(){if(e&&e.getVideoInfo)return e.getVideoInfo()},getTracks:function(){return e&&e.getTracks?e.getTracks():(VizbeeSDK.logger.verbose("AppAdapter::getTracks() - app.getTracks() callback not provided by host app"),!1)},getEnabledTracks:function(){return e&&e.getEnabledTracks?e.getEnabledTracks():(VizbeeSDK.logger.verbose("AppAdapter::getEnabledTracks() - app.getEnabledTracks() callback not provided by host app"),!1)},enableTracks:function(t){return VizbeeSDK.logger.verbose("AppAdapter::enableTracks() called"),e&&e.enableTracks?e.enableTracks(t):(VizbeeSDK.logger.verbose("AppAdapter::enableTracks() - app.enableTracks() callback not provided by host app"),!1)},disableTracks:function(t){return VizbeeSDK.logger.verbose("AppAdapter::disableTracks() called"),e&&e.disableTracks?e.disableTracks(t):(VizbeeSDK.logger.verbose("AppAdapter::disableTracks() - app.disableTracks() callback not provided by host app"),!1)},getAudioTracks:function(){return e&&e.getAudioTracks?e.getAudioTracks():(VizbeeSDK.logger.verbose("AppAdapter::getAudioTracks() - app.getAudioTracks() callback not provided by host app"),!1)},getActiveAudioTrack:function(){return e&&e.getActiveAudioTrack?e.getActiveAudioTrack():(VizbeeSDK.logger.verbose("AppAdapter::getActiveAudioTrack() - app.getActiveAudioTrack() callback not provided by host app"),!1)},changeAudioTrack:function(t){return VizbeeSDK.logger.info("AppAdapter::changeAudioTrack() called"),e&&e.changeAudioTrack?e.changeAudioTrack(t):(VizbeeSDK.logger.info("AppAdapter::changeAudioTrack() - app.changeAudioTrack() callback not provided by host app"),!1)},onEvent:function(t){VizbeeSDK.logger.debug("AppAdapter::onEvent() called"),e&&e.onEvent?e.onEvent(t):VizbeeSDK.logger.info("AppAdapter::onEvent() - callback not provided by host app")},updatePresence:function(t){VizbeeSDK.logger.debug("AppAdapter::updatePresence() called"),e&&e.updatePresence?e.updatePresence(t):VizbeeSDK.logger.info("AppAdapter::updatePresence() - callback not provided by host app")},addListener:function(e){t.addListener("app",e)}},Me}var Re,Ke,Ue=I(),Be=new(0,Le().EventEmitter),Fe=ze(),Ge=void 0,He={isInProgress:!1},We=!1,je=0,qe="videoadapter_video",Ye="videoadapter_ad";function Je(e){var t,i,n=!Ue.contains(["timeupdate"],e.type);He.isInProgress||(Ge&&"app"!==Ge.app.state?(t=new Qe,e.type,"loading"===e.type&&(i="BUFFERING"),"playing"===e.type&&(i="PLAYING"),"paused"===e.type&&(i="PAUSED_BY_USER"),"ended"==e.type&&(i="FINISHED"),"interrupted"==e.type&&(i="INTERRUPTED"),"error"===e.type&&(i="INTERRUPTED",e.data&&e.data.reason&&"stop_by_user"!=e.data.reason.toLowerCase()&&(i="FAILED",t.error=e.data,t.error.data={})),i&&(t.state=i),Be.emit(qe,t,n)):VizbeeSDK.logger.verbose('VideoAdapter::videoEventHandler - app.state = "app"'))}function $e(e,t){var i=e.playing||e.preparing;(i||!i&&He.isInProgress)&&Be.emit(Ye,e,t),He.isInProgress=i||!1,He.isInProgress||(We=!1),"FINISHED"==e.state||e.state}function Qe(e){var t={type:"video",position:-1,duration:-1,cc:{},tr:{}};return Ke?(t.position=1e3*Ke.currentTime(),t.duration=1e3*Ke.getDuration(),t.startTime=Ke.getStartTime(),t.videoBufferLevel=Ke.getBufferLevel(),t.audioBufferLevel=Ke.getAudioBufferLevel(),t.qos=Ke.getStreamQualityInfo(),t.volume=100,t.muted=!1):(t.position=-1,t.duration=-1,t.startTime=0,t.videoBufferLevel=0,t.audioBufferLevel=0,t.volume=1,t.muted=!1),t.qos||(t.qos={adPodStartedTimeInMs:0,adPodEndedTimeInMs:0,loadReceivedByAppTimeInMs:0,loadReceivedByPlayerTimeInMs:0,metadataLoadedTimeInMs:0,playerReadyToPlayTimeInMs:0,playbackStartedTimeInMs:0}),Ue.extend(t,e)}var Ze=["stop_reason_before_next_video","stop_implicit"];function Xe(){He.isInProgress&&Re.reset()}var et,tt,it,nt,rt,st,ot,at,dt,lt,ct,ut,pt,ht,gt={setVideo:function(e){!function(e){var t=++je;function i(){return t!==je&&(VizbeeSDK.logger.debug("VideoAdapter::registerVideoEvents - dropping event from superseded player",t,je),!0)}e.onLoading=function(e){i()||He.isInProgress||(Je({type:"loading"}),We=!1)},e.onPlaying=function(e){i()||He.isInProgress||(Je({type:"playing"}),We=!0)},e.onPaused=function(e){i()||He.isInProgress||(Je({type:"paused"}),We=!1)},e.onBuffering=function(e){i()||He.isInProgress||(Je({type:"loading"}),We=!1)},e.onError=function(e){i()||He.isInProgress||(Je({type:"error",data:e}),We=!1)},e.onInterrupted=function(e){i()||He.isInProgress||(Je({type:"interrupted",data:e}),We=!1)},e.onEnded=function(){i()||He.isInProgress||(Je({type:"ended"}),We=!1)},e.onTimeUpdate=function(e){i()||He.isInProgress||(We?Je({type:"timeupdate"}):(We=!0,Je({type:"playing"})))}}(e),Ke=e},setVideoInfo:function(e){e&&Ge&&Ge.setCurrentVideoInfo(e)},setId:function(e,t){if(Ge){if(Ge.video&&Ge.video.id&&e&&Ge.video.id!=e){VizbeeSDK.logger.debug("VideoAdapter::setId - SENDING INTERRUPTED");var i=new Qe({id:Ge.video.id,state:"INTERRUPTED"});Be.emit(qe,i,!0)}var n=new Qe({id:e});n.position=n.duration=-1,n.state="UNKNOWN",Be.emit(qe,n,!0),VizbeeSDK.logger.debug("VideoAdapter::setId - setting currentGUID = "+e),Ge.setCurrentVideoInfo(Ue.extend(Ge.getCurrentVideoInfo()||{},{id:e,islive:t}))}},setVideoStop:function(){He&&He.isInProgress&&Re&&(He.isInProgress=!1,Re.reset()),Je({type:"error"})},willStart:function(e,t){Fe.willStartVideo(e,t)},start:function(e){Je({type:"loadedmetadata"}),Xe(),Fe.startVideo(e)},play:function(){Fe.playVideo()||VizbeeTV.tv.inputDevice.sendPlay()},pause:function(){Fe.pauseVideo()||VizbeeTV.tv.inputDevice.sendPause()},seek:function(e){Fe.seekVideo(e)||Ue.isNumber(e)&&Ke.seek(e)},stop:function(e){if(Fe.stopVideo(e))Ue.contains(Ze,e)&&(VizbeeSDK.logger.debug("VideoAdapter::stop - host handled switch stop; sending INTERRUPTED state"),Be.emit(qe,new Qe({state:"INTERRUPTED"}),!0));else{VizbeeTV.tv.inputDevice.sendStop(),VizbeeSDK.logger.debug("VideoAdapter::stop - sending INTERRUPTED state");var t=new Qe({state:"INTERRUPTED"});Be.emit(qe,t,!0),Xe()}},exit:function(){var e=new Qe({state:"INTERRUPTED"});Be.emit(qe,e,!0)},setTracks:function(e){Ke.setTracks(e)},getTracks:function(e){e=e||n;var t=Fe.getTracks();return!1!==t?t:Ke.getTracks(e)},getEnabledTracks:function(e){e=e||n;var t=Fe.getEnabledTracks();return!1!==t?t:Ke.getEnabledTracks(e)},enableTracks:function(e){Fe.enableTracks(e)||Ke.enableTracks(e)},disableTracks:function(e){Fe.disableTracks(e)||Ke.disableTracks(e)},getAudioTracks:function(e){e=e||r;var t=Fe.getAudioTracks();return!1!==t?t:Ke.getTracks(e)},getActiveAudioTrack:function(e){e=e||r;var t=Fe.getActiveAudioTrack();return!1!==t?t:(Ke.getEnabledTracks(e)||[])[0]},changeAudioTrack:function(e){Fe.changeAudioTrack(e)||Ke.changeAudioTrack(e)},mute:function(e){},volumeUp:function(){Be.emit(qe,new Qe,!0)},volumeDown:function(){Be.emit(qe,new Qe,!0)},onEvent:function(e){Fe.onEvent(e)},setAdAdapter:function(e){Re&&Re.removeListener($e),(Re=e)&&Re.addListener($e)},setAppStateManager:function(e){Ge=e},reset:function(){Ke=void 0,He={playing:!1}},addListener:function(e){Be.addListener(qe,e),Be.addListener(Ye,e)},removeListener:function(e){Be.removeListener(qe,e),Be.removeListener(Ye,e)}};function ft(){if(tt)return et;tt=1;var e,t=I();return et={reset:function(){e=void 0},setVideoAdapter:function(t){e=t},isAdapterSet:function(){return!!e},getCurrentTime:function(){var i=0;return e&&t.isFunction(e.getCurrentTime)&&(i=e.getCurrentTime()),i},getDuration:function(){var i=0;return e&&t.isFunction(e.getDuration)&&(i=e.getDuration()),i}}}function vt(){if(nt)return it;nt=1;var e=new(0,Le().EventEmitter),t=gt,i=ft(),n=void 0;function r(t,r){"video"==t.type&&(t=function(e,t){return t||e.position<=-1||e.duration<=-1||e.position>e.duration||i.isAdapterSet()&&(e.position=i.getCurrentTime(),e.duration=i.getDuration(),VizbeeSDK.logger.debug("ssaivideoadapater::modifyStatus",e.position,e.duration)),e}(t,n&&n.getSyncVideoInfo().islive)),function(t,i){e.emit("ssaivideoadapter_video",t,i)}(t,r)}return it={init:function(){t.addListener(r)},setVideo:t.setVideo,setVideoInfo:t.setVideoInfo,setId:t.setId,setVideoStop:t.setVideoStop,willStart:t.willStart,start:t.start,play:t.play,pause:t.pause,seek:t.seek,stop:t.stop,exit:t.exit,setTracks:t.setTracks,getTracks:t.getTracks,getEnabledTracks:t.getEnabledTracks,enableTracks:t.enableTracks,disableTracks:t.disableTracks,getAudioTracks:t.getAudioTracks,getActiveAudioTrack:t.getActiveAudioTrack,changeAudioTrack:t.changeAudioTrack,mute:t.mute,volumeUp:t.volumeUp,volumeDown:t.volumeDown,onEvent:t.onEvent,setAppStateManager:function(e){n=e,t.setAppStateManager(e)},setAdAdapter:t.setAdAdapter,reset:function(){n=void 0,t.removeListener(r),t.reset()},addListener:function(t){e.addListener("ssaivideoadapter_video",t)},removeListener:function(t){e.removeListener("ssaivideoadapter_video",t)}}}function yt(){if(st)return rt;st=1;var e=I(),t=new(0,Le().EventEmitter),i=vt(),n=ze(),r={state:"app"},s={},o={},a="default",d={},l={};function c(e){d=e}function u(t,i){"app"===t.type&&p(),"video"===t.type&&function(t,i){e.extend(s,t),["FINISHED","INTERRUPTED","FAILED"].indexOf(s.state)>-1?(VizbeeSDK.logger.debug("AppStateManager::videoEventHanlder() -- setting app.state to 'app'."),h(),r.state="app",g()):(r.state="video",i&&h())}(t,i),"ad"===t.type&&function(t,i){let n=i;t.playing||t.preparing?(r.state="ad",s.state="PAUSED_BY_AD",e.extend(o,t)):(o.preparing=!1,o.playing=!1,"INTERRUPTED"==t.state?(r.state="app",s.state="INTERRUPTED",n=!0):"PAUSED_BY_AD"==s.state&&(s.state="UNKNOWN"),!(l&&l.islive||d&&d.islive)&&s.duration<=s.position&&s.duration>0&&(r.state="app",s.state="FINISHED",n=!0)),n&&h()}(t,i)}function p(){VizbeeSDK.logger.debug("AppStateManager:appEventHandler appIsSet is TRUE"),t.emit("state",{type:"appIsSet"})}function h(){t.emit("state",{})}function g(){VizbeeSDK.logger.debug("AppStateManager:reset() previous video and ad objects = ",s,o,d),s.id="",s.state="UNKNOWN",s.position=-1,s.duration=-1,s.elapsedTime=0,s.tr={},s.error={},o.id="",o.state="UNKNOWN",o.position=-1,o.duration=-1,a={},VizbeeSDK.logger.debug("AppStateManager:reset() complete : current video and ad objects = ",s,o,d)}return g(),i.addListener(u),n.addListener(u),n.isAppSet()&&p(),rt={type:"AppStateManager",app:r,video:s,ad:o,reset:g,syncStartVideoSource:a,syncVideoInfo:d,setSyncVideoInfo:c,getSyncVideoInfo:function(){return d},currentVideoInfo:l,setCurrentVideoInfo:function(e){l=e,d&&e&&d.id!=e.id&&c({})},getCurrentVideoInfo:function(){return l},wasVideoStartedByVizbee:function(){return!!(l&&l.senderInfo&&l.senderInfo.st)||!(!d||!l||d.id!=l.id)},addListener:function(e){t.addListener("state",e)},removeListener:function(e){t.removeListener("state",e)}}}function mt(){return lt?dt:(lt=1,dt={setVGA:function(t){t&&(e=t,VizbeeSDK.logger.debug("VGAAdapter::setVGA in setVGA"))},onSubscribedToSync:function(){VizbeeSDK.logger.debug("VGAAdapter::subscribedToSync in subscribedToSync"),e&&e.onSubscribedToSync&&e.onSubscribedToSync()},reset:function(){e=void 0}});var e}function bt(){if(ut)return ct;ut=1;var e=new(0,Le().EventEmitter),t="sync_proxy_video_cmds";return ct={send:function(i){e.emit(t,i)},reset:function(){e.removeAllListeners(t)},addListener:function(i){e.addListener(t,i)}}}class St{constructor(e){this.appConfig=e||{},this._eventListeners=[]}connect(e){throw new TypeError("BaseSync::connect() - Abstract method.")}disconnect(){this._eventListeners=[]}send(e){}set onReceive(e){"function"==typeof e&&this._eventListeners.push(e)}dispatchReceive(e){for(var t=this._eventListeners.length-1;t>-1;t--)this._eventListeners[t](e)}}class _t{constructor(e,t){this.type=e,this.data=t}}class It{static get SYNC_CONNECT(){return"sync-connect"}static get SYNC_MESSAGE(){return"sync-message"}static get SYNC_PRESENCE(){return"sync-presence"}}var Tt,Et,Vt,Pt,At=_(function(){if(ht)return pt;ht=1;var e=ke().docCookies,t="screen_device_id",i="should_verify_screen_device_id",n="screen_device_id_verified_intermediate",r="screen_device_id_verified",s=e.getItem(r),o=e.getItem(t);return pt={getDeviceId:function(){return o},getDeviceIdFromStorage:function(){return e.getItem(t)},isDeviceIdVerified:function(){return s},isDeviceIdVerifiedFlagStored:function(){return e.getItem(r)},isIntermediateVerifcationCookieSet:function(){return e.getItem(n)},isShouldVerifyDeviceIdFlagSet:function(){return e.getItem(i)},setDeviceId:function(r){s||(o!==r&&this.isIntermediateVerifcationCookieSet()&&e.eraseCookieFromAllPaths(n),o=r,e.setItem(t,o,1/0,"/"),e.setItem(i,"yes",1/0,"/"))},verifyDeviceId:function(){e.getItem(i)&&(e.getItem(r)||(e.getItem(n)?(s="yes",e.setItem(r,s,1/0,"/"),VizbeeSDK.logger.debug("SETTING VERIFIED COOKIE *** ",e.getItem(r))):(e.setItem(n,"yes",1/0,"/"),VizbeeSDK.logger.debug("SETTING INTERMEDIATE COOKIE *** ",e.getItem(n)))),e.eraseCookieFromAllPaths(i))},reset:function(){for(var a=[t,r,i,n],d=0;d<a.length;d++)e.eraseCookieFromAllPaths(a[d]);s=null,o=null}}}()),Ct={exports:{}},Dt={exports:{}};function kt(){return Tt||(Tt=1,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t={rotl:function(e,t){return e<<t|e>>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&t.rotl(e,8)|4278255360&t.rotl(e,24);for(var i=0;i<e.length;i++)e[i]=t.endian(e[i]);return e},randomBytes:function(e){for(var t=[];e>0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],i=0,n=0;i<e.length;i++,n+=8)t[n>>>5]|=e[i]<<24-n%32;return t},wordsToBytes:function(e){for(var t=[],i=0;i<32*e.length;i+=8)t.push(e[i>>>5]>>>24-i%32&255);return t},bytesToHex:function(e){for(var t=[],i=0;i<e.length;i++)t.push((e[i]>>>4).toString(16)),t.push((15&e[i]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],i=0;i<e.length;i+=2)t.push(parseInt(e.substr(i,2),16));return t},bytesToBase64:function(t){for(var i=[],n=0;n<t.length;n+=3)for(var r=t[n]<<16|t[n+1]<<8|t[n+2],s=0;s<4;s++)8*n+6*s<=8*t.length?i.push(e.charAt(r>>>6*(3-s)&63)):i.push("=");return i.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/gi,"");for(var i=[],n=0,r=0;n<t.length;r=++n%4)0!=r&&i.push((e.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<2*r|e.indexOf(t.charAt(n))>>>6-2*r);return i}},Dt.exports=t),Dt.exports;var e,t}function wt(){if(Vt)return Et;Vt=1;var e={utf8:{stringToBytes:function(t){return e.bin.stringToBytes(unescape(encodeURIComponent(t)))},bytesToString:function(t){return decodeURIComponent(escape(e.bin.bytesToString(t)))}},bin:{stringToBytes:function(e){for(var t=[],i=0;i<e.length;i++)t.push(255&e.charCodeAt(i));return t},bytesToString:function(e){for(var t=[],i=0;i<e.length;i++)t.push(String.fromCharCode(e[i]));return t.join("")}}};return Et=e}var Nt,Mt,Ot,xt=(Pt||(Pt=1,function(){var e=kt(),t=wt().utf8,i=wt().bin,n=function(r,s){r.constructor==String?r=s&&"binary"===s.encoding?i.stringToBytes(r):t.stringToBytes(r):"undefined"!=typeof Buffer&&"function"==typeof Buffer.isBuffer&&Buffer.isBuffer(r)?r=Array.prototype.slice.call(r,0):Array.isArray(r)||(r=r.toString());for(var o=e.bytesToWords(r),a=8*r.length,d=1732584193,l=-271733879,c=-1732584194,u=271733878,p=0;p<o.length;p++)o[p]=16711935&(o[p]<<8|o[p]>>>24)|4278255360&(o[p]<<24|o[p]>>>8);o[a>>>5]|=128<<a%32,o[14+(a+64>>>9<<4)]=a;var h=n._ff,g=n._gg,f=n._hh,v=n._ii;for(p=0;p<o.length;p+=16){var y=d,m=l,b=c,S=u;d=h(d,l,c,u,o[p+0],7,-680876936),u=h(u,d,l,c,o[p+1],12,-389564586),c=h(c,u,d,l,o[p+2],17,606105819),l=h(l,c,u,d,o[p+3],22,-1044525330),d=h(d,l,c,u,o[p+4],7,-176418897),u=h(u,d,l,c,o[p+5],12,1200080426),c=h(c,u,d,l,o[p+6],17,-1473231341),l=h(l,c,u,d,o[p+7],22,-45705983),d=h(d,l,c,u,o[p+8],7,1770035416),u=h(u,d,l,c,o[p+9],12,-1958414417),c=h(c,u,d,l,o[p+10],17,-42063),l=h(l,c,u,d,o[p+11],22,-1990404162),d=h(d,l,c,u,o[p+12],7,1804603682),u=h(u,d,l,c,o[p+13],12,-40341101),c=h(c,u,d,l,o[p+14],17,-1502002290),d=g(d,l=h(l,c,u,d,o[p+15],22,1236535329),c,u,o[p+1],5,-165796510),u=g(u,d,l,c,o[p+6],9,-1069501632),c=g(c,u,d,l,o[p+11],14,643717713),l=g(l,c,u,d,o[p+0],20,-373897302),d=g(d,l,c,u,o[p+5],5,-701558691),u=g(u,d,l,c,o[p+10],9,38016083),c=g(c,u,d,l,o[p+15],14,-660478335),l=g(l,c,u,d,o[p+4],20,-405537848),d=g(d,l,c,u,o[p+9],5,568446438),u=g(u,d,l,c,o[p+14],9,-1019803690),c=g(c,u,d,l,o[p+3],14,-187363961),l=g(l,c,u,d,o[p+8],20,1163531501),d=g(d,l,c,u,o[p+13],5,-1444681467),u=g(u,d,l,c,o[p+2],9,-51403784),c=g(c,u,d,l,o[p+7],14,1735328473),d=f(d,l=g(l,c,u,d,o[p+12],20,-1926607734),c,u,o[p+5],4,-378558),u=f(u,d,l,c,o[p+8],11,-2022574463),c=f(c,u,d,l,o[p+11],16,1839030562),l=f(l,c,u,d,o[p+14],23,-35309556),d=f(d,l,c,u,o[p+1],4,-1530992060),u=f(u,d,l,c,o[p+4],11,1272893353),c=f(c,u,d,l,o[p+7],16,-155497632),l=f(l,c,u,d,o[p+10],23,-1094730640),d=f(d,l,c,u,o[p+13],4,681279174),u=f(u,d,l,c,o[p+0],11,-358537222),c=f(c,u,d,l,o[p+3],16,-722521979),l=f(l,c,u,d,o[p+6],23,76029189),d=f(d,l,c,u,o[p+9],4,-640364487),u=f(u,d,l,c,o[p+12],11,-421815835),c=f(c,u,d,l,o[p+15],16,530742520),d=v(d,l=f(l,c,u,d,o[p+2],23,-995338651),c,u,o[p+0],6,-198630844),u=v(u,d,l,c,o[p+7],10,1126891415),c=v(c,u,d,l,o[p+14],15,-1416354905),l=v(l,c,u,d,o[p+5],21,-57434055),d=v(d,l,c,u,o[p+12],6,1700485571),u=v(u,d,l,c,o[p+3],10,-1894986606),c=v(c,u,d,l,o[p+10],15,-1051523),l=v(l,c,u,d,o[p+1],21,-2054922799),d=v(d,l,c,u,o[p+8],6,1873313359),u=v(u,d,l,c,o[p+15],10,-30611744),c=v(c,u,d,l,o[p+6],15,-1560198380),l=v(l,c,u,d,o[p+13],21,1309151649),d=v(d,l,c,u,o[p+4],6,-145523070),u=v(u,d,l,c,o[p+11],10,-1120210379),c=v(c,u,d,l,o[p+2],15,718787259),l=v(l,c,u,d,o[p+9],21,-343485551),d=d+y>>>0,l=l+m>>>0,c=c+b>>>0,u=u+S>>>0}return e.endian([d,l,c,u])};n._ff=function(e,t,i,n,r,s,o){var a=e+(t&i|~t&n)+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._gg=function(e,t,i,n,r,s,o){var a=e+(t&n|i&~n)+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._hh=function(e,t,i,n,r,s,o){var a=e+(t^i^n)+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._ii=function(e,t,i,n,r,s,o){var a=e+(i^(t|~n))+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._blocksize=16,n._digestsize=16,Ct.exports=function(t,r){if(void 0!==t){var s=e.wordsToBytes(n(t,r));return r&&r.asBytes?s:r&&r.asString?i.bytesToString(s):e.bytesToHex(s)}}}()),Ct.exports),Lt=_(xt),zt={exports:{}},Rt={exports:{}},Kt={exports:{}},Ut={exports:{}},Bt={exports:{}};function Ft(){return Mt||(Mt=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){return Nt||(Nt=1,e=Bt,function(e){var t={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function i(){var e,t,i="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(i+="-"),i+=(12===e?4:16===e?3&t|8:t).toString(16);return i}function n(e,i){var n=t[i||"all"];return n&&n.test(e)||!1}i.isUUID=n,i.VERSION="0.1.0",e.uuid=i,e.isUUID=n}(t=Bt.exports),null!==e&&(e.exports=t.uuid)),Bt.exports;var e,t}(),r=(i=n)&&i.__esModule?i:{default:i};t.default={createUUID:function(){return r.default.uuid?r.default.uuid():(0,r.default)()}},e.exports=t.default}(Ut,Ut.exports)),Ut.exports}function Gt(){return Ot||(Ot=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),r=(i=Ft())&&i.__esModule?i:{default:i},s=function(){function e(t){var i=t.setup,n=t.db;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._db=n,this.instanceId="pn-"+r.default.createUUID(),this.secretKey=i.secretKey||i.secret_key,this.subscribeKey=i.subscribeKey||i.subscribe_key,this.publishKey=i.publishKey||i.publish_key,this.sdkName=i.sdkName,this.sdkFamily=i.sdkFamily,this.partnerId=i.partnerId,this.setAuthKey(i.authKey),this.setCipherKey(i.cipherKey),this.setFilterExpression(i.filterExpression),this.origin=i.origin||"pubsub.pndsn.com",this.secure=i.ssl||!1,this.restore=i.restore||!1,this.proxy=i.proxy,this.keepAlive=i.keepAlive,this.keepAliveSettings=i.keepAliveSettings,this.autoNetworkDetection=i.autoNetworkDetection||!1,this.dedupeOnSubscribe=i.dedupeOnSubscribe||!1,this.maximumCacheSize=i.maximumCacheSize||100,this.customEncrypt=i.customEncrypt,this.customDecrypt=i.customDecrypt,"undefined"!=typeof location&&"https:"===location.protocol&&(this.secure=!0),this.logVerbosity=i.logVerbosity||!1,this.suppressLeaveEvents=i.suppressLeaveEvents||!1,this.announceFailedHeartbeats=i.announceFailedHeartbeats||!0,this.announceSuccessfulHeartbeats=i.announceSuccessfulHeartbeats||!1,this.useInstanceId=i.useInstanceId||!1,this.useRequestId=i.useRequestId||!1,this.requestMessageCountThreshold=i.requestMessageCountThreshold,this.setTransactionTimeout(i.transactionalRequestTimeout||15e3),this.setSubscribeTimeout(i.subscribeRequestTimeout||31e4),this.setSendBeaconConfig(i.useSendBeacon||!0),this.setPresenceTimeout(i.presenceTimeout||300),null!=i.heartbeatInterval&&this.setHeartbeatInterval(i.heartbeatInterval),this.setUUID(this._decideUUID(i.uuid))}return n(e,[{key:"getAuthKey",value:function(){return this.authKey}},{key:"setAuthKey",value:function(e){return this.authKey=e,this}},{key:"setCipherKey",value:function(e){return this.cipherKey=e,this}},{key:"getUUID",value:function(){return this.UUID}},{key:"setUUID",value:function(e){return this._db&&this._db.set&&this._db.set(this.subscribeKey+"uuid",e),this.UUID=e,this}},{key:"getFilterExpression",value:function(){return this.filterExpression}},{key:"setFilterExpression",value:function(e){return this.filterExpression=e,this}},{key:"getPresenceTimeout",value:function(){return this._presenceTimeout}},{key:"setPresenceTimeout",value:function(e){return this._presenceTimeout=e,this.setHeartbeatInterval(this._presenceTimeout/2-1),this}},{key:"setProxy",value:function(e){this.proxy=e}},{key:"getHeartbeatInterval",value:function(){return this._heartbeatInterval}},{key:"setHeartbeatInterval",value:function(e){return this._heartbeatInterval=e,this}},{key:"getSubscribeTimeout",value:function(){return this._subscribeRequestTimeout}},{key:"setSubscribeTimeout",value:function(e){return this._subscribeRequestTimeout=e,this}},{key:"getTransactionTimeout",value:function(){return this._transactionalRequestTimeout}},{key:"setTransactionTimeout",value:function(e){return this._transactionalRequestTimeout=e,this}},{key:"isSendBeaconEnabled",value:function(){return this._useSendBeacon}},{key:"setSendBeaconConfig",value:function(e){return this._useSendBeacon=e,this}},{key:"getVersion",value:function(){return"4.20.3"}},{key:"_decideUUID",value:function(e){return e||(this._db&&this._db.get&&this._db.get(this.subscribeKey+"uuid")?this._db.get(this.subscribeKey+"uuid"):"pn-"+r.default.createUUID())}}]),e}();t.default=s,e.exports=t.default}(Kt,Kt.exports)),Kt.exports}var Ht,Wt={exports:{}};function jt(){return Ht||(Ht=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();r(Gt());var n=r(null);function r(e){return e&&e.__esModule?e:{default:e}}var s=function(){function e(t){var i=t.config;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._config=i,this._iv="0123456789012345",this._allowedKeyEncodings=["hex","utf8","base64","binary"],this._allowedKeyLengths=[128,256],this._allowedModes=["ecb","cbc"],this._defaultOptions={encryptKey:!0,keyEncoding:"utf8",keyLength:256,mode:"cbc"}}return i(e,[{key:"HMACSHA256",value:function(e){return n.default.HmacSHA256(e,this._config.secretKey).toString(n.default.enc.Base64)}},{key:"SHA256",value:function(e){return n.default.SHA256(e).toString(n.default.enc.Hex)}},{key:"_parseOptions",value:function(e){var t=e||{};return t.hasOwnProperty("encryptKey")||(t.encryptKey=this._defaultOptions.encryptKey),t.hasOwnProperty("keyEncoding")||(t.keyEncoding=this._defaultOptions.keyEncoding),t.hasOwnProperty("keyLength")||(t.keyLength=this._defaultOptions.keyLength),t.hasOwnProperty("mode")||(t.mode=this._defaultOptions.mode),-1===this._allowedKeyEncodings.indexOf(t.keyEncoding.toLowerCase())&&(t.keyEncoding=this._defaultOptions.keyEncoding),-1===this._allowedKeyLengths.indexOf(parseInt(t.keyLength,10))&&(t.keyLength=this._defaultOptions.keyLength),-1===this._allowedModes.indexOf(t.mode.toLowerCase())&&(t.mode=this._defaultOptions.mode),t}},{key:"_decodeKey",value:function(e,t){return"base64"===t.keyEncoding?n.default.enc.Base64.parse(e):"hex"===t.keyEncoding?n.default.enc.Hex.parse(e):e}},{key:"_getPaddedKey",value:function(e,t){return e=this._decodeKey(e,t),t.encryptKey?n.default.enc.Utf8.parse(this.SHA256(e).slice(0,32)):e}},{key:"_getMode",value:function(e){return"ecb"===e.mode?n.default.mode.ECB:n.default.mode.CBC}},{key:"_getIV",value:function(e){return"cbc"===e.mode?n.default.enc.Utf8.parse(this._iv):null}},{key:"encrypt",value:function(e,t,i){return this._config.customEncrypt?this._config.customEncrypt(e):this.pnEncrypt(e,t,i)}},{key:"decrypt",value:function(e,t,i){return this._config.customDecrypt?this._config.customDecrypt(e):this.pnDecrypt(e,t,i)}},{key:"pnEncrypt",value:function(e,t,i){if(!t&&!this._config.cipherKey)return e;i=this._parseOptions(i);var r=this._getIV(i),s=this._getMode(i),o=this._getPaddedKey(t||this._config.cipherKey,i);return n.default.AES.encrypt(e,o,{iv:r,mode:s}).ciphertext.toString(n.default.enc.Base64)||e}},{key:"pnDecrypt",value:function(e,t,i){if(!t&&!this._config.cipherKey)return e;i=this._parseOptions(i);var r=this._getIV(i),s=this._getMode(i),o=this._getPaddedKey(t||this._config.cipherKey,i);try{var a=n.default.enc.Base64.parse(e),d=n.default.AES.decrypt({ciphertext:a},o,{iv:r,mode:s}).toString(n.default.enc.Utf8);return JSON.parse(d)}catch(e){return null}}}]),e}();t.default=s,e.exports=t.default}(Wt,Wt.exports)),Wt.exports}var qt,Yt,Jt={exports:{}},$t={exports:{}},Qt={exports:{}};function Zt(){return qt||(qt=1,e=Qt,t=Qt.exports,Object.defineProperty(t,"__esModule",{value:!0}),t.default={PNNetworkUpCategory:"PNNetworkUpCategory",PNNetworkDownCategory:"PNNetworkDownCategory",PNNetworkIssuesCategory:"PNNetworkIssuesCategory",PNTimeoutCategory:"PNTimeoutCategory",PNBadRequestCategory:"PNBadRequestCategory",PNAccessDeniedCategory:"PNAccessDeniedCategory",PNUnknownCategory:"PNUnknownCategory",PNReconnectedCategory:"PNReconnectedCategory",PNConnectedCategory:"PNConnectedCategory",PNRequestMessageCountExceededCategory:"PNRequestMessageCountExceededCategory"},e.exports=t.default),Qt.exports;var e,t}function Xt(){return Yt||(Yt=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),r=(i=Zt())&&i.__esModule?i:{default:i},s=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._listeners=[]}return n(e,[{key:"addListener",value:function(e){this._listeners.push(e)}},{key:"removeListener",value:function(e){var t=[];this._listeners.forEach(function(i){i!==e&&t.push(i)}),this._listeners=t}},{key:"removeAllListeners",value:function(){this._listeners=[]}},{key:"announcePresence",value:function(e){this._listeners.forEach(function(t){t.presence&&t.presence(e)})}},{key:"announceStatus",value:function(e){this._listeners.forEach(function(t){t.status&&t.status(e)})}},{key:"announceMessage",value:function(e){this._listeners.forEach(function(t){t.message&&t.message(e)})}},{key:"announceNetworkUp",value:function(){var e={};e.category=r.default.PNNetworkUpCategory,this.announceStatus(e)}},{key:"announceNetworkDown",value:function(){var e={};e.category=r.default.PNNetworkDownCategory,this.announceStatus(e)}}]),e}();t.default=s,e.exports=t.default}($t,$t.exports)),$t.exports}var ei,ti,ii,ni={exports:{}},ri={},si={exports:{}};function oi(){return ei||(ei=1,e=si,t=si.exports,Object.defineProperty(t,"__esModule",{value:!0}),t.default={PNTimeOperation:"PNTimeOperation",PNHistoryOperation:"PNHistoryOperation",PNDeleteMessagesOperation:"PNDeleteMessagesOperation",PNFetchMessagesOperation:"PNFetchMessagesOperation",PNSubscribeOperation:"PNSubscribeOperation",PNUnsubscribeOperation:"PNUnsubscribeOperation",PNPublishOperation:"PNPublishOperation",PNPushNotificationEnabledChannelsOperation:"PNPushNotificationEnabledChannelsOperation",PNRemoveAllPushNotificationsOperation:"PNRemoveAllPushNotificationsOperation",PNWhereNowOperation:"PNWhereNowOperation",PNSetStateOperation:"PNSetStateOperation",PNHereNowOperation:"PNHereNowOperation",PNGetStateOperation:"PNGetStateOperation",PNHeartbeatOperation:"PNHeartbeatOperation",PNChannelGroupsOperation:"PNChannelGroupsOperation",PNRemoveGroupOperation:"PNRemoveGroupOperation",PNChannelsForGroupOperation:"PNChannelsForGroupOperation",PNAddChannelsToGroupOperation:"PNAddChannelsToGroupOperation",PNRemoveChannelsFromGroupOperation:"PNRemoveChannelsFromGroupOperation",PNAccessManagerGrant:"PNAccessManagerGrant",PNAccessManagerAudit:"PNAccessManagerAudit"},e.exports=t.default),si.exports;var e,t}function ai(){if(ti)return ri;ti=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.getOperation=function(){return t.default.PNTimeOperation},ri.getURL=function(){return"/time/0"},ri.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},ri.prepareParams=function(){return{}},ri.isAuthSupported=function(){return!1},ri.handleResponse=function(e,t){return{timetoken:t[0]}},ri.validateParams=function(){};var e,t=(e=oi())&&e.__esModule?e:{default:e};return ri}var di,li,ci,ui,pi={exports:{}};function hi(){if(ci)return li;function e(e){return encodeURIComponent(e).replace(/[!~*'()]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}return ci=1,li={signPamFromParams:function(t){return(i=t,function(e){var t=[];return Object.keys(e).forEach(function(e){return t.push(e)}),t}(i).sort()).map(function(i){return i+"="+e(t[i])}).join("&");var i},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e=void 0,t=void 0;return{promise:new Promise(function(i,n){e=i,t=n}),reject:t,fulfill:e}},encodeString:e}}function gi(){return ui||(ui=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();a(jt()),a(Gt()),a(Xt());var n=a((ii||(ii=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();!(i=ai())||i.__esModule;var r=function(){function e(t){var i=t.timeEndpoint;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._timeEndpoint=i}return n(e,[{key:"onReconnection",value:function(e){this._reconnectionCallback=e}},{key:"startPolling",value:function(){this._timeTimer=setInterval(this._performTimeLoop.bind(this),3e3)}},{key:"stopPolling",value:function(){clearInterval(this._timeTimer)}},{key:"_performTimeLoop",value:function(){var e=this;this._timeEndpoint(function(t){t.error||(clearInterval(e._timeTimer),e._reconnectionCallback())})}}]),e}();t.default=r,e.exports=t.default}(ni,ni.exports)),ni.exports)),r=a((di||(di=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();!(i=Gt())||i.__esModule;var r=function(){function e(t){var i=t.config;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hashHistory=[],this._config=i}return n(e,[{key:"getKey",value:function(e){var t=function(e){var t=0;if(0===e.length)return t;for(var i=0;i<e.length;i+=1)t=(t<<5)-t+e.charCodeAt(i),t&=t;return t}(JSON.stringify(e.payload)).toString();return e.publishMetaData.publishTimetoken+"-"+t}},{key:"isDuplicate",value:function(e){return this.hashHistory.includes(this.getKey(e))}},{key:"addEntry",value:function(e){this.hashHistory.length>=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}},{key:"clearHistory",value:function(){this.hashHistory=[]}}]),e}();t.default=r,e.exports=t.default}(pi,pi.exports)),pi.exports)),s=a(hi()),o=a(Zt());function a(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(t){var i=t.subscribeEndpoint,s=t.leaveEndpoint,o=t.heartbeatEndpoint,a=t.setStateEndpoint,d=t.timeEndpoint,l=t.config,c=t.crypto,u=t.listenerManager;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._listenerManager=u,this._config=l,this._leaveEndpoint=s,this._heartbeatEndpoint=o,this._setStateEndpoint=a,this._subscribeEndpoint=i,this._crypto=c,this._channels={},this._presenceChannels={},this._heartbeatChannels={},this._heartbeatChannelGroups={},this._channelGroups={},this._presenceChannelGroups={},this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[],this._currentTimetoken=0,this._lastTimetoken=0,this._storedTimetoken=null,this._subscriptionStatusAnnounced=!1,this._isOnline=!0,this._reconnectionManager=new n.default({timeEndpoint:d}),this._dedupingManager=new r.default({config:l})}return i(e,[{key:"adaptStateChange",value:function(e,t){var i=this,n=e.state,r=e.channels,s=void 0===r?[]:r,o=e.channelGroups,a=void 0===o?[]:o;return s.forEach(function(e){e in i._channels&&(i._channels[e].state=n)}),a.forEach(function(e){e in i._channelGroups&&(i._channelGroups[e].state=n)}),this._setStateEndpoint({state:n,channels:s,channelGroups:a},t)}},{key:"adaptPresenceChange",value:function(e){var t=this,i=e.connected,n=e.channels,r=void 0===n?[]:n,s=e.channelGroups,o=void 0===s?[]:s;i?(r.forEach(function(e){t._heartbeatChannels[e]={state:{}}}),o.forEach(function(e){t._heartbeatChannelGroups[e]={state:{}}})):(r.forEach(function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]}),o.forEach(function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]}),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:r,channelGroups:o},function(e){t._listenerManager.announceStatus(e)})),this.reconnect()}},{key:"adaptSubscribeChange",value:function(e){var t=this,i=e.timetoken,n=e.channels,r=void 0===n?[]:n,s=e.channelGroups,o=void 0===s?[]:s,a=e.withPresence,d=void 0!==a&&a;this._config.subscribeKey&&""!==this._config.subscribeKey?(i&&(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=i),"0"!==this._currentTimetoken&&0!==this._currentTimetoken&&(this._storedTimetoken=this._currentTimetoken,this._currentTimetoken=0),r.forEach(function(e){t._channels[e]={state:{}},d&&(t._presenceChannels[e]={}),t._pendingChannelSubscriptions.push(e)}),o.forEach(function(e){t._channelGroups[e]={state:{}},d&&(t._presenceChannelGroups[e]={}),t._pendingChannelGroupSubscriptions.push(e)}),this._subscriptionStatusAnnounced=!1,this.reconnect()):console&&console.log}},{key:"adaptUnsubscribeChange",value:function(e,t){var i=this,n=e.channels,r=void 0===n?[]:n,s=e.channelGroups,o=void 0===s?[]:s,a=[],d=[];r.forEach(function(e){e in i._channels&&(delete i._channels[e],a.push(e)),e in i._presenceChannels&&(delete i._presenceChannels[e],a.push(e))}),o.forEach(function(e){e in i._channelGroups&&(delete i._channelGroups[e],d.push(e)),e in i._presenceChannelGroups&&(delete i._channelGroups[e],d.push(e))}),0===a.length&&0===d.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:a,channelGroups:d},function(e){e.affectedChannels=a,e.affectedChannelGroups=d,e.currentTimetoken=i._currentTimetoken,e.lastTimetoken=i._lastTimetoken,i._listenerManager.announceStatus(e)}),0===Object.keys(this._channels).length&&0===Object.keys(this._presenceChannels).length&&0===Object.keys(this._channelGroups).length&&0===Object.keys(this._presenceChannelGroups).length&&(this._lastTimetoken=0,this._currentTimetoken=0,this._storedTimetoken=null,this._region=null,this._reconnectionManager.stopPolling()),this.reconnect())}},{key:"unsubscribeAll",value:function(e){this.adaptUnsubscribeChange({channels:this.getSubscribedChannels(),channelGroups:this.getSubscribedChannelGroups()},e)}},{key:"getHeartbeatChannels",value:function(){return Object.keys(this._heartbeatChannels)}},{key:"getHeartbeatChannelGroups",value:function(){return Object.keys(this._heartbeatChannelGroups)}},{key:"getSubscribedChannels",value:function(){return Object.keys(this._channels)}},{key:"getSubscribedChannelGroups",value:function(){return Object.keys(this._channelGroups)}},{key:"reconnect",value:function(){this._startSubscribeLoop(),this._registerHeartbeatTimer()}},{key:"disconnect",value:function(){this._stopSubscribeLoop(),this._stopHeartbeatTimer(),this._reconnectionManager.stopPolling()}},{key:"_registerHeartbeatTimer",value:function(){this._stopHeartbeatTimer(),0!==this._config.getHeartbeatInterval()&&(this._performHeartbeatLoop(),this._heartbeatTimer=setInterval(this._performHeartbeatLoop.bind(this),1e3*this._config.getHeartbeatInterval()))}},{key:"_stopHeartbeatTimer",value:function(){this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null)}},{key:"_performHeartbeatLoop",value:function(){var e=this,t=[];t=(t=t.concat(this.getHeartbeatChannels())).concat(this.getSubscribedChannels());var i=[];i=(i=i.concat(this.getHeartbeatChannelGroups())).concat(this.getSubscribedChannelGroups());var n={};0===t.length&&0===i.length||(this.getSubscribedChannels().forEach(function(t){var i=e._channels[t].state;Object.keys(i).length&&(n[t]=i)}),this.getSubscribedChannelGroups().forEach(function(t){var i=e._channelGroups[t].state;Object.keys(i).length&&(n[t]=i)}),this._heartbeatEndpoint({channels:t,channelGroups:i,state:n},function(t){t.error&&e._config.announceFailedHeartbeats&&e._listenerManager.announceStatus(t),t.error&&e._config.autoNetworkDetection&&e._isOnline&&(e._isOnline=!1,e.disconnect(),e._listenerManager.announceNetworkDown(),e.reconnect()),!t.error&&e._config.announceSuccessfulHeartbeats&&e._listenerManager.announceStatus(t)}.bind(this)))}},{key:"_startSubscribeLoop",value:function(){this._stopSubscribeLoop();var e=[],t=[];if(Object.keys(this._channels).forEach(function(t){return e.push(t)}),Object.keys(this._presenceChannels).forEach(function(t){return e.push(t+"-pnpres")}),Object.keys(this._channelGroups).forEach(function(e){return t.push(e)}),Object.keys(this._presenceChannelGroups).forEach(function(e){return t.push(e+"-pnpres")}),0!==e.length||0!==t.length){var i={channels:e,channelGroups:t,timetoken:this._currentTimetoken,filterExpression:this._config.filterExpression,region:this._region};this._subscribeCall=this._subscribeEndpoint(i,this._processSubscribeResponse.bind(this))}}},{key:"_processSubscribeResponse",value:function(e,t){var i=this;if(e.error)e.category===o.default.PNTimeoutCategory?this._startSubscribeLoop():e.category===o.default.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this._config.autoNetworkDetection&&this._isOnline&&(this._isOnline=!1,this._listenerManager.announceNetworkDown()),this._reconnectionManager.onReconnection(function(){i._config.autoNetworkDetection&&!i._isOnline&&(i._isOnline=!0,i._listenerManager.announceNetworkUp()),i.reconnect(),i._subscriptionStatusAnnounced=!0;var t={category:o.default.PNReconnectedCategory,operation:e.operation,lastTimetoken:i._lastTimetoken,currentTimetoken:i._currentTimetoken};i._listenerManager.announceStatus(t)}),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===o.default.PNBadRequestCategory?(this._stopHeartbeatTimer(),this._listenerManager.announceStatus(e)):this._listenerManager.announceStatus(e);else{if(this._storedTimetoken?(this._currentTimetoken=this._storedTimetoken,this._storedTimetoken=null):(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=t.metadata.timetoken),!this._subscriptionStatusAnnounced){var n={};n.category=o.default.PNConnectedCategory,n.operation=e.operation,n.affectedChannels=this._pendingChannelSubscriptions,n.subscribedChannels=this.getSubscribedChannels(),n.affectedChannelGroups=this._pendingChannelGroupSubscriptions,n.lastTimetoken=this._lastTimetoken,n.currentTimetoken=this._currentTimetoken,this._subscriptionStatusAnnounced=!0,this._listenerManager.announceStatus(n),this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[]}var r=t.messages||[],a=this._config,d=a.requestMessageCountThreshold,l=a.dedupeOnSubscribe;if(d&&r.length>=d){var c={};c.category=o.default.PNRequestMessageCountExceededCategory,c.operation=e.operation,this._listenerManager.announceStatus(c)}r.forEach(function(e){var t=e.channel,n=e.subscriptionMatch,r=e.publishMetaData;if(t===n&&(n=null),l){if(i._dedupingManager.isDuplicate(e))return;i._dedupingManager.addEntry(e)}if(s.default.endsWith(e.channel,"-pnpres")){var o={channel:null,subscription:null};o.actualChannel=null!=n?t:null,o.subscribedChannel=null!=n?n:t,t&&(o.channel=t.substring(0,t.lastIndexOf("-pnpres"))),n&&(o.subscription=n.substring(0,n.lastIndexOf("-pnpres"))),o.action=e.payload.action,o.state=e.payload.data,o.timetoken=r.publishTimetoken,o.occupancy=e.payload.occupancy,o.uuid=e.payload.uuid,o.timestamp=e.payload.timestamp,e.payload.join&&(o.join=e.payload.join),e.payload.leave&&(o.leave=e.payload.leave),e.payload.timeout&&(o.timeout=e.payload.timeout),i._listenerManager.announcePresence(o)}else{var a={channel:null,subscription:null};a.actualChannel=null!=n?t:null,a.subscribedChannel=null!=n?n:t,a.channel=t,a.subscription=n,a.timetoken=r.publishTimetoken,a.publisher=e.issuingClientId,e.userMetadata&&(a.userMetadata=e.userMetadata),i._config.cipherKey?a.message=i._crypto.decrypt(e.payload):a.message=e.payload,i._listenerManager.announceMessage(a)}}),this._region=t.metadata.region,this._startSubscribeLoop()}}},{key:"_stopSubscribeLoop",value:function(){this._subscribeCall&&("function"==typeof this._subscribeCall.abort&&this._subscribeCall.abort(),this._subscribeCall=null)}}]),e}();t.default=d,e.exports=t.default}(Jt,Jt.exports)),Jt.exports}var fi,vi={exports:{}};var yi,mi,bi,Si,_i,Ii={},Ti={},Ei={},Vi={};function Pi(){return _i||(_i=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),n=K(Gt()),r=K(jt()),s=K(gi()),o=K(Xt()),a=K((fi||(fi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var s=e.networking,d=e.config,l=null,c=null,u={};t.getOperation()===r.default.PNTimeOperation||t.getOperation()===r.default.PNChannelGroupsOperation?l=arguments.length<=2?void 0:arguments[2]:(u=arguments.length<=2?void 0:arguments[2],l=arguments.length<=3?void 0:arguments[3]),"undefined"==typeof Promise||l||(c=n.default.createPromise());var p=t.validateParams(e,u);if(p)return l?l(a(p)):c?(c.reject(new o("Validation failed, check status for details",a(p))),c.promise):void 0;var h=t.prepareParams(e,u),g=function(e,t,i){return e.usePost&&e.usePost(t,i)?e.postURL(t,i):e.getURL(t,i)}(t,e,u),f=void 0,v={url:g,operation:t.getOperation(),timeout:t.getRequestTimeout(e)};h.uuid=d.UUID,h.pnsdk=function(e){if(e.sdkName)return e.sdkName;var t="PubNub-JS-"+e.sdkFamily;return e.partnerId&&(t+="-"+e.partnerId),t+"/"+e.getVersion()}(d),d.useInstanceId&&(h.instanceid=d.instanceId),d.useRequestId&&(h.requestid=i.default.createUUID()),t.isAuthSupported()&&d.getAuthKey()&&(h.auth=d.getAuthKey()),d.secretKey&&function(e,t,i){var r=e.config,s=e.crypto;i.timestamp=Math.floor((new Date).getTime()/1e3);var o=r.subscribeKey+"\n"+r.publishKey+"\n"+t+"\n";o+=n.default.signPamFromParams(i);var a=s.HMACSHA256(o);a=(a=a.replace(/\+/g,"-")).replace(/\//g,"_"),i.signature=a}(e,g,h);var y=function(i,n){if(i.error)l?l(i):c&&c.reject(new o("PubNub call failed, check status for details",i));else{var r=t.handleResponse(e,n,u);l?l(i,r):c&&c.fulfill(r)}};if(t.usePost&&t.usePost(e,u)){var m=t.postPayload(e,u);f=s.POST(h,m,v,y)}else f=t.useDelete&&t.useDelete()?s.DELETE(h,v,y):s.GET(h,v,y);return t.getOperation()===r.default.PNSubscribeOperation?f:c?c.promise:void 0};var i=s(Ft()),n=s(hi());s(Gt());var r=s(oi());function s(e){return e&&e.__esModule?e:{default:e}}var o=function(){function e(t,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return n.name=n.constructor.name,n.status=i,n.message=t,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(e,Error),e}();function a(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}e.exports=t.default}(vi,vi.exports)),vi.exports)),d=R(null),l=R(null),c=R(null),u=R(null),p=R(null),h=R(null),g=R(null),f=R(null),v=R(null),y=function(){if(yi)return Ii;yi=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.getOperation=function(){return e.default.PNUnsubscribeOperation},Ii.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Ii.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,o=s.length>0?s.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+t.default.encodeString(o)+"/leave"},Ii.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Ii.isAuthSupported=function(){return!0},Ii.prepareParams=function(e,t){var i=t.channelGroups,n=void 0===i?[]:i,r={};return n.length>0&&(r["channel-group"]=n.join(",")),r},Ii.handleResponse=function(){return{}};var e=i(oi()),t=i(hi());function i(e){return e&&e.__esModule?e:{default:e}}return Ii}(),m=R(y),b=R(null),S=function(){if(mi)return Ti;mi=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.getOperation=function(){return e.default.PNHeartbeatOperation},Ti.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Ti.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,o=s.length>0?s.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+t.default.encodeString(o)+"/heartbeat"},Ti.isAuthSupported=function(){return!0},Ti.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Ti.prepareParams=function(e,t){var i=t.channelGroups,n=void 0===i?[]:i,r=t.state,s=void 0===r?{}:r,o=e.config,a={};return n.length>0&&(a["channel-group"]=n.join(",")),a.state=JSON.stringify(s),a.heartbeat=o.getPresenceTimeout(),a},Ti.handleResponse=function(){return{}};var e=i(oi()),t=i(hi());function i(e){return e&&e.__esModule?e:{default:e}}return Ti}(),_=R(S),I=R(null),T=R(null),E=R(null),V=R(null),P=R(null),A=function(){if(bi)return Ei;bi=1,Object.defineProperty(Ei,"__esModule",{value:!0});var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Ei.getOperation=function(){return t.default.PNPublishOperation},Ei.validateParams=function(e,t){var i=e.config,n=t.message;return t.channel?n?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},Ei.usePost=function(e,t){var i=t.sendByPost;return void 0!==i&&i},Ei.getURL=function(e,t){var n=e.config,s=t.channel,o=r(e,t.message);return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+i.default.encodeString(s)+"/0/"+i.default.encodeString(o)},Ei.postURL=function(e,t){var n=e.config,r=t.channel;return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+i.default.encodeString(r)+"/0"},Ei.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Ei.isAuthSupported=function(){return!0},Ei.postPayload=function(e,t){return r(e,t.message)},Ei.prepareParams=function(t,i){var n=i.meta,r=i.replicate,s=void 0===r||r,o=i.storeInHistory,a=i.ttl,d={};return null!=o&&(d.store=o?"1":"0"),a&&(d.ttl=a),!1===s&&(d.norep="true"),n&&"object"===(void 0===n?"undefined":e(n))&&(d.meta=JSON.stringify(n)),d},Ei.handleResponse=function(e,t){return{timetoken:t[2]}};var t=n(oi()),i=n(hi());function n(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var i=e.crypto,n=e.config,r=JSON.stringify(t);return n.cipherKey&&(r=i.encrypt(r),r=JSON.stringify(r)),r}return Ei}(),C=R(A),D=R(null),k=R(null),w=R(null),N=R(ai()),M=function(){if(Si)return Vi;Si=1,Object.defineProperty(Vi,"__esModule",{value:!0}),Vi.getOperation=function(){return e.default.PNSubscribeOperation},Vi.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Vi.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,o=s.length>0?s.join(","):",";return"/v2/subscribe/"+n.subscribeKey+"/"+t.default.encodeString(o)+"/0"},Vi.getRequestTimeout=function(e){return e.config.getSubscribeTimeout()},Vi.isAuthSupported=function(){return!0},Vi.prepareParams=function(e,t){var i=e.config,n=t.channelGroups,r=void 0===n?[]:n,s=t.timetoken,o=t.filterExpression,a=t.region,d={heartbeat:i.getPresenceTimeout()};return r.length>0&&(d["channel-group"]=r.join(",")),o&&o.length>0&&(d["filter-expr"]=o),s&&(d.tt=s),a&&(d.tr=a),d},Vi.handleResponse=function(e,t){var i=[];t.m.forEach(function(e){var t={publishTimetoken:e.p.t,region:e.p.r},n={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};i.push(n)});var n={timetoken:t.t.t,region:t.t.r};return{messages:i,metadata:n}};var e=i(oi()),t=i(hi());function i(e){return e&&e.__esModule?e:{default:e}}return Vi}(),O=R(M),x=K(oi()),L=K(Zt()),z=K(Ft());function R(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}function K(e){return e&&e.__esModule?e:{default:e}}var U=function(){function e(t){var i=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var y=t.db,S=t.networking,A=this._config=new n.default({setup:t,db:y}),M=new r.default({config:A});S.init(A);var x={config:A,networking:S,crypto:M},L=a.default.bind(this,x,N),z=a.default.bind(this,x,m),R=a.default.bind(this,x,_),K=a.default.bind(this,x,T),U=a.default.bind(this,x,O),B=this._listenerManager=new o.default,F=new s.default({timeEndpoint:L,leaveEndpoint:z,heartbeatEndpoint:R,setStateEndpoint:K,subscribeEndpoint:U,crypto:x.crypto,config:x.config,listenerManager:B});this.addListener=B.addListener.bind(B),this.removeListener=B.removeListener.bind(B),this.removeAllListeners=B.removeAllListeners.bind(B),this.channelGroups={listGroups:a.default.bind(this,x,u),listChannels:a.default.bind(this,x,p),addChannels:a.default.bind(this,x,d),removeChannels:a.default.bind(this,x,l),deleteGroup:a.default.bind(this,x,c)},this.push={addChannels:a.default.bind(this,x,h),removeChannels:a.default.bind(this,x,g),deleteDevice:a.default.bind(this,x,v),listChannels:a.default.bind(this,x,f)},this.hereNow=a.default.bind(this,x,E),this.whereNow=a.default.bind(this,x,b),this.getState=a.default.bind(this,x,I),this.setState=F.adaptStateChange.bind(F),this.grant=a.default.bind(this,x,P),this.audit=a.default.bind(this,x,V),this.publish=a.default.bind(this,x,C),this.fire=function(e,t){return e.replicate=!1,e.storeInHistory=!1,i.publish(e,t)},this.history=a.default.bind(this,x,D),this.deleteMessages=a.default.bind(this,x,k),this.fetchMessages=a.default.bind(this,x,w),this.time=L,this.subscribe=F.adaptSubscribeChange.bind(F),this.presence=F.adaptPresenceChange.bind(F),this.unsubscribe=F.adaptUnsubscribeChange.bind(F),this.disconnect=F.disconnect.bind(F),this.reconnect=F.reconnect.bind(F),this.destroy=function(e){F.unsubscribeAll(e),F.disconnect()},this.stop=this.destroy,this.unsubscribeAll=F.unsubscribeAll.bind(F),this.getSubscribedChannels=F.getSubscribedChannels.bind(F),this.getSubscribedChannelGroups=F.getSubscribedChannelGroups.bind(F),this.encrypt=M.encrypt.bind(M),this.decrypt=M.decrypt.bind(M),this.getAuthKey=x.config.getAuthKey.bind(x.config),this.setAuthKey=x.config.setAuthKey.bind(x.config),this.setCipherKey=x.config.setCipherKey.bind(x.config),this.getUUID=x.config.getUUID.bind(x.config),this.setUUID=x.config.setUUID.bind(x.config),this.getFilterExpression=x.config.getFilterExpression.bind(x.config),this.setFilterExpression=x.config.setFilterExpression.bind(x.config),this.setHeartbeatInterval=x.config.setHeartbeatInterval.bind(x.config),S.hasModule("proxy")&&(this.setProxy=function(e){x.config.setProxy(e),i.reconnect()})}return i(e,[{key:"getVersion",value:function(){return this._config.getVersion()}},{key:"networkDownDetected",value:function(){this._listenerManager.announceNetworkDown(),this._config.restore?this.disconnect():this.destroy(!0)}},{key:"networkUpDetected",value:function(){this._listenerManager.announceNetworkUp(),this.reconnect()}}],[{key:"generateUUID",value:function(){return z.default.createUUID()}}]),e}();U.OPERATIONS=x.default,U.CATEGORIES=L.default,t.default=U,e.exports=t.default}(Rt,Rt.exports)),Rt.exports}var Ai,Ci={exports:{}};var Di,ki,wi,Ni={exports:{}},Mi={},Oi=(wi||(wi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=a(Pi()),n=a((Ai||(Ai=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();r(Gt());var n=r(Zt());function r(e){return e&&e.__esModule?e:{default:e}}var s=function(){function e(t){var i=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._modules={},Object.keys(t).forEach(function(e){i._modules[e]=t[e].bind(i)})}return i(e,[{key:"init",value:function(e){this._config=e,this._maxSubDomain=20,this._currentSubDomain=Math.floor(Math.random()*this._maxSubDomain),this._providedFQDN=(this._config.secure?"https://":"http://")+this._config.origin,this._coreParams={},this.shiftStandardOrigin()}},{key:"nextOrigin",value:function(){return-1===this._providedFQDN.indexOf("pubsub.")?this._providedFQDN:(this._currentSubDomain=this._currentSubDomain+1,this._currentSubDomain>=this._maxSubDomain&&(this._currentSubDomain=1),e=this._currentSubDomain.toString(),this._providedFQDN.replace("pubsub","ps"+e));var e}},{key:"hasModule",value:function(e){return e in this._modules}},{key:"shiftStandardOrigin",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._standardOrigin=this.nextOrigin(e),this._standardOrigin}},{key:"getStandardOrigin",value:function(){return this._standardOrigin}},{key:"POST",value:function(e,t,i,n){return this._modules.post(e,t,i,n)}},{key:"GET",value:function(e,t,i){return this._modules.get(e,t,i)}},{key:"DELETE",value:function(e,t,i){return this._modules.del(e,t,i)}},{key:"_detectErrorCategory",value:function(e){if("ENOTFOUND"===e.code)return n.default.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return n.default.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return n.default.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return n.default.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return n.default.PNNetworkIssuesCategory;if(e.timeout)return n.default.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return n.default.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return n.default.PNBadRequestCategory;if(e.response.forbidden)return n.default.PNAccessDeniedCategory}return n.default.PNUnknownCategory}}]),e}();t.default=s,e.exports=t.default}(Ci,Ci.exports)),Ci.exports)),r=(Di||(Di=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default={get:function(e){try{return localStorage.getItem(e)}catch(e){return null}},set:function(e,t){try{return localStorage.setItem(e,t)}catch(e){return null}}},e.exports=t.default}(Ni,Ni.exports)),Ni.exports),s=a(r),o=function(){if(ki)return Mi;function e(e){var t=[];for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];null!=n&&t.push(encodeURIComponent(i)+"="+encodeURIComponent(n))}return t.join("&")}function t(e,t,i,n,r,s){var o=this,a=new XMLHttpRequest,d=t+(i?(t.indexOf("?")>=0?"&":"?")+i:""),l=!1,c=!1;function u(e,t){if(!c&&!l){c=!0;var i={};return i.error=null!==e,i.operation=r.operation,a.status&&(i.statusCode=a.status),e?(i.errorData=e,i.category=o._detectErrorCategory(e),s(i,null)):s(i,t)}}a.open(e,d,!0),a.timeout=r.timeout,a.onreadystatechange=function(){if(4===a.readyState){var e=a.status;if(e>=200&&e<300){var t;try{t=JSON.parse(a.responseText)}catch(t){return u({status:e,response:{}},null)}return t&&1===t.error&&t.status&&t.message&&t.service?u({status:t.status,response:{}},null):u(null,t)}return u(0===e?{status:0}:{status:e,response:{badRequest:400===e,forbidden:403===e}},null)}},a.ontimeout=function(){u({timeout:!0},null)},a.onerror=function(){u({status:0},null)};var p=null;null!=n&&(p="string"==typeof n?n:JSON.stringify(n),a.setRequestHeader("Content-Type","application/json"));try{a.send(p)}catch(e){u({status:0},null)}return{abort:function(){l=!0;try{a.abort()}catch(e){}}}}return ki=1,Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.get=function(i,n,r){return t.call(this,"GET",this.getStandardOrigin()+n.url,e(i),null,n,r)},Mi.post=function(i,n,r,s){return t.call(this,"POST",this.getStandardOrigin()+r.url,e(i),n,r,s)},Mi.del=function(i,n,r){return t.call(this,"DELETE",this.getStandardOrigin()+n.url,e(i),null,n,r)},Mi}();function a(e){return e&&e.__esModule?e:{default:e}}function d(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var l=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=e.listenToBrowserNetworkEvents,r=void 0===i||i;e.db=s.default,e.sdkFamily="Web",e.networking=new n.default({del:o.del,get:o.get,post:o.post,sendBeacon:d});var a=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r&&(window.addEventListener("offline",function(){a.networkDownDetected()}),window.addEventListener("online",function(){a.networkUpDetected()})),a}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t}(i.default);t.default=l,e.exports=t.default}(zt,zt.exports)),zt.exports),xi=_(Oi);const Li=["PNAccessDeniedCategory","PNTimeoutCategory","PNNetworkIssuesCategory","PNBadRequestCategory","PNMalformedResponseCategory","PNDecryptionErrorCategory","PNTLSConnectionFailedCategory","PNTLSUntrustedCertificateCategory","PNUnexpectedDisconnectCategory","PNNetworkDownCategory","PNNetworkUpCategory"];class zi extends St{constructor(e){super(e),this.pubnub=void 0,this.channelId=void 0,this._synchronousPublish=!1,this.generateChannel()}connect(e){VizbeeSDK.logger.debug("PubnubSync::appId - "+this.appConfig.appId+" , deviceId - "+this.appConfig.deviceId),void 0===this.pubnub&&(VizbeeSDK.logger.debug("PubnubSync::connect - initializing pubnub ..."),this.pubnub=new xi({publishKey:this.appConfig.pub_key,subscribeKey:this.appConfig.sub_key,ssl:!0}),this.filterOwnMessages());let t=5;this.pubnub.addListener({status:i=>{"PNConnectedCategory"!==i.category&&"PNReconnectedCategory"!==i.category&&"PNNetworkUpCategory"!==i.category||(t=5),"PNConnectedCategory"===i.category?(this.dispatchReceive(new _t(It.SYNC_CONNECT,{})),e(!0)):Li.indexOf(i.category)>=0&&(VizbeeSDK.logger.error("PubnubSync.Connect - PUBNUB.subscribe() error = ",i," with retries = ",t),t>0&&(t--,this.subscribePubnub()))},message:this.messageHandler.bind(this),presence:e=>{}}),this.subscribePubnub()}disconnect(){this.pubnub&&this.channelId&&(VizbeeSDK.logger.debug("PubnubSync::disconnect - invoking disconnect"),this.pubnub.unsubscribe({channels:[this.channelId]}),this.pubnub=void 0,super.disconnect())}send(e){if(this.pubnub&&this.channelId){if(this._synchronousPublish)return void this.sendSynchronously(e);this.pubnub.publish({message:e,channel:this.channelId,sendByPost:!1,storeInHistory:!1,meta:{uuid:this.pubnub.getUUID()}},(e,t)=>{e.error&&VizbeeSDK.logger.error("CommManager:CommManager - PUBNUB.publish() error")})}}enableSynchronousPublish(){this._synchronousPublish=!0}sendSynchronously(e){if(this.pubnub&&this.channelId)try{var t=this.appConfig.pub_key,i=this.appConfig.sub_key,n=this.pubnub.getUUID(),r="?uuid="+encodeURIComponent(n)+"&store=0&meta="+encodeURIComponent(JSON.stringify({uuid:n})),s="https://ps.pndsn.com/publish/"+t+"/"+i+"/0/"+this.channelId+"/0",o=JSON.stringify(e),a=s+"/"+encodeURIComponent(o)+r;if("function"==typeof fetch)return fetch(a,{method:"GET",keepalive:!0,mode:"no-cors"}).catch(function(){}),void VizbeeSDK.logger.debug("PubnubSync::sendSynchronously - sent via keepalive fetch");if("undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(s+r,o))return void VizbeeSDK.logger.debug("PubnubSync::sendSynchronously - sent via sendBeacon");var d=new XMLHttpRequest;d.open("GET",a,!1),d.send(),VizbeeSDK.logger.debug("PubnubSync::sendSynchronously - sent via synchronous XHR")}catch(e){VizbeeSDK.logger.error("PubnubSync::sendSynchronously - error publishing on teardown",e)}}generateChannel(){this.appConfig&&(this.channelId=(""+Lt(this.appConfig.appId+":"+this.appConfig.deviceId)).toLowerCase()),VizbeeSDK.logger.info("PubnubSync::generateChannel",this.channelId)}subscribePubnub(){VizbeeSDK.logger.debug("PubnubSync::subscribePubnub - invoking pubnub subscribe"),this.pubnub&&this.channelId&&(VizbeeSDK.logger.debug("PubnubSync::subscribePubnub - subscribing..."),this.pubnub.subscribe({channels:[this.channelId]}))}filterOwnMessages(){if(this.pubnub){let e="uuid != '";e=e.concat(this.pubnub.getUUID()).concat("'"),this.pubnub.setFilterExpression(e)}}messageHandler(e,t,i){VizbeeSDK.logger.verbose("PubnubSync::messageHandler",e);let n=e?e.message:{};At.verifyDeviceId(),this.dispatchReceive(new _t(It.SYNC_MESSAGE,n))}}class Ri extends St{constructor(e){super(e),this.syncInstances=[]}connect(e){for(let t of this.syncInstances)t.connect(e)}disconnect(){for(let e of this.syncInstances)e.disconnect()}send(e){for(let t of this.syncInstances)t.send(e)}addSyncInstance(e){this.syncInstances.push(e),this.setReceiveListener(e)}setReceiveListener(e){e.onReceive=e=>{this.dispatchReceive.call(this,e)}}}class Ki extends St{constructor(e,t){if(!(e instanceof St))throw new TypeError("BaseSyncExtension::constructor() - classToExtend must be instance of BaseSync.");super(t),this.extendedClass=e,this.extendedClass.onReceive=e=>{this.onReceiveHandler.call(this,e)}}connect(e){this.extendedClass.connect(e)}disconnect(){this.extendedClass.disconnect()}send(e){VizbeeSDK.logger.verbose(this._getLogPrefix("send")+" - FORWARDING OUT send message",e),this.extendedClass.send(e)}get baseSync(){return this.extendedClass instanceof Ki?this.extendedClass.baseSync:this.extendedClass}onReceiveHandler(e){if(!e||!e.data)return void VizbeeSDK.logger.warn(this._getLogPrefix("onReceive")+" - NULL receive event",e);let t;e.type===It.SYNC_MESSAGE?(t=this.handleSyncReceiveEvent(e),t?(VizbeeSDK.logger.verbose(this._getLogPrefix("onReceive")+" - FORWARDING IN sync receive event",t),this.dispatchReceive.call(this,t)):VizbeeSDK.logger.warn(this._getLogPrefix("onReceive")+" - DROPPING receive event",e)):(t=this.handleNonSyncReceiveEvent(e),t?(VizbeeSDK.logger.verbose(this._getLogPrefix("onReceive")+" - FORWARDING IN non-sync receive event",t),this.dispatchReceive.call(this,t)):VizbeeSDK.logger.warn(this._getLogPrefix("onReceive")+" - DROPPING non-sync receive event",e))}handleSyncReceiveEvent(e){return e}handleNonSyncReceiveEvent(e){return e}getClassName(){return this.constructor.name}_getLogPrefix(e){return(this.getClassName()+"::"+e+" ").slice(0,40)}}class Ui extends Ki{constructor(e,t){super(e,t),this.txIdMap={}}handleSyncReceiveEvent(e){if(this.isValidMessage(e.data))return e}isValidMessage(e){let t,i,n,r,s=!1;if(!e)return VizbeeSDK.logger.warn("SanitizeHeaderRecvExtension:isValidMessage - invalid message",e),s;if(!T.isObject(e.h))return VizbeeSDK.logger.warn("SanitizeHeaderRecvExtension:isValidMessage - invalid message head",e),s;if(t=e.h.id,i=e.h.tx,n=e.h.ss,!T.isString(t))return VizbeeSDK.logger.error("SanitizeHeaderRecvExtension:isValidMessage - invalid message id",t,e),s;if(!T.isNumber(i))return VizbeeSDK.logger.error("SanitizeHeaderRecvExtension:isValidMessage - invalid message tx",i,e),s;if(r=t,n&&(r=n+r),0===i)this.txIdMap[r]=i;else{if(this.txIdMap[r]>=i)return VizbeeSDK.logger.warn("SanitizeHeaderRecvExtension:isValidMessage - duplicate message",i,this.txIdMap[r]),s;this.txIdMap[r]=i}return!0}}class Bi extends Ki{constructor(e,t){super(e,t)}handleSyncReceiveEvent(e){if(this.isValidMessage(e.data))return this.sanitize(e)}isValidMessage(e){let t=!1,i=e.b;if(!T.isObject(i))return t;if(!T.isObject(i.cmd))return t;if(!T.isString(i.cmd.name)||!T.isString(i.cmd.ns))return t;if("start_video"==i.cmd.name){let e=i.vinfo;if(!T.isObject(e))return t;if(!T.isString(e.id)&&!T.isString(e.url))return t}return t=!0,t}sanitize(e){let t=e.data,i=t.b.cmd;return i.name=i.name.toLowerCase(),i.ns=i.ns.toLowerCase(),i.type=i.type?i.type.toLowerCase():null,"exit"==i.name&&(i.param=i.param.toLowerCase()),t.b.cmd=i,e.data=t,e}}class Fi extends Ki{constructor(e,t){super(e,t)}getActiveSenders(){throw new TypeError("BaseSyncWithPresence::getSenders() - Abstract method.")}getActiveSendersCount(){throw new TypeError("BaseSyncWithPresence::getActiveSendersCount() - Abstract method.")}}class Gi extends Fi{constructor(e,t){if(!(e instanceof Fi))throw new TypeError("BaseSyncWithPresenceExtension::constructor() - classToExtend must be instance of BaseSyncWithPresence.");super(e,t)}getActiveSenders(){return this.extendedClass.getActiveSenders()}getActiveSendersCount(){return this.extendedClass.getActiveSendersCount()}}class Hi{static decodeVideoInfo(e){if(!e)return;if(!e.vinfo)return;let t={islive:!1,starttime:0,isContinuedVideo:!1};if(t.id=e.vinfo.id,t.videourl=e.vinfo.url,e.vinfo.islive&&(t.islive=e.vinfo.islive),e.vinfo.deeplink&&(t.deeplink=e.vinfo.deeplink),!T.isUndefined(e.cmd)){var i=0;T.isUndefined(e.cmd.param)||(i=parseInt(e.cmd.param,10),isNaN(i)&&(i=0),i<0&&(i=0)),t.starttime=i}if(e.vinfoext){if(e.vinfoext.cuepoints&&(t.cuepoints=e.vinfoext.cuepoints),e.vinfoext.title&&(t.title=e.vinfoext.title),e.vinfoext.subtitle&&(t.subtitle=e.vinfoext.subtitle),e.vinfoext.tracks){let i=T.get(e,["vinfoext","tracks","currentAudioTrack"]);i&&(t.preferredTracks={},t.preferredTracks.currentAudioTrack={label:i.displayName,lang:i.languageCode,id:i.screenTrackId})}e.vinfoext.imgurl&&(t.imgurl=e.vinfoext.imgurl),e.vinfoext.desc&&(t.desc=e.vinfoext.desc),e.vinfoext.customstreaminfo&&(t.customstreaminfo=e.vinfoext.customstreaminfo),e.vinfoext.custommetadata&&(t.custommetadata=e.vinfoext.custommetadata),e.vinfoext.drmtype&&(t.drmtype=e.vinfoext.drmtype),e.vinfoext.protocoltype&&(t.protocoltype=e.vinfoext.protocoltype),e.vinfoext.drmlicenseurl&&(t.drmlicenseurl=e.vinfoext.drmlicenseurl),e.vinfoext.drmcustomdata&&(t.drmcustomdata=e.vinfoext.drmcustomdata)}return t}static encodeVideoInfo(e){if(!e)return;let t={};return t.vinfo={id:e.id,islive:e.islive,url:e.videourl},t.vinfoext={videostarttime:e.starttime||0,imgurl:e.imgurl?e.imgurl:"",title:e.title?e.title:"",subtitle:e.subtitle?e.subtitle:"",desc:e.desc?e.desc:"",isContinuedVideo:null!=e.isContinuedVideo&&e.isContinuedVideo,customstreaminfo:e.customstreaminfo?e.customstreaminfo:{},custommetadata:e.custommetadata?e.custommetadata:{},drmtype:e.drmtype?e.drmtype:"NONE",drmlicenseurl:e.drmlicenseurl?e.drmlicenseurl:"",drmcustomdata:e.drmcustomdata?e.drmcustomdata:{},cuepoints:e.cuepoints?e.cuepoints:[]},t}static addInfoFromHeader(e,t){if(!e||!t)return e;let i=T.clone(t);return e.senderInfo=T.omit(i,["tx","ss"]),e}static encodeEventCmd(e){if(!e)return;let t={cmd:{ns:"video",type:"req",name:"event",param:""},einfo:{type:e.type,data:e.data}};return{type:It.SYNC_MESSAGE,data:{h:{},b:t}}}static encodeStartVideoCmd(e){if(!e)return;e.starttime=e.starttime||0;let t={cmd:{ns:"video",type:"req",name:"start_video",param:e.starttime},internal:{videoInfo:e,startVideoSource:"queue_manager"}};return{type:It.SYNC_MESSAGE,data:{h:{},b:t}}}static encodeVideoStatus(e){if(!e)return;let t={cmd:{name:"status",ns:"video",type:"upd"},vstatus:{du:0,id:e.id,po:-1,st:"BUFFERING",vol:100,cc:0,tr:{},er:{}}};return t=T.extend(t,Hi.encodeVideoInfo(e)),t}}class Wi extends Gi{constructor(e,t){super(e,t)}handleSyncReceiveEvent(e){if("start_video"==e.data.b.cmd.name){let t=Hi.decodeVideoInfo(e.data.b);t&&(t=Hi.addInfoFromHeader(t,e.data.h)),e.data.b.internal={videoInfo:t,startVideoSource:"default",queueInfo:this._createQueueInfo(e.data)}}return e}_createQueueInfo(e){let t={id:"default",name:"default",description:"default",startIndex:0,items:[]},i=Hi.decodeVideoInfo(e.b);return i&&(i=Hi.addInfoFromHeader(i,e.h)),t.items.push(i),t}}class ji extends Fi{constructor(e,t){VizbeeSDK.logger.d("UpdatePresenceRecvExtension","constructor"),super(e,t),this.currentAppId=t.appId,this._sentFirstHelloCheck=!1,this._sentSecondHelloCheck=!1,this._senderMap={},this._presenceIntervalTimer=void 0,this._previousSenderMapCount=0,this._startPresenceTimer()}getActiveSenders(){return this._senderMap}getActiveSendersCount(){return Object.keys(this._senderMap||{}).length}disconnect(){VizbeeSDK.logger.d("UpdatePresenceRecvExtension","disconnect"),this._senderMap={},this._previousSenderMapCount=0,this._stopPresenceTimer(),super.disconnect()}handleSyncReceiveEvent(e){let t=e.data;return"exit"===t.b.cmd.name?this._senderMap=T.omit(this._senderMap,T.keys(this._senderMap).filter(e=>e===t.h.id)):(this._sentFirstHelloCheck=!1,this._sentSecondHelloCheck=!1,this._senderMap[t.h.id]=t.h,this._senderMap[t.h.id].appId=this.currentAppId,this._senderMap[t.h.id].lastMsgReceivedTimeInMs=Date.now(),this._startPresenceTimer()),e}_startPresenceTimer(){this._stopPresenceTimer(),this._presenceIntervalTimer=window.setInterval(()=>{this._updatePresence()},1e3)}_stopPresenceTimer(){window.clearInterval(this._presenceIntervalTimer),this._presenceIntervalTimer=void 0}_checkForSenders(){!this._sentFirstHelloCheck&&this._shouldSendHelloCheckMessage(15e3)?(this._sendHelloCheckMessage(),this._sentFirstHelloCheck=!0):!this._sentSecondHelloCheck&&this._shouldSendHelloCheckMessage(25e3)&&(this._sendHelloCheckMessage(),this._sentSecondHelloCheck=!0)}_shouldSendHelloCheckMessage(e){if(0==Object.keys(this._senderMap||{}).length)return!1;let t=Date.now(),i=T.keys(this._senderMap).filter(i=>this._senderMap[i]&&null!=this._senderMap[i].lastMsgReceivedTimeInMs&&t-this._senderMap[i].lastMsgReceivedTimeInMs>e);return Object.keys(i).length>0}_sendHelloCheckMessage(){this.dispatchReceive(new _t(It.SYNC_MESSAGE,{b:{cmd:{ns:"video",name:"hello",type:"int"},hstatus:{id:this.appConfig.deviceId,type:"SCREEN",vip:"false"}}}))}_updatePresence(){this._checkForSenders();let e=Date.now();if(this._senderMap=T.omit(this._senderMap,T.keys(this._senderMap).filter(t=>this._senderMap[t]&&null!=this._senderMap[t].lastMsgReceivedTimeInMs&&e-this._senderMap[t].lastMsgReceivedTimeInMs>3e4)),0==Object.keys(this._senderMap||{}).length)return VizbeeSDK.logger.d("UpdatePresenceRecvExtension","_updatePresence","there are no senders now"),this._stopPresenceTimer(),this.dispatchReceive(new _t(It.SYNC_PRESENCE,this._senderMap)),void(this._previousSenderMapCount=0);let t=Object.keys(this._senderMap).length;t!=this._previousSenderMapCount&&(VizbeeSDK.logger.d("UpdatePresenceRecvExtension","_updatePresence","there is a change in the senders connected"),this._previousSenderMapCount=t,this.dispatchReceive(new _t(It.SYNC_PRESENCE,this._senderMap)))}}class qi extends Gi{constructor(e,t){super(e,t),this.tx=0,this.sessionId=this.createTimestamp()}send(e){super.send(this.createMessage(null,e))}createMessage(e,t){return(t=t||{}).vers=1,{h:e=T.extend(this.createHeader(),e),b:t}}createHeader(){return this.tx++,{tx:this.tx,id:this.appConfig.senderId||this.appConfig.deviceId,ss:this.sessionId,app:this.appConfig.appId,ssinfo:this.getSenderSessionInfo()}}createTimestamp(){let e=new Date;return e.getFullYear()+":"+("0"+(e.getMonth()+1)).slice(-2)+":"+("0"+e.getDate()).slice(-2)+":"+("0"+e.getHours()).slice(-2)+":"+("0"+e.getMinutes()).slice(-2)+":"+("0"+e.getSeconds()).slice(-2)+":"+("0"+e.getMilliseconds()).slice(-3)}getSenderSessionInfo(){return{SCREEN_IDFA:this.appConfig.screenIdfa,SCREEN_IDFV:this.appConfig.screenIdfv,SCREEN_DEVICE_TYPE:this.appConfig.screenDeviceType,SCREEN_DEVICE_ID:this.appConfig.screenDeviceId,SCREEN_DEVICE_FRIENDLYNAME:this.appConfig.screenFriendlyName}}}const Yi=["BUFFERING","PLAYING","PAUSED_BY_USER","INTERRUPTED","FINISHED","FAILED"];class Ji extends Gi{constructor(e,t){super(e,t),this.appConfig=t,this.shouldSupportLiveDVR=T.get(t,["features","shouldSupportLiveDVR"],!1),this.liveDVRMinBufferInMs=T.get(t,["features","liveDVRMinBufferInMs"],3e5)}send(e){if(!e||!e.cmd)return void super.send(e);let t=e;"status"==e.cmd.name&&(t=this.interceptVideoStatus(e)),super.send(t)}interceptVideoStatus(e){return Yi.includes(e.vstatus.st)&&e.vinfo.islive&&(e.vinfoext||(e.vinfoext={}),!0===e.vinfoext.isdvrsupported||(!this.shouldSupportLiveDVR||e.vstatus.du<this.liveDVRMinBufferInMs?(e.vinfoext.isdvrsupported=!1,e.vstatus.po=-1,e.vstatus.du=0):e.vinfoext.isdvrsupported=!0)),e}}class $i{static setItem(e,t,i,n,r,s,o){if(e)if("undefined"!=typeof Storage)vizbee.logger.debug("StorageUtil::setItem - Storage supported!"),"session"==i?(vizbee.logger.debug("StorageUtil::setItem - storing in session!"),sessionStorage.setItem(e,t)):(vizbee.logger.debug("StorageUtil::setItem - storing in local!"),localStorage.setItem(e,t));else{if(vizbee.logger.debug("StorageUtil::setItem - Storage NOT supported!"),"session"==i)return;vizbee.logger.debug("StorageUtil::setItem - storing in cookies!"),D.docCookies.setItem(e,t,n,r,s,o)}}static getItem(e,t){if(e){if("undefined"!=typeof Storage)return vizbee.logger.debug("StorageUtil::getItem - Storage supported!"),"session"==t?(vizbee.logger.debug("StorageUtil::getItem - getting from session!"),sessionStorage.getItem(e)):(vizbee.logger.debug("StorageUtil::getItem - getting from local!"),localStorage.getItem(e)?sessionStorage.getItem(e):localStorage.getItem(e));if(vizbee.logger.debug("StorageUtil::getItem - Storage NOT supported!"),"session"!=t)return vizbee.logger.debug("StorageUtil::getItem - getting from cookies!"),D.docCookies.getItem(e)}}static removeItem(e,t,i,n){if(e)if("undefined"!=typeof Storage)"session"==t?sessionStorage.removeItem(e):localStorage.removeItem(e)||sessionStorage.removeItem(e);else{if("session"==t)return;D.docCookies.removeItem(e,i,n)}}}class Qi{constructor(e){this.senderConfig=e}track(e,t){if(!e||!t||!this.senderConfig.url)return;if(VizbeeSDK.logger.d(`${this.constructor.name}`,`track() - tracking event ${e}, ${JSON.stringify(t)}`),!this.shouldTrack(e))return;if(t=this.filterProperties(t),0==Object.keys(t).length)return;let i,n,r={event:e,properties:t},s=this._getBase64String(r),o=this._getURIEncodedString(s),a="GET";this._needPostRequest(o)?(i=this.senderConfig.url,a="POST",n=JSON.stringify({data:o})):(i=this.senderConfig.url+"?data="+o,a="GET",n=void 0),VizbeeSDK.logger.d(`${this.constructor.name}`,`track() - sending metrics request: URL ${i}, Method ${a}, Data ${n}`),D.xhr({url:i,method:a,data:n,timeout:1e4,retries:this.senderConfig.networkRetries}).then(e=>{e.error?VizbeeSDK.logger.e(`${this.constructor.name}`,"track - ERROR"):VizbeeSDK.logger.d(`${this.constructor.name}`,`track - SUCCESS: ${e}`)}).catch(e=>{VizbeeSDK.logger.d(`${this.constructor.name}`,`track - ERROR=${e}`)})}shouldTrack(e){return VizbeeSDK.logger.d(`${this.constructor.name}`,`shouldTrack - Filtering events with regex = ${this.senderConfig.eventFilter}`),!this.senderConfig.eventFilter||new RegExp(this.senderConfig.eventFilter,"i").test(e)}filterProperties(e){if(VizbeeSDK.logger.d(`${this.constructor.name}`,`filterProperties - Filtering properties with regex = ${this.senderConfig.attributeFilter}`),!this.senderConfig.attributeFilter)return e;e=e||{},e=JSON.parse(JSON.stringify(e));for(var t=new RegExp(this.senderConfig.attributeFilter,"i"),i=Object.keys(e),n=0;n<i.length;n++){var r=i[n];t.test(r)||delete e[r]}return e}_getBase64String(e){return btoa(unescape(encodeURIComponent(JSON.stringify(e))))}_getURIEncodedString(e){return window.encodeURIComponent(e)}_needPostRequest(e){return!!(e&&e.length>1e4)}}class Zi extends Qi{constructor(e){let t={};e.mixpanel_url&&(t={eventFilter:e.mixpanel_filter,token:e.mixpanel_token,attributeFilter:e.attribute_filter,url:e.mixpanel_url,networkRetries:0}),super(t)}track(e,t){(t=t||{}).token=this.senderConfig.token,super.track(e,t)}}class Xi extends Qi{constructor(e){let t={};e.vizbee_url&&(t={url:e.vizbee_url,attributeFilter:e.attribute_filter,eventFilter:e.vizbee_filter,networkRetries:0}),super(t)}}class en{constructor(e){this.senders=[],e&&e.vizbee_url&&this.senders.push(new Xi(e)),e&&e.mixpanel_url&&e.mixpanel_token&&this.senders.push(new Zi(e))}track(e,t){VizbeeSDK.logger.d(`${this.constructor.name}`,"track",e,t),T.each(this.senders,i=>{i.track(e,T.clone(t))})}}const tn="UNKNOWN",nn="NOT_FOUND";var rn=new class{constructor(){this.config={},this.commonProperties={},this.attributesProvidersList=[],this.isInitialized=!1,this.needToSetDistinctIdForVideoEvents=!0,this.isScreenLaunchedTracked=!1}init(e){if(e&&this.commonProperties)if(VizbeeSDK.logger.d("MetricsManager","init",e.appId,this.commonProperties.APP_ID),this.isInitialized&&this.commonProperties.APP_ID==e.appId)VizbeeSDK.logger.d("MetricsManager","init","already initialized");else{this.config=e,this.metricsRouter=new en(e.metricsParams),this.appSessionId=Math.floor(1e10*Math.random()).toString()+"_"+Date.now(),this.screenSdkId=$i.getItem("SCREEN_SDK_ID"),this.screenSdkId?VizbeeSDK.logger.d("MetricsManager::init","SCREEN_SDK_ID -> AVAILABLE -> REUSING IT"):(VizbeeSDK.logger.d("MetricsManager::init","SCREEN_SDK_ID -> NOT_AVAILABLE"),this.screenSdkId=Math.floor(1e10*Math.random()).toString()+"_"+Date.now(),$i.setItem("SCREEN_SDK_ID",this.screenSdkId,"local",31536e3,"/"));var t=this.prepareCommonProperties(e);this.setCommonProperties(t),e.customAttributesForMetrics&&this.setCustomProperties(e.customAttributesForMetrics),this.isInitialized=!0}else VizbeeSDK.logger.e("MetricsManager","init","called with empty config!")}refreshLaunchParamProperties(){if(VizbeeTV.tv.launchParamsDeferral){const e=VizbeeTV.tv.launchParamsDeferral.isLaunchedbyVizbee()||!1;this.commonProperties.SCREEN_LAUNCHED_WITH_VIZBEE=e,this.commonProperties.SCREEN_VZB_LAUNCH_PARAM=e?"y":nn}}prepareCommonProperties(e){var t,i,n,r={appId:e.appId,deviceId:e.deviceId,deviceType:VizbeeTV.tv.cloudPlatformName,distinctId:e.deviceId,externalIp:e.externalIp,ipv6Address:e.ipv6Address,sdkVersion:window.VZB?window.VZB.VERSION:"",appSessionId:this.appSessionId,screenSdkId:this.screenSdkId,timestamp:Date.now(),timezoneOffset:(t=-(new Date).getTimezoneOffset(),i=t>=0?"+":"-",n=Math.abs(t),"GMT"+i+("0"+Math.floor(n/60)).slice(-2)+":"+("0"+n%60).slice(-2))};return VizbeeTV.tv.deviceInfo&&(VizbeeTV.tv.deviceInfo.deviceId&&VizbeeTV.tv.deviceInfo.deviceId!=tn&&(r.deviceId=VizbeeTV.tv.deviceInfo.deviceId,r.distinctId=VizbeeTV.tv.deviceInfo.deviceId),r.macAddress=VizbeeTV.tv.deviceInfo.macAddress,r.deviceMake=VizbeeTV.tv.deviceInfo.make,r.deviceModel=VizbeeTV.tv.deviceInfo.model,r.deviceSerialNumber=VizbeeTV.tv.deviceInfo.serialNumber,r.friendlyName=VizbeeTV.tv.deviceInfo.friendlyName,r.osVersion=T.get(VizbeeTV.tv.deviceInfo,["os","version"],tn),r.osNativeVersion=T.get(VizbeeTV.tv.deviceInfo,["os","sdkVersion"],tn)),VizbeeTV.tv.adId&&(r.adId=VizbeeTV.tv.adId),null!=VizbeeTV.tv.isAdTrackingDisabled&&(r.isAdTrackingDisabled=VizbeeTV.tv.isAdTrackingDisabled),VizbeeTV.tv.networkInfo&&(r.internalIp=VizbeeTV.tv.networkInfo.internalIP,r.bssid=VizbeeTV.tv.networkInfo.bssid,r.ssid=VizbeeTV.tv.networkInfo.ssid,r.isWifiConnected=VizbeeTV.tv.networkInfo.isWifiConnected,r.connectionType=VizbeeTV.tv.networkInfo.connectionType),VizbeeTV.tv.launchParamsDeferral&&(r.isLaunchedWithVizbee=VizbeeTV.tv.launchParamsDeferral.isLaunchedbyVizbee()||!1),r}setCommonProperties(e){VizbeeSDK.logger.d("MetricsManager","setCommonProperties"),this.commonProperties.SCREEN_DEVICE_USERAGENT=tn,this.commonProperties.SCREEN_IDFV=tn,this.commonProperties.SCREEN_HOMESSO_USER_INFO={user_login:tn,user_login_type:tn,user_name:tn,user_subscription_renewal_type:tn,user_subscription_type:tn,user_subscription_value:tn},e.appId&&(this.commonProperties.APP_ID=e.appId),e.externalIp&&(this.commonProperties.EXTERNAL_IP_ADDRESS=e.externalIp),e.ipv6Address&&(this.commonProperties.IPV6_ADDRESS=e.ipv6Address),e.distinctId&&(this.commonProperties.distinct_id=e.distinctId),e.deviceId&&(this.commonProperties.SCREEN_DEVICE_ID=e.deviceId),e.appSessionId&&(this.commonProperties.SCREEN_APP_SESSION_ID=e.appSessionId),e.screenSdkId&&(this.commonProperties.SCREEN_SDK_ID=e.screenSdkId),e.internalIp&&(this.commonProperties.INTERNAL_IP_ADDRESS=e.internalIp,this.commonProperties.SCREEN_INTERNAL_IP=e.internalIp),"isWifiConnected"in e&&(this.commonProperties.WIFI_CONNECTED=e.isWifiConnected),e.connectionType&&(this.commonProperties.CONNECTION_TYPE=e.connectionType),e.bssid&&(this.commonProperties.WIFI_BSSID=e.bssid),e.ssid&&(this.commonProperties.WIFI_SSID=e.ssid),e.adId&&(this.commonProperties.SCREEN_IDFA=e.adId),null!=e.isAdTrackingDisabled&&(this.commonProperties.SCREEN_LIMIT_AD_TRACKING=e.isAdTrackingDisabled),e.macAddress&&(this.commonProperties.SCREEN_MAC_ADDRESS=e.macAddress),navigator&&navigator.userAgent&&(this.commonProperties.SCREEN_DEVICE_USERAGENT=navigator.userAgent),e.deviceType&&(this.commonProperties.SCREEN_DEVICE_TYPE=e.deviceType),e.deviceMake&&(this.commonProperties.SCREEN_DEVICE_MAKE=e.deviceMake),e.deviceModel&&(this.commonProperties.SCREEN_DEVICE_MODEL=e.deviceModel),e.deviceSerialNumber&&(this.commonProperties.SCREEN_SERIAL_NUMBER=e.deviceSerialNumber),e.friendlyName&&(this.commonProperties.SCREEN_FRIENDLY_NAME=e.friendlyName),e.osNativeVersion&&(this.commonProperties.SCREEN_NATIVE_OS_VERSION=e.osNativeVersion),e.osVersion&&(this.commonProperties.SCREEN_OS_VERSION=e.osVersion),null!=e.isLaunchedWithVizbee&&(this.commonProperties.SCREEN_LAUNCHED_WITH_VIZBEE=e.isLaunchedWithVizbee),this.commonProperties.SCREEN_LAUNCHED_WITH_VIZBEE?this.commonProperties.SCREEN_VZB_LAUNCH_PARAM="y":this.commonProperties.SCREEN_VZB_LAUNCH_PARAM=nn,e.sdkVersion&&(this.commonProperties.SCREEN_SDK_VERSION=e.sdkVersion),e.timestamp&&(this.commonProperties.VZB_TIMESTAMP=e.timestamp),e.timezoneOffset&&(this.commonProperties.TIMEZONE=e.timezoneOffset),e.SCREEN_HOMESSO_USER_INFO&&(this.commonProperties.SCREEN_HOMESSO_USER_INFO=e.SCREEN_HOMESSO_USER_INFO)}setAttributesProviderProperties(e,t){if(0==this.attributesProvidersList.length)return void t(e);const i=this.attributesProvidersList.map(e=>e.provider.getAttributes());Promise.all(i).then(i=>{i.forEach(t=>{t&&(e=T.extend(e,t))}),t(e)}).catch(i=>{console.error("Error getting attributes:",i),t(e)})}setCustomProperties(e){VizbeeSDK.logger.d("MetricsManager","setCustomProperties"),T.each(e,(e,t)=>{this.commonProperties["CUSTOM_"+t]=e})}addProvider(e,t){VizbeeSDK.logger.d("MetricsManager","addProvider"),this.attributesProvidersList.push({provider:e,filterRegEx:t})}removeProvider(e){VizbeeSDK.logger.d("MetricsManager","removeProvider"),this.attributesProvidersList=T.reject(this.attributesProvidersList,t=>t.provider==e)}trackEvent(e,t){this.shouldTrack(e,t)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackEvent",e);let i=T.extend({},this.commonProperties,t);this.track(e,i)})}trackScreenLaunched(e){!this.isScreenLaunchedTracked&&this.shouldTrack("SCREEN_LAUNCHED",this.commonProperties)&&(this.isScreenLaunchedTracked=!0,this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenLaunched");let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),e||{});this.track("SCREEN_LAUNCHED",t)}))}trackScreenTVViewLoad(e){this.shouldTrack("SCREEN_TV_VIEW_LOAD",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewLoad"),this.commonProperties.distinct_id=this.commonProperties.APP_ID+":"+this.commonProperties.SCREEN_DEVICE_TYPE+":"+D.uuidv4()+":"+Date.now(),this.needToSetDistinctIdForVideoEvents=!1;let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildNewScreenTVViewProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track("SCREEN_TV_VIEW_LOAD",t)})}trackScreenTVViewStart(e){this.shouldTrack("SCREEN_TV_VIEW_START",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewStart"),this.needToSetDistinctIdForVideoEvents&&(this.commonProperties.distinct_id&&-1==this.commonProperties.distinct_id.indexOf(this.commonProperties.SCREEN_DEVICE_TYPE)&&(this.commonProperties.APP_ID,this.commonProperties.SCREEN_DEVICE_TYPE,D.uuidv4(),Date.now()),this.needToSetDistinctIdForVideoEvents=!0);let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewStartProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildScreenTVViewStartTimeQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track("SCREEN_TV_VIEW_START",t)})}trackScreenTVViewPause(e){this.shouldTrack("SCREEN_TV_VIEW_PAUSE",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewPause");let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewDurationProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track("SCREEN_TV_VIEW_PAUSE",t)})}trackScreenTVViewResume(e){this.shouldTrack("SCREEN_TV_VIEW_RESUME",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewResume");let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewResumeProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track("SCREEN_TV_VIEW_RESUME",t)})}trackScreenTVViewDuration(e){this.shouldTrack("SCREEN_TV_VIEW_DURATION",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewDuration");let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewDurationProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));t.SCREEN_HOMESSO_USER_INFO=void 0,this.track("SCREEN_TV_VIEW_DURATION",t)})}trackScreenTVViewError(e){let t="SCREEN_TV_VIEW_ERROR";this.shouldTrack(t,e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewError");let i=T.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewErrorProperties(e),this.buildScreenTVViewDurationProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track(t,i)})}trackScreenAdView(e){this.shouldTrack("SCREEN_AD_VIEW",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenAdView","tracking SCREEN_AD_VIEW");let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenAdViewProperties(e));this.track("SCREEN_AD_VIEW",t)})}trackScreenRemoteConnected(e){e&&this.shouldTrack("SCREEN_REMOTE_CONNECTED")&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenRemoteConnected");let t=T.extend({},this.commonProperties,this.buildPlayerProperties(),this._buildSenderProperties(e));this.track("SCREEN_REMOTE_CONNECTED",t)})}trackScreenTVSignin(e){e&&this.shouldTrack("SCREEN_TV_SIGNIN")&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVSignin");let t=T.extend({},this.commonProperties,this.buildScreenTVSigninProperties(e));this.track("SCREEN_TV_SIGNIN",t)})}_buildSenderProperties(e){return e&&e.ssinfo?{CONNECTED_REMOTE:e.ssinfo}:{}}metricsConfig(){return this.config.metricsParams}isVideoEvent(e){return-1!=["SCREEN_TV_VIEW_LOAD","SCREEN_TV_VIEW_START","SCREEN_TV_VIEW_PAUSE","SCREEN_TV_VIEW_RESUME","SCREEN_TV_VIEW_DURATION","SCREEN_AD_VIEW"].indexOf(e)}isValidContinuityEvent(e){return-1!=["SCREEN_LAUNCHED","SCREEN_REMOTE_CONNECTED","SCREEN_TV_SIGNIN","SCREEN_TV_VIEW_LOAD","SCREEN_TV_VIEW_START","SCREEN_TV_VIEW_PAUSE","SCREEN_TV_VIEW_RESUME","SCREEN_TV_VIEW_DURATION","SCREEN_TV_VIEW_ERROR","SCREEN_AD_VIEW"].indexOf(e)}isValidHomeSSOEvent(e){return-1!=["SCREEN_HOMESSO_SIGNIN_RECEIVED","SCREEN_HOMESSO_SIGNIN_STATUS"].indexOf(e)}shouldTrack(e,t){if(0==Object.keys(this.config).length)return void VizbeeSDK.logger.e("MetricsManager","shouldTrack","called with empty config!");let i=!0;return this.isValidContinuityEvent(e)?this.isVideoEvent(e)&&this.metricsConfig()&&this.metricsConfig().shouldSendViewEventsOnlyOnCast&&t&&!t.isVideoLaunchedFromPhone&&(i=!1):this.isValidHomeSSOEvent(e)||(i=!1),i}track(e,t){this.metricsRouter.track(e,t)}buildPlayerProperties(){let e={PLAYER_NAME:"UNKNOWN"};return VizbeeTV.tv.player&&(e.PLAYER_NAME=VizbeeTV.tv.player.getName()),e}buildVideoProperties(e){return{VIDEO_ID:e.videoId,VIDEO_TITLE:e.videoTitle,VIDEO_START_TIME:e.videoStartTime,VIDEO_DURATION_MS:Math.round(e.videoDuration),IS_LIVE:e.isLive,IS_CONTINUED_VIEW:e.isContinuedView,IS_VIDEO_LAUNCHED_FROM_PHONE:e.isVideoLaunchedFromPhone}}buildNewScreenTVViewProperties(e){return this.buildVideoProperties(e)}buildScreenTVViewStartProperties(e){return this.buildVideoProperties(e)}buildScreenTVViewResumeProperties(e){return T.extend({VIDEO_PAUSED_TIME_MS:Math.round(e.videoPausedTimeInMs)},this.buildScreenTVViewDurationProperties(e))}buildScreenTVViewDurationProperties(e){return T.extend({VIDEO_POSITION_MS:Math.round(e.videoPosition),VIDEO_POSITION_MIN:e.videoPostitionMin,VIDEO_ELAPSED_TIME_MS:Math.round(e.videoElapsedTime),VIDEO_ELAPSED_TIME_MIN:e.videoElapsedTimeMin},this.buildVideoProperties(e))}buildStreamInfoAndMetadataProperties(e){let t={};try{if(e.customStreamInfo&&e.customMetadata){let i={customStreamInfo:e.customStreamInfo,customMetadata:e.customMetadata};t=T.extend({},D.flatten(i))}}catch(e){}return t}buildScreenTVViewQualityProperties(e){(!e.startTime||e.startTime<0)&&(e.startTime=0);let t=e.startTime/1e3,i=e.videoBufferLevel?e.videoBufferLevel.current:0,n=e.audioBufferLevel?e.audioBufferLevel.current:0,r=e.audioBufferLevel?e.audioBufferLevel.didDetectSeparateAudio:"UNKNOWN",s=2*Math.ceil(t/2),o=2*Math.ceil(i/2),a=2*Math.ceil(n/2);return T.extend({START_TIME_SEC:t||0,VIDEO_BUFFER_SEC:i||0,AUDIO_BUFFER_SEC:n||0,AUDIO_STREAM_DETECTED:r,START_TIME_2SEC_BIN:s||0,VIDEO_BUFFER_2SEC_BIN:o||0,AUDIO_BUFFER_2SEC_BIN:a||0},this.buildVideoProperties(e))}buildScreenTVViewStartTimeQualityProperties(e){return e&&T.get(this.config,["features","sendStartTimeQualityInfo"])?{PRE_ROLL_AD_POD_START_TIME_MS:e.adPodStartedTimeInMs?e.adPodStartedTimeInMs:0,PRE_ROLL_AD_POD_END_TIME_MS:e.adPodEndedTimeInMs?e.adPodEndedTimeInMs:0,VIDEO_LOAD_RECEIVED_BY_APP_TIME_MS:e.loadReceivedByAppTimeInMs?e.loadReceivedByAppTimeInMs:0,VIDEO_LOAD_RECEIVED_BY_PLAYER_TIME_MS:e.loadReceivedByPlayerTimeInMs?e.loadReceivedByPlayerTimeInMs:0,VIDEO_METADATA_LOADED_TIME_MS:e.metadataLoadedTimeInMs?e.metadataLoadedTimeInMs:0,VIDEO_PLAYER_READY_TIME_MS:e.playerReadyToPlayTimeInMs?e.playerReadyToPlayTimeInMs:0,VIDEO_PLAYBACK_STARTED_TIME_MS:e.playbackStartedTimeInMs?e.playbackStartedTimeInMs:0}:{}}buildScreenTVViewErrorProperties(e){return T.extend({VIDEO_POSITION_MS:Math.round(e.videoPosition),FAILURE_VALUE:e.failureValue,FAILURE_CODE:e.failureCode},this.buildVideoProperties(e))}buildScreenAdViewProperties(e){return{SCREEN_AD_ID:e.adId,AD_DURATION:e.adDuration,VIDEO_ID:e.videoId,VIDEO_TITLE:e.videoTitle,VIDEO_DURATION_MS:Math.round(e.videoDuration),VIDEO_POSITION_MS:Math.round(e.videoPosition),IS_LIVE:e.isLive,IS_VIDEO_LAUNCHED_FROM_PHONE:e.isVideoLaunchedFromPhone}}buildScreenTVSigninProperties(e){return{USER_ID:e.userId,USER_LOGIN:e.userLogin,USER_LOGIN_TYPE:e.userLoginType}}_setUpdatedCommonProperties(e){let t={};this.commonProperties.adId&&this.commonProperties.adId!=tn||(t.adId=VizbeeTV.tv.adId||tn),this.commonProperties.isAdTrackingDisabled&&this.commonProperties.isAdTrackingDisabled!=tn||(t.isAdTrackingDisabled=VizbeeTV.tv.isAdTrackingDisabled||tn),VizbeeTV.tv.deviceInfo&&(VizbeeTV.tv.deviceInfo.deviceId&&VizbeeTV.tv.deviceInfo.deviceId!=tn&&(t.deviceId=VizbeeTV.tv.deviceInfo.deviceId),VizbeeTV.tv.deviceInfo.model&&VizbeeTV.tv.deviceInfo.model!=tn&&(t.deviceModel=VizbeeTV.tv.deviceInfo.model)),this.setAttributesProviderProperties(t,t=>{this.setCommonProperties(t),e()})}};const sn="receiver_with_applets";class on extends Gi{constructor(e,t){super(e,t),this.appConfig=t,this.currentVideoId=void 0,this.didLogStartVideo=!1,this.lastLoggedVideoPostition2XMin=-1,this.elapsedLastPlayingTimestamp=void 0,this.elapsedPlayingTime=0,this.targetAppType=this.appConfig&&this.appConfig.features&&this.appConfig.features.targetAppType,this.senderMap={}}connect(e){rn.init(this.appConfig);const t=VizbeeTV.tv.launchParamsDeferral;t&&"function"==typeof t.waitUntilReady&&t.waitUntilReady().then(()=>{rn.refreshLaunchParamProperties()}),super.connect(e)}send(e){if(!e||!e.cmd)return void super.send(e);let t=e;"status"==e.cmd.name&&(t=this.interceptVideoStatus(e)),super.send(t)}interceptVideoStatus(e){if(this.currentVideoId!=e.vstatus.id&&(this.currentVideoId=e.vstatus.id,this.didLogStartVideo=!1,this.lastLoggedVideoPostition2XMin=-1,this.elapsedLastPlayingTimestamp=Date.now(),this.elapsedPlayingTime=0,VizbeeSDK.logger.d("MetricsExtension","interceptVideoStatus","logging new video"),rn.trackScreenTVViewLoad({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du||-1,isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee})),"PLAYING"==e.vstatus.st&&(e.vinfo.islive||!e.vinfo.islive&&e.vstatus.po>0)){if(!this.didLogStartVideo){VizbeeSDK.logger.d("MetricsExtension","interceptVideoStatus","logging start video");var t=e.vinfoext.qos||{};rn.trackScreenTVViewStart({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:t.starttime||0,audioBufferLevel:t.audiobufferlevel||{},videoBufferLevel:t.videobufferlevel||{},adPodStartedTimeInMs:t.adPodStartedTimeInMs||0,adPodEndedTimeInMs:t.adPodEndedTimeInMs||0,loadReceivedByAppTimeInMs:t.loadReceivedByAppTimeInMs||0,loadReceivedByPlayerTimeInMs:t.loadReceivedByPlayerTimeInMs||0,metadataLoadedTimeInMs:t.metadataLoadedTimeInMs||0,playerReadyToPlayTimeInMs:t.playerReadyToPlayTimeInMs||0,playbackStartedTimeInMs:t.playbackStartedTimeInMs||0}),this.didLogStartVideo=!0}this.elapsedPlayingTime=this.elapsedPlayingTime+(Date.now()-this.elapsedLastPlayingTimestamp),this.elapsedLastPlayingTimestamp=Date.now();let i=2*Math.floor(e.vstatus.po/12e4);i>this.lastLoggedVideoPostition2XMin&&(this.lastLoggedVideoPostition2XMin=i,rn.trackScreenTVViewDuration({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:this.lastLoggedVideoPostition2XMin,videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel}))}return"FAILED"==e.vstatus.st&&rn.trackScreenTVViewError({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,isLive:e.vinfo.islive,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:this.lastLoggedVideoPostition2XMin,videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,failureValue:e.vstatus.er.reason,failureCode:e.vstatus.er.code,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel}),["INTERRUPTED","FINISHED","FAILED"].indexOf(e.vstatus.st)>-1&&(this.currentVideoId=void 0),e}handleSyncReceiveEvent(e){let t=e.data;if(t&&t.b&&t.b.cmd&&"video"===t.b.cmd.ns&&"event"===t.b.cmd.name&&t.b.einfo&&"tv.vizbee.homesign.signin"==t.b.einfo.type){let e=t.b.einfo.data&&t.b.einfo.data.authInfo;e&&rn.trackScreenTVSignin(e)}return e}handleNonSyncReceiveEvent(e){if(e&&e.type==It.SYNC_CONNECT&&rn.trackScreenLaunched(),e&&e.type==It.SYNC_PRESENCE){let t=e.data;if(t&&this.senderMap){let e=Object.keys(this.senderMap),i=Object.keys(t);i.length>e.length?i.forEach(e=>{this.senderMap[e]||(!t[e]||"vzb0000000"===t[e].appId&&this.targetAppType===sn||(VizbeeSDK.logger.d("MetricsExtension","handleNonSyncReceiveEvent","new sender connected, id = "+e),rn.trackScreenRemoteConnected(t[e])),this.senderMap[e]=t[e])}):i.length<e.length&&e.forEach(e=>{-1==i.indexOf(e)&&(VizbeeSDK.logger.d("MetricsExtension","handleNonSyncReceiveEvent","sender disconnected, id = "+e),delete this.senderMap[e])})}}return e}}class an extends Gi{constructor(e,t){super(e,t),this.appConfig=t,this.currentVideoId=void 0,this.elapsedLastPlayingTimestamp=void 0,this.elapsedPlayingTime=0,this.videoPausedTimestamp=-1,this.didLogPauseVideo=!1}connect(e){rn.init(this.appConfig),super.connect(e)}send(e){if(!e||!e.cmd)return void super.send(e);let t=e;"status"==e.cmd.name&&(t=this.interceptVideoStatus(e)),super.send(t)}interceptVideoStatus(e){return this.currentVideoId!=e.vstatus.id&&(this.currentVideoId=e.vstatus.id,this.elapsedLastPlayingTimestamp=Date.now(),this.elapsedPlayingTime=0,this.videoPausedTimestamp=-1,this.didLogPauseVideo=!1),"PLAYING"==e.vstatus.st&&(e.vinfo.islive||!e.vinfo.islive&&e.vstatus.po>0)&&(this.elapsedPlayingTime=this.elapsedPlayingTime+(Date.now()-this.elapsedLastPlayingTimestamp),this.elapsedLastPlayingTimestamp=Date.now(),this.didLogPauseVideo&&(VizbeeSDK.logger.debug("FilterPauseResumeEventsExtension::interceptVideoStatus - logging resume video"),rn.trackScreenTVViewResume({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:2*Math.floor(e.vstatus.po/12e4),videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),videoPausedTimeInMs:Date.now()-this.videoPausedTimestamp,isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel})),this.videoPausedTimestamp=-1,this.didLogPauseVideo=!1),"PAUSED_BY_USER"==e.vstatus.st&&(-1==this.videoPausedTimestamp&&(this.videoPausedTimestamp=Date.now()),!this.didLogPauseVideo&&Date.now()-this.videoPausedTimestamp>=15e3&&(VizbeeSDK.logger.debug("FilterPauseResumeEventsExtension::interceptVideoStatus - logging pause video"),rn.trackScreenTVViewPause({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:2*Math.floor(e.vstatus.po/12e4),videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel}),this.didLogPauseVideo=!0)),["INTERRUPTED","FINISHED","FAILED"].indexOf(e.vstatus.st)>-1&&(this.currentVideoId=void 0),e}}var dn=_(vt());class ln extends Gi{constructor(e,t){if(super(e,t),this.enable=!0,t&&t.features&&t.features.SubtitlesExtension){let e=t.features.SubtitlesExtension;null!=e.enable&&(this.enable=e.enable)}}_isEnabled(){return this.enable}handleSyncReceiveEvent(e){let t=e.data;if(VizbeeSDK.logger.verbose(`SubtitlesExtension::handleSyncReceiveEvent - received message data = ${JSON.stringify(t)}`),!(t&&t.b&&t.b.cmd))return e;let i=t.b.cmd.name;if(!(i&&["enabletrack","disabletrack"].indexOf(i.toLowerCase())>-1))return e;if(this._isEnabled()){let e=Number(t.b.cmd.param);if(!isNaN(e)){let i=[e];"enabletrack"===t.b.cmd.name?dn.enableTracks(i):dn.disableTracks(i)}}}send(e){if(!e||!e.cmd)return void super.send(e);let t=e,i="status"==e.cmd.name,n="hello"==e.cmd.name&&"rsp"==e.cmd.type&&e.vstatus;(i||n)&&(t=this._interceptVideoStatus(e)),super.send(t)}_interceptVideoStatus(e){return this._addTrackStatus(e)}_addTrackStatus(e){if(!e||!e.vstatus)return e;if(e.vstatus.tr||(e.vstatus.tr={}),!this._isEnabled())return e;let t=this._getTextTrackStatus();return e.vstatus.tr.availableTextTracks=t.availableTextTracks,e.vstatus.tr.currentTextTrack=t.currentTextTrack,e}_getTextTrackStatus(){let e={},t=dn.getTracks(n),i=dn.getEnabledTracks(n);if(t&&Array.isArray(t)&&t.length>0&&(t.forEach(t=>{let i=t.toJSON();i&&(e.availableTextTracks||(e={availableTextTracks:[],currentTextTrack:{}}),e.availableTextTracks.push({screenTrackId:i.id,languageCode:i.lang}))}),i&&Array.isArray(i)&&i.length>0)){let t=i[0].toJSON();t&&(e.currentTextTrack={screenTrackId:t.id,languageCode:t.lang})}return e}}class cn extends Gi{constructor(e,t){if(super(e,t),this.enable=!0,t&&t.features&&t.features.AudioTracksExtension){let e=t.features.AudioTracksExtension;null!=e.enable&&(this.enable=e.enable)}}_isEnabled(){return this.enable}handleSyncReceiveEvent(e){if(!this._isEnabled())return e;let t=e.data;if(VizbeeSDK.logger.verbose(`AudioTracksExtension::handleSyncReceiveEvent - received message data = ${JSON.stringify(t)}`),!(t&&t.b&&t.b.cmd))return e;let i=t.b.cmd.name;if(!i||"string"!=typeof i||"changeaudiotrack"!==i.toLowerCase())return e;let n=Number(t.b.cmd.param);isNaN(n)?VizbeeSDK.logger.debug(`AudioTracksExtension::handleSyncReceiveEvent - received changeAudioTrack command with invalid trackId = ${n}`):(VizbeeSDK.logger.debug(`AudioTracksExtension::handleSyncReceiveEvent - received changeAudioTrack command with trackId = ${n}`),dn.changeAudioTrack(n))}send(e){if(!e||!e.cmd)return void super.send(e);let t=e,i="status"==e.cmd.name,n="hello"==e.cmd.name&&"rsp"==e.cmd.type&&e.vstatus;(i||n)&&(t=this._interceptVideoStatus(e)),VizbeeSDK.logger.verbose("AudioTracksExtension::send - forwarding out message",t),super.send(t)}_interceptVideoStatus(e){return this._addAudioTrackStatus(e)}_addAudioTrackStatus(e){if(!e||!e.vstatus)return e;if(e.vstatus.tr||(e.vstatus.tr={}),!this._isEnabled())return e;let t=this._getAudioTrackStatus();return e.vstatus.tr.availableAudioTracks=t.availableAudioTracks,e.vstatus.tr.currentAudioTrack=t.currentAudioTrack,e}_getAudioTrackStatus(){let e={},t=dn.getAudioTracks(r),i=dn.getActiveAudioTrack(r);return t&&Array.isArray(t)&&t.length>0&&(t.forEach(t=>{let i=t.toJSON();i&&(e.availableAudioTracks||(e={availableAudioTracks:[],currentAudioTrack:{}}),e.availableAudioTracks.push({screenTrackId:i.id,languageCode:i.lang,displayName:i.label}))}),i&&null!=i.id&&(e.currentAudioTrack={screenTrackId:i.id,languageCode:i.lang,displayName:i.label})),e}}const un=[Ui,Bi,ji,Wi,class extends Gi{constructor(e,t){VizbeeSDK.logger.debug("ExitOnLastMessageRecvExtension::constructor()"),super(e,t)}handleSyncReceiveEvent(e){let t=e.data;if(VizbeeSDK.logger.verbose(`ExitOnLastMessageRecvExtension::onReceiveHandler() ${this.appConfig.appId}`,t),VizbeeSDK.logger.verbose("ExitOnLastMessageRecvExtension::onReceiveHandler getActiveSendersCount - cmd ",this.getActiveSendersCount(),t.b?t.b.cmd.name:""),!t.b||"exit"!==t.b.cmd.name)return e;"user_invoked_disconnect"===t.b.cmd.param&&0==this.getActiveSendersCount()&&this.appConfig.features&&this.appConfig.features.shouldExitOnLastSender&&(VizbeeSDK.logger.debug("ExitOnLastMessageRecvExtension::onReceiveHandler getActiveSendersCount is zero - going to exit the receiver app"),VizbeeTV.tv.exit())}},qi,class extends Gi{constructor(e,t){VizbeeSDK.logger.debug("FilterMessageSendExtension::constructor()"),super(e,t),this.shouldFilterAllMessagesOnLastSenderExit=t&&t.features&&t.features.shouldFilterAllMessagesOnLastSenderExit}send(e){if(!e||!e.cmd)return void super.send(e);let t=this.getActiveSendersCount();if(!(this.shouldFilterAllMessagesOnLastSenderExit&&t<=0))return"status"==e.cmd.name?e.vstatus&&-1!=["FINISHED","INTERRUPTED","FAILED"].indexOf(e.vstatus.st)?(VizbeeSDK.logger.debug(`FilterMessageSendExtension::send message.vstatus.st: ${e.vstatus.st}`),void super.send(e)):void(0!==t?super.send(e):VizbeeSDK.logger.verbose("FilterMessageSendExtension::send senders not available: MESSAGE NOT SENT",this.getActiveSendersCount(),e)):void super.send(e);VizbeeSDK.logger.verbose("FilterMessageSendExtension::send filtering all messages as senders are not available and shouldFilterAllMessagesOnLastSenderExit is set")}},Ji,an,on,class extends Gi{constructor(e,t){VizbeeSDK.logger.debug("DisconnectSendersInBackgroundExtension::constructor()",e,t.appId),super(e,t),this._enable=!1,this._senderAliveTimeoutWithFGFlagInMs=6e4,this._senderAliveTimeoutWithoutFGFlagInMs=72e4,this._senderAliveCheckTimer=void 0,this._senderAliveTimerWithFGFlag=void 0,this._senderAlivetTimerWithoutFGFlag=void 0,this._androidSendersInBackgroundMap={},this._androidSendersWithoutFGFlagMap={},this._getExtensionConfigData(t)}_getExtensionConfigData(e){if(e&&e.features&&e.features.DisconnectSendersInBackgroundExtension){let t=e.features.DisconnectSendersInBackgroundExtension;1==t.enable&&(this._enable=!0,null!=t.senderAliveTimeoutWithFGFlagInMs&&(this._senderAliveTimeoutWithFGFlagInMs=t.senderAliveTimeoutWithFGFlagInMs),null!=t.senderAliveTimeoutWithoutFGFlagInMs&&(this._senderAliveTimeoutWithoutFGFlagInMs=t.senderAliveTimeoutWithoutFGFlagInMs))}}disconnect(){VizbeeSDK.logger.debug("DisconnectSendersInBackgroundExtension::disconnect()"),this._stopAllTimers(),this._resetToDefault(),super.disconnect()}handleSyncReceiveEvent(e){if(!this._enable)return e;let t=e.data;if(t&&t.h){let e=t.h.ty&&t.h.ty.toLowerCase(),i=t.h.st&&t.h.st.toLowerCase();e&&"remote"==e&&i&&"android"==i&&(t.h.ssinfo&&null!=t.h.ssinfo.IS_IN_FOREGROUND?0==t.h.ssinfo.IS_IN_FOREGROUND?this._androidSendersInBackgroundMap[t.h.id]||(VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::handleSyncReceiveEvent - adding new sender to the map"),this._androidSendersInBackgroundMap[t.h.id]=Date.now()):this._androidSendersInBackgroundMap={}:this._androidSendersWithoutFGFlagMap[t.h.id]||(this._androidSendersWithoutFGFlagMap[t.h.id]=Date.now(),VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::handleSyncReceiveEvent - adding new sender to the map")))}return this._startSenderAliveCheckTimer(),e}_startSenderAliveCheckTimer(){this._stopSenderAliveCheckTimer(),this._senderAliveCheckTimer=window.setInterval(()=>{this._checkSenderStatusAndSendOlleh()},1e3)}_checkSenderStatusAndSendOlleh(){this._handleSendersInBackground(),this._handleSendersWithoutFGFlag()}_handleSendersInBackground(){let e=Date.now();T.keys(this._androidSendersInBackgroundMap).filter(t=>e-this._androidSendersInBackgroundMap[t]>this._senderAliveTimeoutWithFGFlagInMs).length>0&&(VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::_handleSendersInBackground - sending olleh as there are no senders in foreground"),this._sendOllehMessage(),this._resetToDefault())}_handleSendersWithoutFGFlag(){let e=Date.now(),t=T.keys(this._androidSendersWithoutFGFlagMap),i=T.keys(this._androidSendersWithoutFGFlagMap).filter(t=>e-this._androidSendersWithoutFGFlagMap[t]>this._senderAliveTimeoutWithoutFGFlagInMs);i.length>0&&t.length==i.length&&(VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::_handleSendersWithoutFGFlag - sending olleh as there are no senders in foreground"),this._sendOllehMessage(),this._resetToDefault())}_sendOllehMessage(){this.dispatchReceive(new _t(It.SYNC_MESSAGE,{b:{cmd:{ns:"video",name:"olleh",type:"int"},hstatus:{id:this.appConfig.deviceId,type:"SCREEN",vip:"false"}}}))}_resetToDefault(){this._stopAllTimers(),this._androidSendersInBackgroundMap={},this._androidSendersWithoutFGFlagMap={}}_stopAllTimers(){this._stopSenderAliveCheckTimer(),this._stopDisconnetionTimerWithIsInFGFlag(),this._stopDisconnetionTimerWithoutIsInFGFlag()}_stopSenderAliveCheckTimer(){this._senderAliveCheckTimer&&(window.clearInterval(this._senderAliveCheckTimer),this._senderAliveCheckTimer=void 0)}_stopDisconnetionTimerWithIsInFGFlag(){this._senderAliveTimerWithFGFlag&&(window.clearTimeout(this._senderAliveTimerWithFGFlag),this._senderAliveTimerWithFGFlag=void 0)}_stopDisconnetionTimerWithoutIsInFGFlag(){this._senderAliveWithoutFGFlagTimer&&(window.clearTimeout(this._senderAliveWithoutFGFlagTimer),this._senderAliveWithoutFGFlagTimer=void 0)}},ln,cn],pn=[Ui,Bi,ji,Wi,qi,Ji,an,on,ln,cn,null];let hn;class gn{createSync(e){let t=T.get(e,["syncInfo","syncMethod"],"pubnub").toLowerCase();return"googlecustom"==t?(hn=this.getGoogleCustomSyncInstanceWitExtensions(e),hn):"googledual"==t?(hn=this.getGoogleDualSyncInstanceWitExtensions(e),hn):(hn=this.getDefaultSyncInstanceWitExtensions(e),hn)}static getSync(){return hn}getGoogleCustomSyncInstanceWitExtensions(e){return this.addExtensions(e,this.getGoogleCastSync(e),pn)}getGoogleDualSyncInstanceWitExtensions(e){let t=this.addExtensions(e,new zi(e),un),i=this.addExtensions(e,this.getGoogleCastSync(e),pn),n=new Ri(e);return n.addSyncInstance(t),n.addSyncInstance(i),n}getDefaultSyncInstanceWitExtensions(e){return this.addExtensions(e,new zi(e),un)}addExtensions(e,t,i){for(let n=0;n<i.length;n++)t=new(0,i[n])(t,e);return t}getGoogleCastSync(e){return cast.framework,new null(e)}}let fn=function(e){return e[e.NOT_CONNECTED=1]="NOT_CONNECTED",e[e.CONNECTING=2]="CONNECTING",e[e.CONNECTED=3]="CONNECTED",e}({});var vn,yn,mn,bn,Sn,_n,In,Tn,En=I(),Vn=yt(),Pn=function(){if(at)return ot;at=1,I();var e={},t={};function i(){VizbeeSDK.logger.debug("VGAStateManager:reset() previous video and ad objects = ",e,t),e.id="",e.state="UNKNOWN",e.position=-1,e.duration=-1,t.id="",t.state="UNKNOWN",t.position=-1,t.duration=-1}return i(),ot={type:"VGAStateManager",app:{state:"app"},video:e,ad:t,reset:i,addListener:function(e){},removeListener:function(){}}}(),An=ze(),Cn=mt(),Dn=vt(),kn=bt(),wn=750;let Nn;class Mn{static getInstance(){return null==Nn&&(Nn=new Mn),Nn}getQueueManager(){return null==this.queueManager&&(this.queueManager=new null(null.getInstance())),VizbeeSDK.logger.debug("ContinuityContext::getQueueManager - returning queue manager",this.queueManager),this.queueManager}}var On,xn,Ln,zn=I(),Rn=function(){if(De)return Ce;De=1;var e,t,i=ke().xhr,n=I(),r={appId:null,config:null,pub_key:"pub-c-1e4f216f-168e-4fdc-8a2b-a29ffe05cb5b",sub_key:"sub-c-6da25f1b-58d7-4f17-bd10-21a30198a794"};return Ce={appConfig:r,getConfig:function(s,o){r.appId=s.appId,r.platform=s.platform,r.platformModel=s.platformModel,r.hostProxy=s.hostProxy,function(){var n="config.claspws.tv";r.hostProxy&&(n=r.hostProxy),e=r.platform,t=r.platformModel;var s="//"+n+"/api/v2/";s+="apps/"+r.appId+"/screen/"+e,t&&(s+="."+t);let o=!1;if(window&&window.navigator&&window.navigator.language){var a=window.navigator.language.split("-");a.length>1&&(s+="?country="+a[1],o=!0)}return s+=(o?"&":"?")+"seed="+Math.round(1e3*Math.random()),VizbeeSDK.logger.debug("Config:getAPIConfig - didn't find any saved config from local storage. Calling config server ..."),s="https:"+s,VizbeeSDK.logger.debug("Config:getAPIConfig - URL = "+s),i({url:s,retries:3,timeout:3e4,headers:{Accept:"application/json"}}).then(function(e){if(e&&e.error&&100==e.error.code)return VizbeeSDK.logger.error("Config:getAPIConfig - received error code and message = ",e.error.code,e.error.message),VizbeeSDK.logger.error("Config:getAPIConfig - screen device may not be allowed or setup. Screen device platform = ",r.platform),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),Promise.reject(e.error);if(e&&e.data&&e.data.items&&e.data.items[0]){if(e.data.items[0].channelKeys.pub_key&&e.data.items[0].channelKeys.sub_key){var t=e.data.items[0];return t.externalIp=e.externalIpAddress,VizbeeSDK.logger.debug("Config:getAPIConfig - valid config returned by API",t),VizbeeSDK.logger.debug("Config:getAPIConfig - SDK init SUCCESS!"),t}return VizbeeSDK.logger.error("Config:getAPIConfig - got config response but no channel pub keys or sub keys!"),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),Promise.reject("No pub sub keys for given appId")}return VizbeeSDK.logger.error("Config:getAPIConfig - invalid response (but no error!) returned by server"),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),Promise.reject("Invalid response")}).catch(function(e){return VizbeeSDK.logger.error("Config:getAPIConfig - XHR request to get config failed"),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),Promise.reject(e)})}().then(function(e){VizbeeSDK.logger.debug("Config:getConfig - got apiConfig",e),n.extend(r,e),e.channelKeys.pub_key&&e.channelKeys.sub_key&&(r.pub_key=e.channelKeys.pub_key,r.sub_key=e.channelKeys.sub_key),"function"==typeof o&&(VizbeeSDK.logger.debug("Config:getConfig - calling callback with extended config =",r),o(r))}).catch(function(e){var t="SDK CONFIG FETCH FAILED";null!=e&&(t+=" - "+e.message);var i=new Error(t);VizbeeSDK.logger.critical("Config::getConfig - SDK CONFIG FETCH FAILED",i),VizbeeSDK.logger.error("Config::getConfig - NOTE - could be a failure in the callback passed to getConfig!")})}},Ce}(),Kn=xe,Un=function(e,t){var i,n=e,r=void 0,s=void 0,o=!1,a=!1,d=!1,l=!1;let c=n&&n.features&&n.features.syncSendIntervalInMs;isNaN(c)||(wn=c);var u=[],p=[],h={};return t?(o=!0,i=Pn):(o=!1,i=Vn,Dn.setAppStateManager(Vn),kn.addListener(function(e){VizbeeSDK.logger.debug("synccontroller",e),"sync_proxy_video_cmds"==e.type&&("x"===e.cmd.name||"event"===e.cmd.name?(delete e.type,r.send(e)):v(e))})),{connect:function(e){VizbeeSDK.logger.debug("SyncController::connect - dumping appConfig = ",n);var t=new gn;(r=t.createSync(n)).onReceive=function(t){if(t)switch(t.type){case It.SYNC_CONNECT:!function(e){a=!0,o&&(VizbeeSDK.logger.debug("SyncController::syncConnectHandler - setting isAppAdapterAvailable to TRUE (isVGA=true)"),d=!0),g(),e(!0)}(e);break;case It.SYNC_MESSAGE:var i=t.data.b,n=t.data.h;if(o&&i.cmd&&-1==["launch_applet","hello"].indexOf(i.cmd.name))return;s=n,"video"===(r=i).cmd.ns&&v(r,s),"x"===r.cmd.ns&&m((l=r).b.cmd.ns,y(l));break;case It.SYNC_PRESENCE:o||function(e){VizbeeSDK.logger.debug("SyncController::presenceHandler() - connected users count",e);var t=En.extend({},h);h=En.extend({},e),VizbeeSDK.logger.debug("SyncController::syncPresenceHandler - transition","from:",Object.keys(t),"to:",Object.keys(h)),function(e,t){var i=Object.keys(e||{}),n=Object.keys(t||{});VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - previousIds: ",i," newIds: ",n);var r=n.filter(function(e){return-1===i.indexOf(e)});VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - joinedIds: ",r);var s=i.filter(function(e){return-1===n.indexOf(e)});VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - leftIds: ",s),r.forEach(function(e){var i=t[e];if(i){VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - user joined: ",e);var n={event:"JOIN",member:i};p.forEach(function(e){try{e(n)}catch(e){VizbeeSDK.logger.error("SyncController::notifyPresenceListeners - Error calling listener",e)}})}}),s.forEach(function(t){VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - user left: ",t);var i=e[t];if(i){VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - user left: ",t);var n={event:"LEAVE",member:i};p.forEach(function(e){try{e(n)}catch(e){VizbeeSDK.logger.error("SyncController::notifyPresenceListeners - Error calling listener",e)}})}})}(t,h),An.updatePresence(e)}(t.data)}var r,s,l},r.connect(e),i.addListener(S),An.isAppSet()&&(VizbeeSDK.logger.debug("SyncController::connect appIsSet"),d=!0,g()),u.forEach(e=>{e(fn.CONNECTED)}),s=window.setInterval(_,wn)},disconnect:function(){VizbeeSDK.logger.debug("SyncController::disconnect() called"),clearInterval(s),i.removeListener(S),u.forEach(e=>{e(fn.NOT_CONNECTED)}),f(),r.disconnect(),a=!1},isConnected:function(){return a},addSessionStateListener:function(e){u.push(e)},sessionState:function(){return a?fn.CONNECTED:fn.NOT_CONNECTED},subscribeToPresence:function(e){"function"==typeof e&&(p.push(e),VizbeeSDK.logger.debug("SyncController::subscribeToPresence - listener added"))},unsubscribeFromPresence:function(e){const t=p.indexOf(e);t>-1&&(p.splice(t,1),VizbeeSDK.logger.debug("SyncController::unsubscribeFromPresence - listener removed"))},getActiveSenders:function(){return r&&"function"==typeof r.getActiveSenders?r.getActiveSenders():{}},enableSynchronousPublish:function(){try{var e=r&&r.baseSync;e&&"function"==typeof e.enableSynchronousPublish&&e.enableSynchronousPublish()}catch(e){VizbeeSDK.logger.error("SyncController::enableSynchronousPublish - error",e)}}};function g(){if(a&&d){o&&!l&&(l=!0,Cn.onSubscribedToSync()),VizbeeSDK.logger.debug("SyncController::sendJoin - sending initial JOIN HELLO UPD message");var e={cmd:{ns:"video",name:"hello",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}};r.send(e)}else VizbeeSDK.logger.debug("SyncController::sendJoin - NOT sending JOIN HELLO yet",a,d)}function f(){if(a&&d){VizbeeSDK.logger.debug("SyncController::sendOlleh - sending OLLEH UPD message");var e={cmd:{ns:"video",name:"olleh",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}};r.send(e)}else VizbeeSDK.logger.debug("SyncController::sendOlleh - NOT sending Olleh",a,d)}function v(e,t={}){var s,o,a,d;if(!("int"!==e.cmd.type&&e.hstatus&&"SCREEN"==e.hstatus.type||"req"!==e.cmd.type&&"int"!==e.cmd.type))switch(e.cmd.name){case"launch_applet":if(En.isUndefined(e.cmd.param))return;VizbeeSDK.logger.debug("SyncController::launch_applet - called",e.cmd.param),void 0!==window.VGA&&window.VGA.launch(e.cmd.param);break;case"hello":s={cmd:{ns:"video",name:"hello",type:"rsp"},hstatus:{id:n.deviceId,type:"SCREEN"}};try{"app"!==i.app.state?((d=I()).vstatus&&(s.vstatus=d.vstatus),d.vinfo&&(s.vinfo=d.vinfo),d.vinfoext&&(s.vinfoext=d.vinfoext),s.hstatus.vip="true"):s.hstatus.vip="false","int"==e.cmd.type&&(s.cmd.type="req"),r.send(s)}catch(e){VizbeeSDK.logger.error("SyncController::videoMessgaeHandler -- hello command. error ",e)}break;case"will_start_video":if(VizbeeSDK.logger.debug("SyncController::videoMessageHandler::will_start_video called",e),!(c=e.internal.videoInfo))return;var l=e.internal.videoStartsIn;l=l||0,Dn.willStart(c,l);break;case"start_video":VizbeeSDK.logger.debug("SyncController::videoMessageHandler::start_video called",e);var c=e.internal.videoInfo;let p=e.internal.startVideoSource?e.internal.startVideoSource:"default";if(!c)return;"app"!==i.app.state?(VizbeeSDK.logger.debug("SyncController::videoMessageHandler()::start_video -- CALLING VIDEOADAPTER.STOP()"),Dn.stop("stop_reason_before_next_video"),setTimeout(function(){VizbeeSDK.logger.debug("SyncController::videoMessageHandler()::start_video -- CALLING START AFTER STOP"),b(c,p)},3e3)):b(c,p);break;case"pause":if("video"!==i.app.state)return void VizbeeSDK.logger.warn("pause requested when not in 'video' state",i.app.state);Dn.pause();break;case"play":if("video"!==i.app.state)return void VizbeeSDK.logger.warn("play requested when not in 'video' state",i.app.state);Dn.play();break;case"stop":if("app"==i.app.state)return void VizbeeSDK.logger.warn("stop requested when in 'app' state",i.app.state);VizbeeSDK.logger.info("syccontroller:: stop ",e.cmd.param);var u=e.cmd.param||"stop_reason_unknown";Dn.stop(u);break;case"exit":s={cmd:{ns:"video",name:"olleh",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}},r.send(s),Dn.exit();break;case"olleh":"int"==e.cmd.type&&f();break;case"status":_();break;case"seek":if(i.ad.playing)return VizbeeSDK.logger.debug("1",i.ad),void VizbeeSDK.logger.debug(i.video);if(En.isUndefined(e.cmd.param))return void VizbeeSDK.logger.debug("2",e);if(o=parseInt(e.cmd.param,10),isNaN(o))return void VizbeeSDK.logger.debug("3",o);if(i.video&&i.video.duration&&(a=i.video.duration,VizbeeSDK.logger.debug("4",o,a),o>a))return;if(o<0)return void VizbeeSDK.logger.debug("5",o);Dn.seek(o);break;case"vol_up":"function"==typeof Dn.volumeUp&&Dn.volumeUp();break;case"vol_down":"function"==typeof Dn.volumeDown&&Dn.volumeDown();break;case"mute":"function"==typeof Dn.mute&&Dn.mute(!0);break;case"unmute":"function"==typeof Dn.mute&&Dn.mute(!1);break;case"set_tracks":"function"==typeof Dn.setTracks&&Dn.setTracks(e.cmd.param||[]);break;case"event":"function"==typeof Dn.onEvent&&e.einfo&&e.einfo.data&&(Dn.onEvent(e.einfo),"tv.vizbee.homesso.signin"===e.einfo.type&&function(e,t){m(e.type,y({h:t,b:{payload:e.data}}))}(e.einfo,t))}}function y(e){const t=e.h.ssinfo,i={deviceId:t.REMOTE_DEVICE_ID,deviceType:t.REMOTE_DEVICE_TYPE,friendlyName:t.REMOTE_FRIENDLY_NAME,networkSessionId:t.REMOTE_NETWORK_SESSION_ID};return{payload:e.b.payload,senderInfo:i}}function m(e,t){if(!window.vizbee||!window.vizbee.continuity||!window.vizbee.continuity.xmessages)return void VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: xmessages not found");if(!window.vizbee.continuity.xmessages.VizbeeBicastSessionManager)return void VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: session manager not found");const i=new window.vizbee.continuity.xmessages.VizbeeBicastSessionManager;if(!i)return void VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: unable to create session manager instance");const n=i.getSession();if(!n)return void VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: session not found");const r=n.getMessagingClient();r?r.onReceive(e,t.payload,t.senderInfo):VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: messaging client not found")}function b(e,t){VizbeeSDK.logger.debug("SyncController::doStartVideo -- called StateManager.reset()",i),i.reset(),VizbeeSDK.logger.debug("SyncController::doStartVideo -- calling setSyncVideoInfo",i,i.getSyncVideoInfo()),i.setSyncVideoInfo(e),i.syncStartVideoSource=t,VizbeeSDK.logger.debug("SyncController::doStartVideo -- calling VideoAdapter.start() with videoInfo",e),Dn.start(e)}function S(e){"appIsSet"===e.type?(VizbeeSDK.logger.debug("SyncController::stateHandler appIsSet"),d=!0,g()):_()}function _(){if("app"!==i.app.state)if("UNKNOWN"!==i.video.state)if("PAUSED_BY_AD"!==i.video.state||"UNKNOWN"!==i.ad.state){var e=I();r&&r.send(e)}else VizbeeSDK.logger.debug("SyncController:sendUpdate - unknown video/ad state, not sending. app/video/ad.state: ",i.app.state,i.video.state,i.ad.state);else VizbeeSDK.logger.verbose("SyncController::sendUpdate - UNKNOWN video state, not sending");else"AppStateManager"==i.type&&VizbeeSDK.logger.verbose("SyncController::sendUpdate - in app state, not sending update",i)}function I(){var e,t=i.video,n=i.ad,r=i.getSyncVideoInfo(),s=i.getCurrentVideoInfo(),o={cmd:{name:"status",ns:"video",type:"upd"}};t&&(e=t.volume,t.muted&&(e=0),o.vinfo={id:t.id,url:""},r.id||(r=s),o.vinfo.islive=!1,o.vinfoext={title:"",subtitle:"",imgurl:"",desc:"",videostarttime:0,custommetadata:{},customstreaminfo:{},qos:{}},VizbeeSDK.logger.verbose("SyncController::createStatusMessage:: - ",r,s),s&&s.id&&r&&r.id&&r.id==s.id?(o.vinfo.url=r.videourl,o.vinfo.islive=r.islive,o.vinfoext={title:r.title||"",subtitle:r.subtitle||"",imgurl:r.imgurl||"",desc:r.desc||"",videostarttime:r.starttime||0,custommetadata:r.customMetadata||r.custommetadata,customstreaminfo:r.customStreamInfo||r.customstreaminfo,qos:T(t)}):s&&s.id&&(o.vinfo.url=s.videourl,o.vinfo.islive=s.islive,o.vinfoext={title:s.title||"",subtitle:s.subtitle||"",imgurl:s.imgurl||"",desc:s.desc||"",videostarttime:s.starttime||0,custommetadata:s.customMetadata||s.custommetadata,customstreaminfo:s.customStreamInfo||s.customstreaminfo,qos:T(t)}),o.vinfoext.wasVideoStartedByVizbee=i.wasVideoStartedByVizbee(),o.vstatus={du:parseInt(t.duration,10)||-1,id:t.id,po:parseInt(t.position,10)||-1,st:t.state,vol:parseInt(e),cc:t.cc,tr:t.tr,er:t.error||{}},"Infinity"!=t.duration&&"0"!=t.duration||(o.vstatus.du=0)),n&&t&&"PAUSED_BY_AD"==t.state&&(o.adstatus={du:parseInt(n.duration,10)||-1,id:n.id,po:parseInt(n.position,10)||-1,st:n.state});var a=An.getVideoInfo();return a&&(a.id&&(o.vinfo=o.vinfo||{},o.vinfo.id=a.id,o.vstatus=o.vstatus||{},o.vstatus.id=a.id),void 0!==a.videourl&&(o.vinfo=o.vinfo||{},o.vinfo.url=a.videourl),void 0!==a.islive&&(o.vinfo=o.vinfo||{},o.vinfo.islive=a.islive),void 0!==a.title&&(o.vinfoext=o.vinfoext||{},o.vinfoext.title=a.title),void 0!==a.subtitle&&(o.vinfoext=o.vinfoext||{},o.vinfoext.subtitle=a.subtitle),void 0!==a.imgurl&&(o.vinfoext=o.vinfoext||{},o.vinfoext.imgurl=a.imgurl),void 0!==a.isdvrsupported&&(o.vinfoext=o.vinfoext||{},o.vinfoext.isdvrsupported=a.isdvrsupported),void 0!==a.state&&(o.vstatus=o.vstatus||{},o.vstatus.st=a.state),void 0!==a.position&&(o.vstatus=o.vstatus||{},o.vstatus.po=parseInt(a.position,10)),void 0!==a.duration&&(o.vstatus=o.vstatus||{},o.vstatus.du=parseInt(a.duration,10))),o}function T(e){if(!e)return{};let t=e.qos||{};return{starttime:e.startTime||0,audiobufferlevel:e.audioBufferLevel,videobufferlevel:e.videoBufferLevel,adPodStartedTimeInMs:t.adPodStartedTimeInMs||0,adPodEndedTimeInMs:t.adPodEndedTimeInMs||0,loadReceivedByAppTimeInMs:t.loadReceivedByAppTimeInMs||0,loadReceivedByPlayerTimeInMs:t.loadReceivedByPlayerTimeInMs||0,metadataLoadedTimeInMs:t.metadataLoadedTimeInMs||0,playerReadyToPlayTimeInMs:t.playerReadyToPlayTimeInMs||0,playbackStartedTimeInMs:t.playbackStartedTimeInMs||0}}},Bn=yt(),Fn=ze(),Gn=mt(),Hn=vt(),Wn=ft(),jn=function(){if(yn)return vn;yn=1;var e,t,i=I(),n=new(0,Le().EventEmitter),r={preparing:!1,playing:!1,alladscomplete:!1},s=-1,o=-1,a=!1;function d(e){var n={type:"ad",position:-1,duration:-1,preparing:r.preparing,playing:r.playing,alladscomplete:r.alladscomplete};return r.playing&&(o>0?(n.position=s,n.duration=o,VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::Status using app ad timing — po:",s,"du:",o)):t&&(n.position=1e3*t.currentTime(),n.duration=1e3*t.getDuration(),VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::Status using videoEl — po:",n.position,"du:",n.duration))),i.extend(n,e)}function l(e){var s,o,a=!i.contains(["timeupdate"],e.type);(r.preparing||r.playing)&&(s=new d,"timeupdate"!==e.type&&VizbeeSDK.logger.debug("AdAdapter::handleAdEvent() - not a timeupdate event",e.type),"preparing"===e.type&&(o="LOADING",s.id="UNKNOWN"),"play"===e.type&&(o="LOADING"),"playing"===e.type&&(o="PLAYING",t&&t.basePlayer&&t.basePlayer.videoInfo&&t.basePlayer.videoInfo.src&&(s.id=t.basePlayer.videoInfo.src)),"error"===e.type&&(o="INTERRUPTED",r.playing=!1),"ended"===e.type&&(o="FINISHED",r.playing=!1),s.playing=r.playing,o&&(s.state=o),n.emit("ad",s,a))}function c(e){var t=e.type||"UNKNOWN";VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::adsManagerHandleStateChange state:",t,"data:",e.data),-1!=["ad-pod-start","ad-pod-end","ad-start","ad-playing"].indexOf(t)&&(r.preparing=!1,r.playing=!1,"ad-pod-start"===t?(a=!1,r.preparing=!0,l({type:"preparing"})):"ad-start"===t?(a=!1,l({type:"play"})):"ad-playing"===t?(r.playing=!0,e.data&&(void 0!==e.data.duration&&e.data.duration>0&&(o=e.data.duration),void 0!==e.data.position&&e.data.position>=0&&(s=e.data.position),VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::ad-playing stored timing — po:",s,"du:",o))):("ad-pod-end"===t&&(r.playing=!1,r.alladscomplete=!0,s=-1,o=-1),n.emit("ad",new d({position:-1,duration:-1,state:"UNKNOWN",preparing:r.preparing,playing:r.playing}),!1)))}function u(i){VizbeeSDK.logger.debug("VIZBEE: AdAdapter.setAdVideo()",i),i&&((t=i).onError=function(e){r.playing&&(l({type:"error"}),a=!1)},t.onEnded=function(){r.playing&&(l({type:"ended"}),a=!1)},t.onTimeUpdate=function(e){r.playing&&(a?l({type:"timeupdate"}):(a=!0,l({type:"playing"})))},e||p(t))}function p(t){VizbeeSDK.logger.debug("VIZBEE: AdAdapter.setAdsManager()",t),(e=t).onEvent=c,u(e)}return vn={setAdVideo:u,setAdsManager:p,reset:function(){r.preparing=!1,r.playing=!1,r.alladscomplete=!1,s=-1,o=-1,n.emit("ad",new d({position:-1,duration:-1,state:"UNKNOWN"}),!1)},addListener:function(e){n.addListener("ad",e)},removeListener:function(e){n.removeListener("ad",e)}}}(),qn=function(){if(_n)return Sn;_n=1,I();var e=function(){if(bn)return mn;bn=1;var e=Le().EventEmitter;const t="ad";var i=new e,n={type:t,state:"UNKNOWN",id:"UNKNOWN",position:-1,duration:-1,playing:!1,adPodStarted:!1,adPodsPlayedDuration:0,totalAdPodsDuration:0};return mn={adStatus:n,reset:function(){n.state="UNKNOWN",n.id="UNKNOWN",n.position=-1,n.duration=-1,n.playing=!1,n.adPodStarted=!1},resetTotalAdPodsDuration:function(){n.adPodsPlayedDuration=0,n.totalAdPodsDuration=0},addListener:function(e){i.addListener(t,e)},removeListener:function(e){i.removeListener(t,e)},notify:function(e){i.emit(t,n,e)}}}();const t=["loadedmetadata","play","playing","timeupdate","error","ended"];var i,n;function r(t){if(e.adStatus.adPodStarted){var r="LOADING";"loadedmetadata"==t.type||"play"==t.type?r="LOADING":"playing"==t.type?(e.adStatus.id=i.src,r="PLAYING"):"timeupdate"==t.type?r="PLAYING":"error"==t.type?r="FAILED":("ended"==t.type||i.ended)&&(r="FINISHED");var s=!1;r!=e.adStatus.state&&(s=!0,e.adStatus.state=r),e.adStatus.playing&&e.adStatus.duration>0&&n>=0?e.adStatus.position=1e3*i.currentTime-n:e.adStatus.position=-1,e.notify(s)}}function s(){e.reset(),n=-1}function o(){s(),e.notify()}return Sn={setAdVideo:function(e){!function(e){e&&t.forEach(function(t){e.removeEventListener(t,r,!1)})}(i),function(e){e&&t.forEach(function(t){e.addEventListener(t,r,!1)})}(i=e)},setAdPodStart:function(t,i,n){s(),e.adStatus.adPodStarted=!0},setAdPodEnd:function(){o()},setTotalAdPodsDuration:function(t){e.adStatus.totalAdPodsDuration=t||0,e.notify(!1)},setAdStart:function(t,i){e.adStatus.playing=!0,n=t,e.adStatus.duration=i,e.adStatus.adPodsPlayedDuration+=i},setAdEnd:function(){e.adStatus.state="FINISHED",e.notify(!0),e.adStatus.playing=!1,n=-1,e.adStatus.duration=-1},getAdStatus:function(){return e.adStatus},reset:o,resetTotalAdPodsDuration:function(){e.resetTotalAdPodsDuration()},addListener:function(t){e.addListener(t)},removeListener:function(t){e.removeListener(t)}}}(),Yn=bt(),Jn=(Tn||(Tn=1,In={getDeviceID:function(e,t,i){if(VizbeeTV&&VizbeeTV.tv)VizbeeTV.tv.uniqueDeviceID(function(i){switch(VizbeeSDK.logger.debug("Device::getDeviceID - DeviceIDAlgorithm = "+VizbeeTV.tv.deviceIDAlgorithm),VizbeeTV.tv.deviceIDAlgorithm){case"VTV_SESSION_ID":case"VTV_DEFAULT":case"VTV_URL_PARAMS":i=e.platform+":"+i;break;case"VTV_INTERNAL_IP":i=e.platform+":"+e.externalIp.toLowerCase()+":"+i}VizbeeSDK.logger.debug("Device::getDeviceID - deviceID = "+i),t(i)},function(e){VizbeeSDK.logger.error("PROD","C:001 failed to fetch deviceId, halting SDK initialization",e),i&&i(e)},e);else{var n="VizbeeTV framework not initialized yet, halting SDK initialization";VizbeeSDK.logger.error("PROD","C:002",n),i&&i(n)}}}),In),$n=void 0,Qn=void 0,Zn=!1,Xn=[],er="vzb0000000";function tr(){if(Ln&&Ln.features&&Ln.features.shouldSyncDisconnectOnBackground){if(Zn)return;$n?$n.isConnected()||(VizbeeSDK.logger.i("SDK","onForeground","connecting VGA"),Zn=!0,rr(er,function(){Zn=!1,Qn&&!Qn.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET after VGA ",xn.id),Zn=!0,rr(xn.id,function(){Zn=!1}))})):Qn&&!Qn.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET ",xn.id),Zn=!0,rr(xn.id,function(){Zn=!1}))}}function ir(){return VizbeeSDK.logger.i("SDK","onBackground"),Ln&&Ln.features&&Ln.features.shouldExitOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","exiting the app"),void VizbeeTV.tv.exit()):Ln&&Ln.features&&Ln.features.shouldSyncDisconnectOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","disconnecting from sync"),$n&&$n.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting VGA"),$n.disconnect()),Qn&&Qn.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting APPLET"),Qn.disconnect()),void(Zn=!1)):void lr()}function nr(e){VizbeeSDK.logger.i("SDK","onEnd","sending olleh"),e&&e.isTeardown&&($n&&$n.enableSynchronousPublish(),Qn&&Qn.enableSynchronousPublish()),lr()}function rr(e,t){Rn.getConfig({appId:e||xn.id,deviceId:"",platform:VizbeeTV.tv.cloudPlatformName,platformModel:VizbeeTV.tv.platformModel,hostProxy:xn.configServiceProxyHost},function(e){Ln=e,VizbeeSDK.logger.d("SDK","getConfig","got config=",Ln),Ln.customAttributesForMetrics=xn.customAttributesForMetrics,Ln.features&&Ln.features.enableIpv6Lookup?Kn.getIpv6Address(function(e){VizbeeSDK.logger.d("SDK","getIpv6Address","got response=",e),Ln.ipv6Address=e,sr(Ln,t)}):(VizbeeSDK.logger.d("SDK","getIpv6Address","skipped - enableIpv6Lookup not set in screen config"),sr(Ln,t))})}function sr(e,t){Jn.getDeviceID(e,function(i){if(VizbeeSDK.logger.d("SDK","onConfigReady","using deviceid="+i),!function(e){if(!e||"string"!=typeof e)return!1;var t=e.split(":"),i=t[t.length-1];if(!i)return!1;var n=i.toLowerCase();return"unknown_device_id"!==n&&"0.0.0.0"!==n&&"127.0.0.1"!==n&&"localhost"!==n&&"undefined"!==n&&"null"!==n}(i))return VizbeeSDK.logger.e("SDK","onConfigReady","PROD - SDK init aborted: deviceId is a default/sentinel value; sync will not be established",i),Zn=!1,void(t&&t(void 0));e.deviceId=i,function(e,t){(function(e){if(e&&e.debug&&e.debug.clients&&e.debug.clients.length>0&&e.debug.server)for(var t=0;t<e.debug.clients.length;t++){var i=e.debug.clients[t];if(i.ip&&i.ip==e.externalIp){var n=e.appId+":"+e.platform+":"+e.externalIp,r=i.aka||n;r="["+r+"]",Ve.enableRemoteLogging(e.debug.server,r),window.VizbeeSDK&&window.VizbeeSDK.logger.setLevel(window.VizbeeSDK.logger.LEVEL.DEBUG),window.VizbeeTV&&window.VizbeeTV.logger.setLevel(window.VizbeeTV.logger.LEVEL.DEBUG),window.VGA&&window.VGA.logger.setLevel(window.VGA.logger.LEVEL.DEBUG)}}})(e),e.appId==er||e.features&&e.features.targetAppType==sn?(er=e.appId,$n||($n=new Un(e,!0)),$n.connect(function(e){e?VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connected VGA"):VizbeeSDK.logger.e("SDK","onConfigAndDeviceIDReady","failed to connect VGA")})):(Qn||(VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","creating appletSyncController"),Qn=new Un(e,!1),zn.each(Xn,e=>{e()})),VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connecting appletSyncController"),Qn.connect(function(e){e?VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connected APPLET"):VizbeeSDK.logger.e("SDK","onConfigAndDeviceIDReady","failed to connect APPLET")})),t&&t(e)}(e,t)},function(e){VizbeeSDK.logger.e("SDK","onConfigReady","PROD - SDK init aborted: deviceId fetch failed; sync will not be established",e),Zn=!1,t&&t(void 0)})}function or(e){VizbeeSDK.logger.d("SDK","setApp"),Fn.setApp(e)}function ar(e){VizbeeSDK.logger.d("SDK","setVideo","video=",e),Hn.setVideo(e)}function dr(e){On={vzb_ad_ima:null,vzb_ad_ssai:qn,vzb_ad_ssai_avplay:null,vzb_ad_default:jn}[e.toLowerCase()],Hn.setAdAdapter(On)}function lr(){Yn.send({type:"sync_proxy_video_cmds",cmd:{ns:"video",name:"olleh",type:"int"}})}var cr={ContinuityContext:Mn,QueueBase:null,QueueManager:null,QueueDelegate:null,QueueDelegateFactory:null},ur={VERSION:"7.8.58",wasVideoStartedByVizbee:function(){return Bn&&Bn.wasVideoStartedByVizbee()},init:function(e){VizbeeSDK.logger.i("SDK","init"),VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.addHandler("onForeground",tr),VizbeeTV.tv.appLifeCycleManager.addHandler("onBackground",ir),VizbeeTV.tv.appLifeCycleManager.addHandler("onEnd",nr)),xn=e,VizbeeSDK.logger.i("SDK","onStart"),xn&&xn.id&&(function(e){var t;VizbeeSDK.logger.d("SDK","handleInitOptions"),e.video&&ar(e.video),e.app&&or(e.app),e.videoAdapter&&(t=e.videoAdapter,VizbeeSDK.logger.d("SDK","setHostVideoAdapter","video=",t),Wn.setVideoAdapter(t)),e.adType&&dr(e.adType),e.VGA&&e.isVGA&&Gn.setVGA(e.VGA)}(xn),Hn.init(),rr())},setApp:or,setVideo:ar,setVideoGuid:function(e,t){Hn.setId(e,t)},setVideoInfo:function(e){VizbeeSDK.logger.d("SDK","setVideoInfo","videoInfo=",e),Hn.setVideoInfo(e)},setVideoStop:function(){Hn.setVideoStop()},setAdsVideo:function(e){VizbeeSDK.logger.d("SDK","setAdsVideo","video=",e),On?On.setAdVideo(e):VizbeeSDK.logger.d("SDK","setAdsVideo","AdAdapter not configured; skipping")},getAdsAdapter:function(){return On},setAdType:dr,sendXMessage:function(e,t,i){if(!Qn)return void VizbeeSDK.logger.e("XMessages",this.constructor.name,"sendXMessage","appletSyncController not initialized");if(zn.get(Ln,["features","useXMessagesFormat"])){let i={type:"sync_proxy_video_cmds",cmd:{type:"req",ns:t,name:"x",param:""},payload:e};return VizbeeSDK.logger.d("XMessages",this.constructor.name,"sendXMessage",`sending message: ${JSON.stringify(i)} in new format to sync controller`),void Yn.send(i)}let n={type:"sync_proxy_video_cmds",cmd:{type:"req",ns:"video",name:"event",param:""},einfo:{type:t,data:e}};VizbeeSDK.logger.d("XMessages",this.constructor.name,"sendXMessage",`sending message: ${JSON.stringify(n)} in old format to sync controller`),Yn.send(n)},syncProxy:Yn,addSyncReadyListener:function(e){Xn.push(e)},removeSyncReadyListener:function(e){Xn=zn.without(Xn,e)},getSyncController:function(){return Qn},getMetricsManager:function(){return rn},wrapVideoCallbacks:Hn.wrapCallbacks,addVideoEventListener:Hn.addEventListener,removeVideoEventListener:Hn.removeEventListener,reset:function(){VizbeeSDK.logger.d("SDK","reset");try{Qn&&(Qn.disconnect(),Qn=void 0)}catch(e){VizbeeSDK.logger.e("SDK","reset","error disconnecting appletSyncController.",e)}try{Bn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppStateManager",e)}try{Fn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppAdapter",e)}try{On&&On.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AdAdapter",e)}try{Hn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset"," error resetting VideoAdapter",e)}try{Wn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting HostVideoAdapter",e)}try{Yn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting SyncProxy",e)}try{VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.removeHandler("onForeground",tr),VizbeeTV.tv.appLifeCycleManager.removeHandler("onBackground",ir),VizbeeTV.tv.appLifeCycleManager.removeHandler("onEnd",nr))}catch(e){VizbeeSDK.logger.e("SDK","reset","error removing app lifecycle handlers",e)}},framework:cr};window.VizbeeSDK||(window.VizbeeSDK={},VizbeeSDK.logger||(VizbeeSDK.logger=new Ve,VizbeeSDK.logger.setPrefix("[Vizbee]")));var pr=window.VZB;pr=ur,window.VZB=pr;class hr{constructor(){this.platformType="",this.platformConfig={},this.appAdapter=void 0,this.vgaAdapter=void 0,this.videoAdapter=void 0,this.adAdapter=void 0,this.vzbOptions={}}setOptions(e){e||(e={}),this.vzbOptions=e}getOptions(){return this.vzbOptions}initAppOnPlatform(e,t,i,n){this.appAdapter=t.appAdapter||t,this.vgaAdapter=t.vgaAdapter,this.videoAdapter=t.videoAdapter,this.adAdapter=t.adAdapter,this.platformType=i,this.platformConfig=n,this.platformConfig.appId=e,null==this.platformConfig.standalone&&(this.platformConfig.standalone=!0),VizbeeTV.init(this.platformType,this.platformConfig);var r=this.appAdapter.startVideo||function(){},s=this;this.appAdapter.startVideo=function(e,t){t=t||0,s.platformConfig.standalone||s.setVideoGuid(e.id,e.isLive||e.islive),r(e,t)};var o={id:e,app:this.appAdapter,videoAdapter:this.videoAdapter,adAdapter:this.adAdapter,customAttributesForMetrics:{}};this.vgaAdapter?(o.isVGA=!0,o.VGA=this.vgaAdapter):o.video=VizbeeTV.tv.player,o.customAttributesForMetrics=Object.assign(o.customAttributesForMetrics,this.platformConfig.customAttributesForMetrics,this.vzbOptions.customAttributesForMetrics),this.vzbOptions.configServiceProxyHost&&(o.configServiceProxyHost=this.vzbOptions.configServiceProxyHost),VZB.init(o)}setAdAdapterType(e){VZB.setAdType(e)}getAdsAdapter(){return VZB.getAdsAdapter()}setAdsVideo(e){VZB.setAdsVideo(e)}setVideoElement(e){if(!e)return"undefined"!=typeof VizbeeSDK&&VizbeeSDK.logger&&VizbeeSDK.logger.warn("BaseAPIWrapper::setVideoElement - INVALID newVideoElement"),!1;if(!this.platformConfig)return"undefined"!=typeof VizbeeSDK&&VizbeeSDK.logger&&VizbeeSDK.logger.warn("BaseAPIWrapper::setVideoElement - SDK not initialized"),!1;if(this.platformConfig.videoElement===e)return!0;this.platformConfig.videoElement=e;var t=Object.assign({},this.platformConfig,{standalone:!0});return"undefined"!=typeof VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player&&"function"==typeof VizbeeTV.tv.player.reconstruct&&VizbeeTV.tv.player.reconstruct(t),this.setAdsVideo(e),!0}setVideoGuid(e,t){VZB.setVideoGuid(e,t)}setVideoInfo(e){VZB.setVideoInfo(e),this.setVideoGuid(e.id||e.videourl,e.islive)}setVideoStop(){VZB.setVideoStop()}}const gr={};class fr extends hr{get VERSION(){return window.VZB?window.VZB.VERSION:""}init(e,t,i,n){let r=Ie.getPlatformType();r&&this.initAppOnPlatform(e,t,r,i,t.mediaManagerAdapter,n)}initAppOnPlatform(e,t,i,n,r,s){i=i.toLowerCase(),gr[i]&&!t.vgaAdapter?(this._apiWrapper=new gr[i],this._apiWrapper.setOptions(s),this._apiWrapper.initAppOnPlatform(e,t,i,n,r)):(this._apiWrapper=new hr,this._apiWrapper.setOptions(s),this._apiWrapper.initAppOnPlatform(e,t,i,n))}setVideoGuid(e,t){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoGuid(e,t),!0}setVideoInfo(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoInfo(e),!0}setVideoStop(){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoStop(),!0}getAdsManager(){if(this._isAPIWrapperInitialized())return this._apiWrapper.getAdsManager()}setAdsVideo(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setAdsVideo(e),!0}setVideoElement(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoElement(e)}setAdAdapterType(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setAdAdapterType(e),!0}wrapAVPlayerListener(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.wrapAVPlayerListener(e)}_isAPIWrapperInitialized(){return null!=this._apiWrapper}}let vr,yr,mr;class br{constructor(){this.virtualAPIWrapper=ds,this.vzbOptions={}}static getInstance(){return null==vr&&(vr=new br),vr}startWithOptions(e,t){this.vzbOptions=t||{},this.start(e)}start(e){this.isValidAppId(e)&&this.virtualAPIWrapper.init(e,{},{},this.vzbOptions)}isValidAppId(e){if("string"!=typeof e)return!1;let t=new RegExp("^vzb[0-9]+$"),i=new RegExp("^vzb(-[A-Za-z]+)+-[0-9]+$");return t.test(e)||i.test(e)}}class Sr{constructor(){this._configServiceProxyHost=void 0,this._customAttributesForMetrics=void 0}get configServiceProxyHost(){return this._configServiceProxyHost}set configServiceProxyHost(e){this._configServiceProxyHost=e}get customAttributesForMetrics(){return this._customAttributesForMetrics}set customAttributesForMetrics(e){this._customAttributesForMetrics=e}}class _r{get ContinuityContext(){return br}get ContinuityOptions(){return Sr}}class Ir{constructor(){this.deeplinkHandler=void 0,this.vizbeeEventHandler=void 0,this.vizbeeSigninEventHandler=void 0}setSignInHandler(e){"function"==typeof e?this.vizbeeSigninEventHandler=e:vizbee.logger.warn(this.constructor.name+"::setSignInHandler - NO SIGNIN Handler implemented by HostApp")}setDeeplinkHandler(e){"function"==typeof e?this.deeplinkHandler=e:vizbee.logger.warn(this.constructor.name+"::setDeeplinkHandler - NO DEEPLINK Handler implemented by HostApp")}setVizbeeEventHandler(e){"function"==typeof e?this.vizbeeEventHandler=e:vizbee.logger.warn(this.constructor.name+"::setVizbeeEventHandler - NO Event Handler implemented by HostApp")}setVizbeeSigninEventHandler(e){"function"==typeof e?this.vizbeeSigninEventHandler=e:vizbee.logger.warn(this.constructor.name+"::setVizbeeSigninEventHandler - NO Event Handler implemented by HostApp")}}class Tr{static get AD_POD_WAITING(){return"awaiting-ad-pod"}static get AD_POD_START(){return"ad-pod-start"}static get AD_PREPARING(){return"ad-preparing"}static get AD_START(){return"ad-start"}static get AD_PLAYING(){return"ad-playing"}static get AD_PAUSED(){return"ad-paused"}static get AD_END(){return"ad-end"}static get AD_POD_END(){return"ad-pod-end"}static get AD_ERROR(){return"ad-error"}}class Er{constructor(e,t){this._eventType=e,this._eventData=t}set eventType(e){this._eventType=e}get eventType(){return this._eventType}set eventData(e){this._eventData=e}get eventData(){return this._eventData}}class Vr{constructor(e,t){this.type=e,this.data=t}}class Pr{constructor(e,t){this.adType=e,this.playerElement=t,this.vtvPlayerEvent=new Vr}updateAdStatus(e){this._isValidAdStatus(e)?this._handleAdStatus(e):vizbee.logger.verbose("AdAdapter::updateAdStatus - invalid ad status")}_isValidAdStatus(e){return e instanceof Er?-1!=[Tr.AD_POD_WAITING,Tr.AD_PREPARING,Tr.AD_POD_START,Tr.AD_POD_END,Tr.AD_START,Tr.AD_PLAYING,Tr.AD_PAUSED,Tr.AD_END,Tr.AD_ERROR].indexOf(e.eventType)||(vizbee.logger.warn(`AdAdapter::_isValidAdStatus - adStatus event type is invalid: ${e.eventType}`),!1):(vizbee.logger.warn("AdAdapter::_isValidAdStatus - adStatus is not an instance of vizbee.continuity.messages.AdStatus"),!1)}_handleAdStatus(e){e?(vizbee.logger.verbose(`AdAdapter::_handleAdStatus - eventType: ${e.eventType}`),this.vtvPlayerEvent.type=e.eventType,this.vtvPlayerEvent.data=e.eventData||{},VizbeeTV.tv.player.dispatchOnEvent(this.vtvPlayerEvent)):vizbee.logger.warn("AdAdapter::_handleAdStatus - invalid ad status")}}class Ar{constructor(e,t){this.playerType=e,this.playerElement=t,this.playHandler=void 0,this.pauseHandler=void 0,this.seekHandler=void 0,this.stopHandler=void 0,this.videoInfoGetter=void 0,this.tracksGetHandler=void 0,this.enabledTracksGetHandler=void 0,this.enableTracksHandler=void 0,this.disableTracksHandler=void 0,this.vizbeeEventHandler=void 0}setPlayerType(e){e&&(this.playerType=e)}setPlayerElement(e){e&&(this.playerElement=e)}updateVideoInfo(e){window.vizbee&&vizbee.continuity.ContinuityContext.getInstance().setVideoInfo(e)}setVideoInfoGetter(e){"function"==typeof e&&(this.videoInfoGetter=e)}getVideoInfo(){if(this.videoInfoGetter)return this.videoInfoGetter()}setPlayHandler(e){"function"==typeof e&&(this.playHandler=e)}setPauseHandler(e){"function"==typeof e&&(this.pauseHandler=e)}setSeekHandler(e){"function"==typeof e&&(this.seekHandler=e)}setStopHandler(e){"function"==typeof e&&(this.stopHandler=e)}getTracksHandler(e){"function"==typeof e&&(this.tracksGetHandler=e)}getEnabledTracksHandler(e){"function"==typeof e&&(this.enabledTracksGetHandler=e)}setAvailableTracksGetter(e){"function"==typeof e&&(this.tracksGetHandler=e)}setEnabledTracksGetter(e){"function"==typeof e&&(this.enabledTracksGetHandler=e)}setEnableTracksHandler(e){"function"==typeof e&&(this.enableTracksHandler=e)}setDisableTracksHandler(e){"function"==typeof e&&(this.disableTracksHandler=e)}setVizbeeEventHandler(e){"function"==typeof e&&(this.vizbeeEventHandler=e)}}class Cr{static get UNKNOWN(){return"unknown"}static get HTML(){return"html"}static get AVPLAYER(){return"avplayer"}static get BITMOVIN(){return"bitmovin"}static get VIDEOJS(){return"videojs"}static get THEO(){return"theo"}static get SHAKA(){return"shaka"}}class Dr{static get UNKNOWN(){return"unknown"}static get SSAI(){return"ssai"}static get CSAI(){return"csai"}}class kr{constructor(){this._guid="",this._isLive=!1,this._startTime=0,this._videoUrl="",this._deeplink="",this._imgUrl="",this._title="",this._subtitle="",this._desc="",this._tracks=[],this._cuepoints=[],this._customStreamInfo=void 0,this._customMetadata=void 0}toJson(){let e={};return e.id=this._guid,e.islive=this._isLive,e.starttime=this._startTime,e.videourl=this._videoUrl,e.deeplink=this._deeplink,e.imgurl=this._imgUrl,e.title=this._title,e.subtitle=this._subtitle,e.desc=this._desc,e.tracks=this._tracks,e.cuepoints=this._cuepoints,e.customstreaminfo=this._customStreamInfo,e.custommetadata=this._customMetadata,e}fromJson(e){e?(this._guid=e.id,this._isLive=e.islive,this._startTime=e.starttime,this._videoUrl=e.videourl,this._deeplink=void 0!==e.deeplink&&null!==e.deeplink?e.deeplink:"",this._imgUrl=e.imgurl,this._title=e.title,this._subtitle=e.subtitle,this._desc=e.desc,this._tracks=e.tracks,this._cuepoints=e.cuepoints,this._customStreamInfo=e.customstreaminfo,this._customMetadata=e.custommetadata):vizbee.logger.debug(this.constructor.name+"::toJson - invalid syncVideoInfo")}set isLive(e){this._isLive=e}get isLive(){return this._isLive}set guid(e){this._guid=e}get guid(){return this._guid}set videoUrl(e){this._videoUrl=e}get videoUrl(){return this._videoUrl}set deeplink(e){this._deeplink=e}get deeplink(){return this._deeplink}set imgUrl(e){this._imgUrl=e}get imgUrl(){return this._imgUrl}set title(e){this._title=e}get title(){return this._title}set subtitle(e){this._subtitle=e}get subtitle(){return this._subtitle}set desc(e){this._desc=e}get desc(){return this._desc}set startTime(e){this._startTime=e}get startTime(){return this._startTime}set tracks(e){this._tracks=e}get tracks(){return this._tracks}set cuepoints(e){this._cuepoints=e}get cuepoints(){return this._cuepoints}set customStreamInfo(e){this._customStreamInfo=e}get customStreamInfo(){return this._customStreamInfo}set customMetadata(e){this._customMetadata=e}get customMetadata(){return this._customMetadata}}class wr{static get IDLE(){return"idle"}static get PREPARING(){return"preparing"}static get LOADING(){return"loading"}static get STARTED(){return"started"}static get PLAYING(){return"playing"}static get PAUSED(){return"paused"}static get BUFFERING(){return"buffering"}static get INTERRUPTED(){return"interrupted"}static get ENDED(){return"ended"}static get ERROR(){return"error"}}class Nr{constructor(){this._guid="",this._state=wr.IDLE,this._currentPosition=-1,this._duration=-1,this._isLive=!1,this._isDvrSupported=!1,this._title="",this._subtitle="",this._videoUrl="",this._imgUrl=""}set guid(e){this._guid=e}get guid(){return this._guid}set state(e){this._state=e}get state(){return this._state}set currentPosition(e){this._currentPosition=e}get currentPosition(){return this._currentPosition}set duration(e){this._duration=e}get duration(){return this._duration}set isLive(e){this._isLive=e}get isLive(){return this._isLive}set isDvrSupported(e){this._isDvrSupported=e}get isDvrSupported(){return this._isDvrSupported}set title(e){this._title=e}get title(){return this._title}set subtitle(e){this._subtitle=e}get subtitle(){return this._subtitle}set videoUrl(e){this._videoUrl=e}get videoUrl(){return this._videoUrl}set imgUrl(e){this._imgUrl=e}get imgUrl(){return this._imgUrl}}class Mr{constructor(){this._type="",this._data=void 0}set type(e){this._type=e}get type(){return this._type}set data(e){this._data=e}get data(){return this._data}}class Or extends br{constructor(){super(),this.appAdapter=new Ir,this.playerAdapter=void 0,this.adAdapter=void 0,this.adType=void 0}static getInstance(){return null==yr&&(yr=new Or,vizbee.logger.d(this.constructor.name,"getInstance","created")),yr}getAppAdapter(){return this.appAdapter}setAppAdapter(e){e instanceof Ir&&(this.appAdapter=e)}getPlayerAdapter(){return this.playerAdapter}setPlayerAdapter(e){if(!this._isPlatformPlayerInitialized())return vizbee.logger.w("DefaultContinuityContext::setPlayerAdapter - Vizbee platform player not initialized"),!1;if(!this._isValidPlayerAdapter(e))return vizbee.logger.w("DefaultContinuityContext::setPlayerAdapter - playerAdapter should be valid and of type vizbee.continuity.adapters.PlayerAdapter"),!1;this.playerAdapter=e;let t=this._buildPlatformConfig(e);return VizbeeTV.tv.player.reconstruct(t),this._setAdAdapter(),!0}removePlayerAdapter(e){return this._isPlatformPlayerInitialized()?(this.stopVideo(),this.playerAdapter=void 0,!0):(vizbee.logger.w(this.constructor.name,"resetPlayerAdapter","Vizbee platform player not initialized"),!1)}setPlayerAdapterWithVideoInfo(e,t){return!!this.setPlayerAdapter(e)&&this.setVideoInfo(t)}setVideoInfo(e){return!!this._isValidVideoInfo(e)&&this.virtualAPIWrapper.setVideoInfo(e.toJson())}getVideoInfo(){if(this.playerAdapter&&this.playerAdapter.getVideoInfo){let e=this.playerAdapter.getVideoInfo();if(e instanceof Nr)return e}}getAdAdapter(e){return this.adAdapter}setAdAdapter(e){return e instanceof Pr?this._isValidAdType(e.adType)?(this.adAdapter=e,this.setAdType(Dr.CSAI),void this._setAdAdapter()):(vizbee.logger.w("DefaultContinuityContext::setAdAdapter - adAdapter.adType is INVALID"),!1):(vizbee.logger.w("DefaultContinuityContext::setAdAdapter - AdAdapter should be of type vizbee.continuity.adapters.AdAdapter"),!1)}removeAdAdapter(e){this.adAdapter=void 0}setAdType(e){this._isValidAdType(e)&&(this.adType=e,this._setAdAdapter())}start(e){if(!this.isValidAppId(e))return;let t={};t.appAdapter={startVideo:e=>{if(this.appAdapter&&this.appAdapter.deeplinkHandler){let t=new kr;t.fromJson(e),this.appAdapter.deeplinkHandler(t)}else vizbee.logger.w(this.constructor.name,"startVideo","NO DEEPLINK HANDLER")},onEvent:e=>{if(this.appAdapter&&this.appAdapter.vizbeeSigninEventHandler&&e&&"tv.vizbee.homesign.signin"===e.type){let t=new Mr;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeSigninEventHandler(t)}if(this.appAdapter&&this.appAdapter.vizbeeEventHandler&&e){let t=new Mr;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeEventHandler(t)}if(this.playerAdapter&&this.playerAdapter.vizbeeEventHandler&&e){let t=new Mr;t.type=e.type,t.data=e.data,this.playerAdapter.vizbeeEventHandler(t)}},playVideo:()=>!(!this.playerAdapter||!this.playerAdapter.playHandler||(this.playerAdapter.playHandler(),0)),pauseVideo:()=>!(!this.playerAdapter||!this.playerAdapter.pauseHandler||(this.playerAdapter.pauseHandler(),0)),seekVideo:e=>!(!this.playerAdapter||!this.playerAdapter.seekHandler||(this.playerAdapter.seekHandler(e),0)),stopVideo:e=>!(!this.playerAdapter||!this.playerAdapter.stopHandler||(this.playerAdapter.stopHandler(e),0)),getTracks:()=>!(!this.playerAdapter||!this.playerAdapter.tracksGetHandler)&&this.playerAdapter.tracksGetHandler(),getEnabledTracks:()=>!(!this.playerAdapter||!this.playerAdapter.enabledTracksGetHandler)&&this.playerAdapter.enabledTracksGetHandler(),enableTracks:e=>!(!this.playerAdapter||!this.playerAdapter.enableTracksHandler||(this.playerAdapter.enableTracksHandler(e),0)),disableTracks:e=>!(!this.playerAdapter||!this.playerAdapter.disableTracksHandler||(this.playerAdapter.disableTracksHandler(e),0)),getVideoInfo:()=>this._buildSyncVideoInfo()},this.virtualAPIWrapper.init(e,t,{},this.vzbOptions)}stopVideo(){vizbee.logger.d(this.constructor.name,"stopVideo"),this.virtualAPIWrapper&&this.virtualAPIWrapper.setVideoStop&&(vizbee.logger.d(this.constructor.name,"stopVideo","calling setVideoStop"),this.virtualAPIWrapper.setVideoStop())}_buildPlatformConfig(e){let t={standalone:!0,videoElement:e.playerElement,vtvPlayerListConfig:[{type:"native"}]};return e.playerType==Cr.BITMOVIN&&(t.vtvPlayerListConfig=[{type:"bitmovin"}]),e.playerType==Cr.VIDEOJS&&(t.vtvPlayerListConfig=[{type:"videojs"}]),e.playerType==Cr.THEO&&(t.vtvPlayerListConfig=[{type:"theo"}]),e.playerType==Cr.SHAKA&&(t.vtvPlayerListConfig=[{type:"shaka"}]),t}_isValidVideoInfo(e){return e instanceof kr||(vizbee.logger.w(this.constructor.name,"_isValidVideoInfo","videoInfo should be of type vizbee.continuity.messages.VideoInfo"),!1)}_isValidPlayerAdapter(e){return e instanceof Ar?!(e&&!e.playerElement&&(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should contain playerElement"),1)):(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should be of type vizbee.continuity.adapters.PlayerAdapter"),!1)}_isPlatformInitialized(){return VizbeeTV&&VizbeeTV.tv}_isPlatformPlayerInitialized(){return this._isPlatformInitialized()&&VizbeeTV.tv.player}_isValidAdType(e){return e?e==Dr.SSAI||e==Dr.CSAI||(vizbee.logger.w(`DefaultContinuityContext::_isValidAdType - adType is invalid: ${e}`),!1):(vizbee.logger.w("DefaultContinuityContext::_isValidAdType - adType is undefined"),!1)}_mapPlayerStateToSyncState(e){return{idle:"UNKNOWN",preparing:"UNKNOWN",loading:"BUFFERING",started:"PLAYING",playing:"PLAYING",paused:"PAUSED_BY_USER",buffering:"BUFFERING",interrupted:"INTERRUPTED",ended:"FINISHED",error:"FAILED"}[e]||e}_getAdAdapterType(e){if(e&&e.playerType)return this.adType==Dr.CSAI?"vzb_ad_default":this.adType==Dr.SSAI?e.playerType==Cr.AVPLAYER?"vzb_ad_ssai_avplay":"vzb_ad_default":void 0;vizbee.logger.w(this.constructor.name,"_getAdAdapterType","INVALID playerAdapter")}_buildSyncVideoInfo(){if(!this.playerAdapter||!this.playerAdapter.getVideoInfo)return;let e=this.playerAdapter.getVideoInfo();if(!(e instanceof Nr))return;let t={};return e.guid&&(t.id=e.guid),e.videoUrl&&(t.videourl=e.videoUrl),null!=e.isLive&&(t.islive=!!e.isLive),!1!==e.isDvrSupported&&(t.isdvrsupported=e.isDvrSupported),e.title&&(t.title=e.title),e.subtitle&&(t.subtitle=e.subtitle),e.imgUrl&&(t.imgurl=e.imgUrl),e.currentPosition>=0&&(t.position=e.currentPosition),e.duration>=0&&(t.duration=e.duration),t}_setAdAdapter(){let e=this._getAdAdapterType(this.playerAdapter);e&&this.virtualAPIWrapper&&VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player&&(this.virtualAPIWrapper.setAdAdapterType(e),this.virtualAPIWrapper.setAdsVideo(VizbeeTV.tv.player))}}class xr{constructor(e){e=e||{},this._getStatus=e.getStatus,this._getPlayer=e.getPlayer,this._isPlaybackActive=e.isPlaybackActive,this._setVideoGuid=e.setVideoGuid,this._intervalMs="number"==typeof e.intervalMs&&e.intervalMs>0?e.intervalMs:850,this._logger=e.logger||{debug:function(){},warn:function(){}},this._timer=void 0,this._lastGuid=void 0}start(){this._timer||(this._logger.debug("V2StatusPoller::start",this._intervalMs),this._timer=setInterval(()=>this._onTick(),this._intervalMs))}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._lastGuid=void 0,this._logger.debug("V2StatusPoller::stop")}_onTick(){let e;try{e=this._getStatus&&this._getStatus()}catch(e){return void this._logger.warn("V2StatusPoller::_onTick - getter threw",e)}if(!e)return;const t=this._getPlayer&&this._getPlayer();if(!t)return;const i=e.id;i&&i!==this._lastGuid&&("function"==typeof this._setVideoGuid&&this._setVideoGuid(i,!!e.islive),this._lastGuid=i),t.setPositionMs(e.position),t.setDurationMs(e.duration),this._isPlaybackActive&&!this._isPlaybackActive()||t.dispatchOnTimeUpdate(t.currentTime())}}class Lr extends Or{constructor(){super(),this._statusPoller=void 0,this._lastPushedEventType=void 0}static getInstance(){return null==mr&&(mr=new Lr,vizbee.logger.d("ElementlessContinuityContext","getInstance","created")),mr}setPlayerAdapter(e){let t=super.setPlayerAdapter(e);return t&&this._updateStatusPoller(e),t}removePlayerAdapter(e){return this.notifyPlayerState(wr.INTERRUPTED),this._stopStatusPoller(),super.removePlayerAdapter(e)}notifyPlayerState(e){const t=this._mapStateToEventType(e);if(!t)return;this._lastPushedEventType=t;const i=VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player?VizbeeTV.tv.player.currentPlayer:void 0;i&&this._fireOnPlayer(i,t)}_isPlaybackActive(){return void 0===this._lastPushedEventType||"playing"===this._lastPushedEventType}_mapStateToEventType(e){return{loading:"loading",buffering:"loading",started:"playing",playing:"playing",paused:"paused",paused_by_user:"paused",interrupted:"interrupted",ended:"ended",finished:"ended",error:"error",failed:"error"}[String(e).toLowerCase()]||null}_fireOnPlayer(e,t){switch(t){case"loading":e.dispatchOnLoading();break;case"playing":e.dispatchOnPlaying();break;case"paused":e.dispatchOnPaused();break;case"ended":e.dispatchOnEnded();break;case"interrupted":e.dispatchOnInterrupted({reason:"host"});break;case"error":e.dispatchOnError({reason:"host"})}}_isValidPlayerAdapter(e){return e instanceof Ar?!(!e.playerElement&&!e.videoInfoGetter&&(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should contain a playerElement or a videoInfoGetter"),1)):(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should be of type vizbee.continuity.adapters.PlayerAdapter"),!1)}_buildPlatformConfig(e){return e&&e.playerElement?super._buildPlatformConfig(e):{standalone:!0,vtvPlayerListConfig:[{type:"native"}],playerType:e&&e.playerType}}_updateStatusPoller(e){if(this._stopStatusPoller(),!e||!e.videoInfoGetter)return;this._lastPushedEventType=void 0;let t=this;this._statusPoller=new xr({intervalMs:this.vzbOptions&&this.vzbOptions.statusPollIntervalMs,logger:vizbee&&vizbee.logger,getStatus:()=>t._buildSyncVideoInfo(),getPlayer:()=>VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player?VizbeeTV.tv.player.currentPlayer:void 0,isPlaybackActive:()=>t._isPlaybackActive(),setVideoGuid:(e,i)=>{t.virtualAPIWrapper&&t.virtualAPIWrapper.setVideoGuid&&t.virtualAPIWrapper.setVideoGuid(e,i)}}),this._statusPoller.start()}_stopStatusPoller(){this._statusPoller&&(this._statusPoller.stop(),this._statusPoller=void 0)}}class zr extends Ar{constructor(e){super(Cr.HTML,e)}}class Rr{constructor(){this.playHandler=void 0,this.pauseHandler=void 0,this.seekHandler=void 0,this.stopHandler=void 0,this.videoInfoGetter=void 0,this.enableTracksHandler=void 0,this.disableTracksHandler=void 0,this.availableTracksGetter=void 0,this.enabledTracksGetter=void 0,this.vizbeeEventHandler=void 0}updateVideoInfo(e){window.vizbee&&vizbee.continuity.ContinuityContext.getInstance().setVideoInfo(e)}setVideoInfoGetter(e){"function"==typeof e&&(this.videoInfoGetter=e)}getVideoInfo(){if(this.videoInfoGetter)return this.videoInfoGetter()}updateVideoStatus(e){}setPlayHandler(e){"function"==typeof e&&(this.playHandler=e)}setPauseHandler(e){"function"==typeof e&&(this.pauseHandler=e)}setSeekHandler(e){"function"==typeof e&&(this.seekHandler=e)}setStopHandler(e){"function"==typeof e&&(this.stopHandler=e)}setAvailableTracksGetter(e){"function"==typeof e&&(this.availableTracksGetter=e)}setEnabledTracksGetter(e){"function"==typeof e&&(this.enabledTracksGetter=e)}setEnableTracksHandler(e){"function"==typeof e&&(this.enableTracksHandler=e)}setDisableTracksHandler(e){"function"==typeof e&&(this.disableTracksHandler=e)}setVizbeeEventHandler(e){"function"==typeof e&&(this.vizbeeEventHandler=e)}}class Kr extends Y{constructor(e){if(!(e instanceof Y))throw new TypeError("BasePlayerExtension::constructor() - playerToExtend must be instance of BasePlayerExtensible.");super(e.platform),this.extendedPlayer=e,this.parentExtension=null,this.isExtendedPlayerBasePlayer()||(this.extendedPlayer.parentExtension=this),this.registerEvents(this.extendedPlayer,this),VizbeeTV.logger.debug(this.constructor.name+"::constructed")}registerEvents(e,t){e&&t?(e.onLoading=e=>{this.onLoadingHandler.call(t,e)},e.onStarted=e=>{this.onStartedHandler.call(t,e)},e.onPlaying=e=>{this.onPlayingHandler.call(t,e)},e.onPaused=e=>{this.onPausedHandler.call(t,e)},e.onBuffering=e=>{this.onBufferingHandler.call(t,e)},e.onBufferingComplete=e=>{this.onBufferingCompleteHandler.call(t,e)},e.onTimeUpdate=e=>{this.onTimeUpdateHandler.call(t,e)},e.onInterrupted=e=>{this.onInterruptedHandler.call(t,e)},e.onEnded=e=>{this.onEndedHandler.call(t,e)},e.onError=e=>{this.onErrorHandler.call(t,e)},e.onEvent=e=>{this.onEventHandler.call(t,e)}):VizbeeTV.logger.error(this.constructor.name+"::registerEvents - MISSING playerToExtend/currentPlayer")}reconstruct(e){this.extendedPlayer.reconstruct(e)}beforeStart(e){super.start(e)}start(e){this.beforeStart(e),this.extendedPlayer.start(e)}play(){this.extendedPlayer.play()}pause(){this.extendedPlayer.pause()}togglePlayPause(){VizbeeTV.logger.debug("BasePlayerExtension::togglePlayPause() -- called"),this.extendedPlayer.togglePlayPause()}stop(e){this.extendedPlayer.stop(e)}seek(e){this.extendedPlayer.seek(e)}currentTime(){return this.extendedPlayer.currentTime()}getDuration(){return this.extendedPlayer.getDuration()}getStartTime(){return this.extendedPlayer.getStartTime()}getBufferLevel(){return this.extendedPlayer.getBufferLevel()}getAudioBufferLevel(){return this.extendedPlayer.getAudioBufferLevel()}getCurrentState(){return this.extendedPlayer.getCurrentState()}getCurrentVersion(){return this.extendedPlayer.getCurrentVersion()}getTracks(e){return this.extendedPlayer.getTracks(e)}getEnabledTracks(e){return this.extendedPlayer.getEnabledTracks(e)}setTracks(e){return this.extendedPlayer.setTracks(e)}enableTracks(e){this.extendedPlayer.enableTracks(e)}disableTracks(e){this.extendedPlayer.disableTracks(e)}changeAudioTrack(e){this.extendedPlayer.changeAudioTrack(e)}doAction(e){return this.extendedPlayer.doAction(e)}getName(){return this.extendedPlayer.getName()}destroy(){this.resetListeners(),this.extendedPlayer.destroy()}getStreamQualityInfo(){return this.extendedPlayer?this.extendedPlayer.getStreamQualityInfo():{}}setStreamQualityInfo(e){this.extendedPlayer&&this.extendedPlayer.setStreamQualityInfo(e)}resetStreamQualityInfo(){this.extendedPlayer&&this.extendedPlayer.resetStreamQualityInfo()}get basePlayer(){return this.isExtendedPlayerBasePlayer()?this.extendedPlayer.currentPlayer:this.extendedPlayer instanceof Kr?this.extendedPlayer.basePlayer:void 0}isExtendedPlayerBasePlayer(){return this.extendedPlayer instanceof Y&&!(this.extendedPlayer instanceof Kr)}get parentPlayer(){return this.parentExtension}onLoadingHandler(e){this.dispatchOnLoading.call(this,e)}onStartedHandler(e){this.dispatchOnStarted.call(this,e)}onPlayingHandler(e){this.dispatchOnPlaying.call(this,e)}onPausedHandler(e){this.dispatchOnPaused.call(this,e)}onBufferingHandler(e){this.dispatchOnBuffering.call(this,e)}onBufferingCompleteHandler(e){this.dispatchOnBufferingComplete.call(this,e)}onTimeUpdateHandler(e){this.dispatchOnTimeUpdate.call(this,e)}onInterruptedHandler(e){this.dispatchOnInterrupted.call(this,e)}onEndedHandler(e){this.dispatchOnEnded.call(this,e)}onErrorHandler(e){this.dispatchOnError.call(this,e)}onEventHandler(e){this.dispatchOnEvent.call(this,e)}}class Ur extends Ar{constructor(){super(Cr.AVPLAYER,webapis.avplay)}setPlayerType(e){}setPlayerElement(e){}wrapListener(e){let t=this._getVTVAVPlayer();return null==t?(vizbee.logger.warn(this.constructor.name+"::wrapListener - can't get AVPlayer"),e):t.wrapAVPlayerListener(e)}getListener(){let e=this._getVTVAVPlayer();if(null!=e)return e.getListener();vizbee.logger.warn(this.constructor.name+"::getListener - can't get AVPlayer")}_getVTVAVPlayer(){if(!this.playerElement)return;let e,t;if(VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player)return e=VizbeeTV.tv.player,Object.getPrototypeOf(e.constructor).name===Kr.name?t=e.basePlayer:Object.getPrototypeOf(e.constructor).name===Y.name&&(t=e.currentPlayer),t&&"avplayer"==t.getName().toLowerCase()?t:void vizbee.logger.warn(this.constructor.name+"::_getVTVAVPlayer - can't get AVPlayer");vizbee.logger.warn(this.constructor.name+"::_getVTVAVPlayer - can't get platform player")}}class Br{static get STOP_REASON_UNKNOWN(){return"stop_reason_unknown"}static get STOP_BY_USER(){return"stop_by_user"}static get STOP_IMPLICIT(){return"stop_implicit"}static get STOP_REASON_BEFORE_NEXT_VIDEO(){return"stop_reason_before_next_video"}}class Fr{constructor(){}wasAppLaunchedByVizbee(){return!!VizbeeTV.tv.launchParamsDeferral&&VizbeeTV.tv.launchParamsDeferral.isLaunchedbyVizbee()}wasVideoStartedByVizbee(){return VZB.wasVideoStartedByVizbee()}addProvider(e,t){const i=VZB.getMetricsManager();i&&i.addProvider(e,t)}removeProvider(e){const t=VZB.getMetricsManager();t&&t.removeProvider(e)}logMetrics(e,t){const i=VZB.getMetricsManager();i&&i.trackEvent(e,t)}setCustomAttributes(e){const t=VZB.getMetricsManager();t&&t.setCustomProperties(e)}}class Gr{constructor(){this._type="",this._id=-1}toJSON(){return{type:this._type,id:this._id}}fromJSON(e){e&&e.type&&!isNaN(e.id)?(this._type=e.type,this._id=e.id):VizbeeSDK.logger.verbose("Track::fromJSON - invalid trackInfo")}set type(e){this._type=e}get type(){return this._type}set id(e){this._id=e}get id(){return this._id}}class Hr extends Gr{constructor(){super(),this.type=n,this.subtype="",this._lang=""}toJSON(){let e=super.toJSON();return e.lang=this._lang,e.subtype=this._subtype,e}fromJSON(e){e?(e.type=e.type||this.type,super.fromJSON(e),this._lang=e.lang,this._subtype=e.subtype):VizbeeSDK.logger.verbose("SubtitleTrack::fromJSON - invalid trackInfo")}set lang(e){this._lang=e}get lang(){return this._lang}set subtype(e){this._subtype=e}get subtype(){return this._subtype}}class Wr{constructor(){this.state={message:"This is vizbee snackbar!",theme:{color:"#FFFFFF",bgColor:"#7F98DE"},layout:{position:""},border:{color:"#FFFFFF"},font:{uri:"",family:"",size:24,weight:""},icon:{uri:"https://static.claspws.tv/screen/icons/common/user_icon_white.png"}},this.uiContainer=document.getElementsByTagName("body")[0],this.uiContainer&&(this._setupCSS(),this.render(this.uiContainer),this.isCurrentAnimationShowingUI=void 0)}render(e){this.nodes||e&&(this.nodes={},this.nodes.popupMessageWithIconOverlay=document.createElement("div"),this.nodes.popupMessageWithIconOverlay.id="vizbeeSnackbarOverlay",this.nodes.popupMessageWithIconOverlay.className="opaqueBackground hidden",this.nodes.popupMessageWithIconContainer=document.createElement("div"),this.nodes.popupMessageWithIconContainer.id="popupTimedoutMessageWithIconUIContainer",this.nodes.popupMessageWithIconContainer.className="popupTimedoutMessageWithIconUIContainer",this.nodes.popupMessageWithIconContainer.style.color=this.state.theme.color,this.nodes.popupTimedoutIconEle=document.createElement("div"),this.nodes.popupTimedoutIconEle.id="popupTimedoutIconEle",this.nodes.popupTimedoutIconEle.className="popupTimedoutIconEle",this.nodes.popupTimedoutMessageEle=document.createElement("div"),this.nodes.popupTimedoutMessageEle.id="popupTimedoutMessageEle",this.nodes.popupTimedoutMessageEle.className="popupMessageEle",this.nodes.popupMessageWithIconContainer.appendChild(this.nodes.popupTimedoutIconEle),this.nodes.popupMessageWithIconContainer.appendChild(this.nodes.popupTimedoutMessageEle),this.nodes.popupMessageWithIconOverlay.appendChild(this.nodes.popupMessageWithIconContainer),e.appendChild(this.nodes.popupMessageWithIconOverlay),this._updateUI())}setOptions(e){e&&(this.state.message=e.message||this.state.message,this.state.theme.color=e.theme.color||this.state.theme.color,this.state.theme.bgColor=e.theme.bgColor||this.state.theme.bgColor,this.state.layout.position=e.layout.position||this.state.layout.position,this.state.border.color=e.border.color||this.state.border.color,this.state.font.uri=e.font.uri||this.state.font.uri,this.state.font.family=e.font.family||this.state.font.family,this.state.font.size=this.screenRatio*(e.font.size||this.state.font.size),this.state.font.weight=e.font.weight||this.state.font.weight,this.state.icon.uri=e.icon.uri||this.state.icon.uri,this._updateUI(),this.show())}show(){this.nodes&&this.nodes.popupMessageWithIconOverlay&&(this._showUIWithAnimation(),D.removeClass("hidden",this.nodes.popupMessageWithIconOverlay))}hide(){this.nodes&&this.nodes.popupMessageWithIconOverlay&&this.nodes.popupMessageWithIconContainer&&(D.addClass("hidden",this.nodes.popupMessageWithIconOverlay),this.uiContainer&&this.uiContainer.contains(this.nodes.popupMessageWithIconOverlay)&&this.nodes.popupMessageWithIconOverlay.parentNode.removeChild(this.nodes.popupMessageWithIconOverlay))}_updateUI(){if(!this.nodes)return;let e=this.nodes.popupMessageWithIconContainer;if(e){e.style.color=this.state.theme.color,e.style.backgroundColor=this.state.theme.bgColor,null!=this.state.border.color&&(e.style.borderColor=this.state.border.color);const t=this.state.layout.position;if(t){delete e.style.top,delete e.style.right,delete e.style.bottom,delete e.style.left,e.style.position=t;const i=30*this.screenRatio+"px";t.indexOf("top")>-1?(e.style.top=i,t.indexOf("left")>-1?e.style.left=i:e.style.right=i):(e.style.bottom=i,t.indexOf("left")>-1?e.style.left=i:e.style.right=i)}}let t=this.nodes.popupTimedoutMessageEle;t&&(null!=this.state.font.uri&&(t.style.fontFamily=this.state.font.family),null!=this.state.font.size&&(t.style.fontSize=this.state.font.size+"px"),null!=this.state.font.weight&&(t.style.fontWeight=this.state.font.weight),null!=this.state.font.color&&(t.style.color=this.state.font.color),t.innerHTML=this.state.message);let i=this.nodes.popupTimedoutIconEle;i&&(this.state.icon.uri?(i.style.minWidth=36*this.screenRatio+"px",i.style.minHeight=36*this.screenRatio+"px",i.style.backgroundImage="url('"+this.state.icon.uri+"')",t&&(t.style.paddingLeft=12*this.screenRatio+"px")):(i.style.minWidth="0px",i.style.width="0px",t&&(t.style.paddingLeft="0px")))}_showUIWithAnimation(){this.isCurrentAnimationShowingUI=!0,T.get(this.state,["layout","position"],"").indexOf("top")>-1?this._showSlidingFromTopToBottom():this._showSlidingFromBottomToTop()}_isAnimationSupported(e){return e&&"function"==typeof e.animate}_showSlidingFromBottomToTop(){if(!this.nodes||!this.nodes.popupMessageWithIconContainer)return;if(!this._isAnimationSupported(this.nodes.popupMessageWithIconContainer))return void VizbeeTV.logger.i("PopupMessageWithIconView","_showSlidingFromBottomToTop","animation NOT supported!");const e=this.nodes.popupMessageWithIconContainer.offsetHeight+50,t=[{transform:"translateY("+e+"px)"},{transform:"translateY("+e/2+"px)"},{transform:"translateY(0px)"}];this.nodes.popupMessageWithIconContainer.animate(t,{duration:300,iterations:1})}_showSlidingFromTopToBottom(){if(!this.nodes||!this.nodes.popupMessageWithIconContainer)return;if(!this._isAnimationSupported(this.nodes.popupMessageWithIconContainer))return void VizbeeTV.logger.i("PopupMessageWithIconView","_showSlidingFromTopToBottom","animation NOT supported!");const e=this.nodes.popupMessageWithIconContainer.offsetHeight+50,t=[{transform:"translateY(-"+e+"px)"},{transform:"translateY(-"+e/2+"px)"},{transform:"translateY(0px)"}];this.nodes.popupMessageWithIconContainer.animate(t,{duration:300,iterations:1})}_setupCSS(){this.screenRatio=this._getScreenRatio();let e=this._processCSS(this.screenRatio,"\n #vizbeeSnackbarOverlay {\n position: absolute;\n top: 0px;\n left: 0px;\n width: $1280px;\n height: $720px;\n background: transparent !important;\n z-index: 9999;\n }\n\n #popupTimedoutMessageWithIconUIContainer {\n position: absolute;\n display: inline-flex;\n align-items: center;\n max-width: $420px;\n max-height: $80px;\n background: white;\n border-color: #FFFFFF;\n border: solid;\n border-width: $1px;\n border-radius: $45px;\n padding: $10px $24px;\n text-align: left !important;\n }\n\n #popupTimedoutIconEle {\n width: $36px;\n height: $36px;\n min-width: $36px;\n min-height: $36px;\n background-size: contain;\n background-repeat: no-repeat;\n }\n\n #popupTimedoutMessageEle {\n padding-left: $12px;\n }\n");this._appendToHEAD("vizbeeSnackbarCSS",e)}_processCSS(e,t){if(t)return t.replace(/\$[0-9]+/gi,function(t){let i=t.split("$");return Math.ceil(e*i[1])})}_getScreenRatio(){return document.body.clientWidth/1280}_appendToHEAD(e,t){if(this._isEmpty(e))return;if(this._isEmpty(t))return;let i=document.getElementById(e);if(null!==i&&i instanceof HTMLStyleElement)return;let n=document.createElement("style");n.type="text/css",n.id=e,n.styleSheet?n.styleSheet.cssText=t:n.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(n)}_isEmpty(e){return void 0===e||0==e.length||null==e}}class jr{constructor(e){this.uiConfig=e,this.popupMessageWithIconView=void 0}show(e=8){this.hide(),this.uiConfig&&"function"==typeof this.uiConfig.toJSON?(this.popupMessageWithIconView=new Wr,this.popupMessageWithIconView.setOptions(this.uiConfig.toJSON()),-1!==e&&setTimeout(()=>{this.popupMessageWithIconView.hide()},1e3*e)):VizbeeTV.logger.e("PopupMessageWithIconView","show","Invalid uiConfig")}hide(){this.popupMessageWithIconView&&this.popupMessageWithIconView.hide();let e=document.getElementById("vizbeeSnackbarOverlay");e&&(VizbeeTV.logger.i("PopupMessageWithIconView","hide","Removing vizbeeSnackbarEle"),e.parentNode.removeChild(e))}}const qr={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"};class Yr{constructor(){this._message="This is a vizbee snackbar message",this._theme={color:"#FFFFFF",bgColor:"#7F98DE"},this._layout={position:qr.BOTTOM_RIGHT},this._border={color:"#FFFFFF"},this._font={uri:"",family:"",size:24,weight:""},this._icon={uri:"https://s3.amazonaws.com/vga-videos/images/vsa/loading.gif"}}get message(){return this._message}set message(e){this._message=e}get theme(){return this._theme}set theme(e){this._theme=e}get layout(){return this._layout}set layout(e){this._layout=e}get border(){return this._border}set border(e){this._border=e}get font(){return this._font}set font(e){this._font=e}get icon(){return this._icon}set icon(e){this._icon=e}fromJSON(e){e&&(this._message=e.message,e.theme&&(this._theme.color=e.theme.color||this._theme.color,this._theme.bgColor=e.theme.bgColor||this._theme.bgColor),e.layout&&(this._layout=e.layout||this._layout),e.border&&(this._border=e.border||this._border),e.font&&(this._font.uri=e.font.uri||this._font.uri,this._font.family=e.font.family||this._font.family,this._font.size=e.font.size||this._font.size,this._font.weight=e.font.weight||this._font.weight),e.icon&&e.icon.uri&&(this._icon.uri=e.icon.uri||this._icon.uri))}toJSON(){return{message:this._message,theme:this._theme,layout:this._layout,border:this._border,font:this._font,icon:this._icon}}}function Jr(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class $r{constructor(){Jr(this,"namespaceAndReceiverMap",new Map)}async send(e,t){return VizbeeSDK.logger.debug(this.constructor.name,"send",`namespace: ${t}, payload: ${JSON.stringify(e)}`),new Promise((i,n)=>{window.VZB.sendXMessage(e,t,{onSuccess:e=>{i()},onFailure:e=>{n(e)}})})}addReceiver(e,t){VizbeeSDK.logger.debug(this.constructor.name,"addReceiver",`with namespace: ${e}`),this.namespaceAndReceiverMap.set(e,t)}removeReceiver(e,t){VizbeeSDK.logger.debug(this.constructor.name,"removeReceiver",`with namespace: ${e}`),this.namespaceAndReceiverMap.delete(e)}onReceive(e,t,i){VizbeeSDK.logger.debug(this.constructor.name,"onReceive",`namespace: ${e}, payload: ${JSON.stringify(t)}, device: ${i}`);const n=this.namespaceAndReceiverMap.get(e);n&&n(t,e,i)}}let Qr=function(e){return e.ANDROID_MOBILE="Android",e.IOS="iOS",e.UNKNOWN="Unknown",e}({}),Zr=function(e){return e.ANDROID_MOBILE="ANDROID_MOBILE",e.IOS="IOS",e.UNKNOWN="UNKNOWN",e}({});function Xr(e){switch(e){case Qr.ANDROID_MOBILE:return Zr.ANDROID_MOBILE;case Qr.IOS:return Zr.IOS;case Qr.UNKNOWN:default:return Zr.UNKNOWN}}let es=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({}),ts=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({});class is{constructor(){Jr(this,"presenceCallbacks",[]),Jr(this,"syncController",null),this.init()}init(){var e,t,i;this.syncController=null===(e=window.VZB)||void 0===e||null===(t=e.getSyncController)||void 0===t?void 0:t.call(e),this.syncController?this.listenForSyncControllerSessionState():(null===(i=window.VizbeeSDK)||void 0===i||null===(i=i.logger)||void 0===i||i.warn("VizbeeBicastMemberPresenceClientImpl","init","syncController is not available"),this.listenForSyncControllerAvailability())}listenForSyncControllerAvailability(){var e,t;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerAvailability","waiting for syncController to be available"),null===(t=window.VZB)||void 0===t||t.addSyncReadyListener(()=>{var e,t,i;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerAvailability","syncController is now available"),this.syncController=null===(t=window.VZB)||void 0===t||null===(i=t.getSyncController)||void 0===i?void 0:i.call(t),this.listenForSyncControllerSessionState()})}listenForSyncControllerSessionState(){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerSessionState","subscribing to presence events"),this.syncController.subscribeToPresence(e=>{if(VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerSessionState",`presence event received: ${JSON.stringify(e)}`),null!==e){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerSessionState",`processing presence event: ${JSON.stringify(e)}`);const t=this.toVizbeeDevice(e.member),i={event:e.event===ts.JOIN?es.JOIN:es.LEAVE,device:t};this.presenceCallbacks.forEach(e=>e(i))}})}subscribe(e){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","subscribe",e),this.presenceCallbacks.push(e)}unsubscribe(e){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","unsubscribe","");const t=this.presenceCallbacks.indexOf(e);t>-1&&this.presenceCallbacks.splice(t,1)}getMembers(){var e,t;const i=(null===(e=this.syncController)||void 0===e||null===(t=e.getActiveSenders)||void 0===t?void 0:t.call(e))||{};return Object.values(i).map(e=>this.toVizbeeDevice(e))}toVizbeeDevice(e){var t,i,n,r,s,o,a,d,l,c,u;return{deviceId:null!==(t=null==e||null===(i=e.ssinfo)||void 0===i?void 0:i.REMOTE_DEVICE_ID)&&void 0!==t?t:"UNKNOWN",friendlyName:null!==(n=null==e||null===(r=e.ssinfo)||void 0===r?void 0:r.REMOTE_FRIENDLY_NAME)&&void 0!==n?n:"UNKNOWN",modelName:null!==(s=null==e||null===(o=e.ssinfo)||void 0===o?void 0:o.modelName)&&void 0!==s?s:"UNKNOWN",modelNumber:null!==(a=null==e||null===(d=e.ssinfo)||void 0===d?void 0:d.modelNumber)&&void 0!==a?a:"UNKNOWN",manufacturer:null!==(l=null==e||null===(c=e.ssinfo)||void 0===c?void 0:c.manufacturer)&&void 0!==l?l:"UNKNOWN",deviceType:Xr(null==e||null===(u=e.ssinfo)||void 0===u?void 0:u.REMOTE_DEVICE_TYPE)}}}Jr(is,"LOG_TAG","VizbeeBicastMemberPresenceClientImpl");class ns{constructor(){Jr(this,"_messagingClient",null),Jr(this,"_presenceClient",null)}getMessagingClient(){return this._messagingClient||(this._messagingClient=new $r),this._messagingClient}getPresenceClient(){return this._presenceClient||(this._presenceClient=new is),this._presenceClient}}class rs{constructor(){if(Jr(this,"session",null),Jr(this,"sessionState",fn.NOT_CONNECTED),Jr(this,"sessionStateListeners",[]),Jr(this,"syncController",null),Jr(this,"onSessionStateChanged",e=>{var t,i;switch(this.sessionState=e,e){case fn.CONNECTED:null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.info("VizbeeBicastSessionManager","onSessionStateChanged","CONNECTED"),this.session=new ns,this.sessionStateListeners.forEach(e=>e.onSessionStateChanged(fn.CONNECTED));break;case fn.NOT_CONNECTED:null===(i=window.VizbeeSDK)||void 0===i||null===(i=i.logger)||void 0===i||i.info("VizbeeBicastSessionManager","onSessionStateChanged","NOT_CONNECTED"),this.session=null,this.sessionStateListeners.forEach(e=>e.onSessionStateChanged(fn.NOT_CONNECTED))}}),rs.instance)return rs.instance;this.init(),rs.instance=this}init(){var e,t,i,n;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastSessionManager","init","initialize session manager"),this.syncController=null===(t=window.VZB)||void 0===t||null===(i=t.getSyncController)||void 0===i?void 0:i.call(t),this.syncController?this.listenForSyncControllerSessionState():(null===(n=window.VizbeeSDK)||void 0===n||null===(n=n.logger)||void 0===n||n.warn("VizbeeBicastSessionManager","init","syncController is not available"),this.listenForSyncControllerAvailability())}listenForSyncControllerAvailability(){var e,t;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastSessionManager","listenForSyncControllerAvailability","waiting for syncController to be available"),null===(t=window.VZB)||void 0===t||t.addSyncReadyListener(()=>{var e,t,i;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastSessionManager","listenForSyncControllerAvailability","syncController is now available"),this.syncController=null===(t=window.VZB)||void 0===t||null===(i=t.getSyncController)||void 0===i?void 0:i.call(t),this.listenForSyncControllerSessionState()})}listenForSyncControllerSessionState(){var e,t,i,n;this.sessionState=null!==(e=null===(t=this.syncController)||void 0===t||null===(i=t.sessionState)||void 0===i?void 0:i.call(t))&&void 0!==e?e:fn.NOT_CONNECTED,this.sessionState===fn.CONNECTED&&(this.session=new ns),null===(n=this.syncController)||void 0===n||n.addSessionStateListener(this.onSessionStateChanged)}addSessionStateListener(e){var t;null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.debug("VizbeeBicastSessionManager","addSessionStateListener","add session state listener"),"function"==typeof e?this.sessionStateListeners.push({onSessionStateChanged:e}):this.sessionStateListeners.push(e)}removeSessionStateListener(e){var t;null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.debug("VizbeeBicastSessionManager","removeSessionStateListener","remove session state listener");const i=this.sessionStateListeners.indexOf(e);i>-1&&this.sessionStateListeners.splice(i,1)}getSession(){return this.session}isConnecting(){return this.sessionState===fn.CONNECTING}isConnected(){return this.sessionState===fn.CONNECTED}}class ss{constructor(){if(Jr(this,"presenceCallbacks",[]),Jr(this,"vizbeeSession",null),ss.instance)return ss.instance;this.init(),ss.instance=this}init(){try{var e;if(VizbeeSDK.logger.info("VizbeePresenceManager::init - Initializing Vizbee Presence Manager"),null===(e=window.vizbee)||void 0===e||null===(e=e.continuity)||void 0===e||!e.xmessages)throw new Error("Vizbee continuity or xmessages not initialized");const t=new window.vizbee.continuity.xmessages.VizbeeBicastSessionManager;if(!t)throw new Error("Session manager initialization failed");t.addSessionStateListener({onSessionStateChanged:e=>{if(VizbeeSDK.logger.info("VizbeePresenceManager::init - Session state changed:",e),e===fn.CONNECTED){if(VizbeeSDK.logger.debug("VizbeePresenceManager::init - Session connected"),this.vizbeeSession=t.getSession(),!this.vizbeeSession)throw new Error("Failed to retrieve Vizbee session");if(this.vizbeePresenceClient=this.vizbeeSession.getPresenceClient(),!this.vizbeePresenceClient)throw new Error("Failed to retrieve Vizbee presence client");if(this.presenceCallbacks.length>0)for(let e=0;e<this.presenceCallbacks.length;e++){const t=this.presenceCallbacks[e];this.vizbeePresenceClient.subscribe(t)}}else{if(this.vizbeePresenceClient)for(let e=0;e<this.presenceCallbacks.length;e++){const t=this.presenceCallbacks[e];this.vizbeePresenceClient.unsubscribe(t)}this.vizbeeSession=null}}})}catch(e){throw VizbeeSDK.logger.warn("VizbeePresenceManager::init - Error initializing Vizbee session:",e),e}}subscribe(e){"function"==typeof e?(this.presenceCallbacks.push(e),this.vizbeePresenceClient?this.vizbeePresenceClient.subscribe(e):VizbeeSDK.logger.warn("VizbeePresenceManager::subscribe - Presence client not initialized yet")):VizbeeSDK.logger.warn("VizbeePresenceManager::subscribe - Provided callback is not a function")}unsubscribe(e){VizbeeSDK.logger.debug("VizbeePresenceManager::unsubscribe"),this.vizbeePresenceClient&&this.vizbeePresenceClient.unsubscribe(e);const t=this.presenceCallbacks.indexOf(e);t>-1&&this.presenceCallbacks.splice(t,1)}getMembers(){return this.vizbeePresenceClient?this.vizbeePresenceClient.getMembers():[]}}class os extends _r{constructor(){super()}get ContinuityContext(){return Lr}get adapters(){return{AppAdapter:Ir,PlayerAdapter:Ar,HTMLPlayerAdapter:zr,BasePlayerAdapter:Rr,AVPlayerAdapter:Ur,PlayerType:Cr,AdAdapter:Pr,AdType:Dr,VideoStopReason:Br}}get messages(){return{VizbeeEvent:Mr,VideoInfo:kr,VideoStatus:Nr,AdEventType:Tr,AdStatus:Er,PlayerState:wr,SubtitleTrack:Hr}}get analytics(){return{AnalyticsProvider:Fr}}get ui(){return{LayoutPosition:qr,Snackbar:jr,SnackbarUIConfig:Yr}}get analytics(){return{AnalyticsProvider:Fr}}get ui(){return{LayoutPosition:qr,Snackbar:jr,SnackbarUIConfig:Yr}}get xmessages(){return{VizbeeBicastSessionManager:rs,VizbeeBicastSession:ns,VizbeeMessagingClient:void 0,VizbeePresenceManager:ss}}}var as=new class extends os{constructor(){super()}},ds=new class extends fr{constructor(){super()}get continuity(){return as}get framework(){return as}};if(ds.logger=new Ve,ds.logger.setPrefix("[Vizbee]"),"undefined"!=typeof window){if(window.VizbeeSDK=ds,window.vizbee){let e=window.vizbee;window.vizbee=window.VizbeeSDK,Object.keys(e).forEach(t=>{window.vizbee[t]=e[t]})}else window.vizbee=window.VizbeeSDK;"function"==typeof window.dispatchEvent&&window.dispatchEvent(new Event("VIZBEE_SDK_READY"))}export{Tr as AdEventType,Dr as AdType,wr as PlayerState,Cr as PlayerType,Br as VideoStopReason,ds as default};
1
+ if(window.VizbeeSDK||(window.VizbeeSDK={}),!window.VizbeeSDK.logger){var e=function(){};window.VizbeeSDK.logger={debug:e,info:e,warn:e,error:e,d:e,i:e,w:e,e,critical:e,verbose:e}}const t="UNKNOWN",i="onEnd",n="subtitle",r="audio",s="bitmovin",o="videojs",a="theo",d="shaka";class l{constructor(e){if("Platform"===this.constructor.name)throw new TypeError("Platform::constructor() - Abstract class.");this.config=e||{},this.launchParams=void 0,this.isAppExitInProgress=!1}setConfig(e){this.config=e}get cloudPlatformName(){throw new TypeError("Platform::cloudPlatformName() - Abstract method.")}uniqueDeviceID(e,t){this.deviceId.uniqueDeviceID(e,t)}set deviceIDAlgorithm(e){}get deviceIDAlgorithm(){return this.deviceId.algorithm}get deviceIDSource(){return this.deviceId?this.deviceId.source:void 0}get platformModel(){}get deviceInfo(){}get platformVersion(){}get networkInfo(){}get adId(){}get isAdTrackingDisabled(){}createInputDevice(){throw new TypeError("Platform::createInputDevice() - Abstract method.")}enableScreenSaver(e){}get defaultAppletAppId(){throw new TypeError("Platform::defaultAppletAppId() - Abstract method.")}get launchParamsDeferral(){return this.launchParams}get appLifeCycleManager(){}exit(){VizbeeTV.logger.i("BasePlatform","exit"),this.appLifeCycleManager&&this.appLifeCycleManager.emit(i)}set isAppExiting(e){this.isAppExitInProgress=e}get isAppExiting(){return this.isAppExitInProgress}createPlayer(){throw new TypeError("Platform::createPlayer() - Abstract method.")}}class c{constructor(e,t){if("BaseEvent"===this.constructor.name)throw new TypeError("BaseEvent::constructor() - Abstract class.");this.nativeEvent=e,this.source=t}}class u extends c{constructor(e,t){super(e,t)}}class p extends u{constructor(e,t){if(!(t instanceof w))throw new TypeError("TVRemoteEvent::constructor() - source must be an instance of BaseTVRemote.");super(e,t),this.keyCode=t.keyCodeMap[e.keyCode],this.keyName=t.keyNameMap[this.keyCode]}}class h{constructor(){if("BaseEventDispatcher"===this.constructor.name)throw new TypeError("BaseEventDispatcher::constructor() - Abstract class.");this.eventType=void 0,this._eventHandlers=[],this.registerListener()}registerListener(){throw new TypeError("BaseEventDispatcher::registerListener() - Abstract method.")}set onevent(e){if(void 0===e)this._eventHandlers=[];else{if(!(e instanceof Function))throw new TypeError("BaseEventDispatcher::onevent setter - callback must be an instance of Function.");this._eventHandlers.push(e)}}dispatchEvent(e){if(!(e instanceof c))throw new TypeError("BaseEventDispatcher::dispatchEvent() - event must be instance of BaseEvent.");this._eventHandlers.forEach(t=>{t instanceof Function&&t(e)})}reset(){this._eventHandlers=[]}}class g extends h{constructor(){if(super(),"BaseInputDevice"===this.constructor.name)throw new TypeError("BaseInputDevice::constructor() - Abstract class.")}}var f,v,y,m={exports:{}},b=m.exports;function S(){return f||(f=1,e=m,function(t){var i=setTimeout;function n(){}var r="function"==typeof setImmediate&&setImmediate||function(e){i(e,1)},s=function(e){"undefined"!=typeof console&&console},o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function a(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof e)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],h(e,this)}function d(e,t){for(;3===e._state;)e=e._value;0!==e._state?(e._handled=!0,r(function(){var i=1===e._state?t.onFulfilled:t.onRejected;if(null!==i){var n;try{n=i(e._value)}catch(e){return void c(t.promise,e)}l(t.promise,n)}else(1===e._state?l:c)(t.promise,e._value)})):e._deferreds.push(t)}function l(e,t){try{if(t===e)throw new TypeError("A promise cannot be resolved with itself.");if(t&&("object"==typeof t||"function"==typeof t)){var i=t.then;if(t instanceof a)return e._state=3,e._value=t,void u(e);if("function"==typeof i)return void h((n=i,r=t,function(){n.apply(r,arguments)}),e)}e._state=1,e._value=t,u(e)}catch(t){c(e,t)}var n,r}function c(e,t){e._state=2,e._value=t,u(e)}function u(e){2===e._state&&0===e._deferreds.length&&setTimeout(function(){e._handled||s(e._value)},1);for(var t=0,i=e._deferreds.length;t<i;t++)d(e,e._deferreds[t]);e._deferreds=null}function p(e,t,i){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.promise=i}function h(e,t){var i=!1;try{e(function(e){i||(i=!0,l(t,e))},function(e){i||(i=!0,c(t,e))})}catch(e){if(i)return;i=!0,c(t,e)}}a.prototype.catch=function(e){return this.then(null,e)},a.prototype.then=function(e,t){var i=new a(n);return d(this,new p(e,t,i)),i},a.all=function(){var e=Array.prototype.slice.call(1===arguments.length&&o(arguments[0])?arguments[0]:arguments);return new a(function(t,i){if(0===e.length)return t([]);var n=e.length;function r(s,o){try{if(o&&("object"==typeof o||"function"==typeof o)){var a=o.then;if("function"==typeof a)return void a.call(o,function(e){r(s,e)},i)}e[s]=o,0===--n&&t(e)}catch(e){i(e)}}for(var s=0;s<e.length;s++)r(s,e[s])})},a.resolve=function(e){return e&&"object"==typeof e&&e.constructor===a?e:new a(function(t){t(e)})},a.reject=function(e){return new a(function(t,i){i(e)})},a.race=function(e){return new a(function(t,i){for(var n=0,r=e.length;n<r;n++)e[n].then(t,i)})},a._setImmediateFn=function(e){r=e},a._setUnhandledRejectionFn=function(e){s=e},e.exports?e.exports=a:t.Promise||(t.Promise=a)}(b)),m.exports;var e}function _(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function E(){if(y)return v;y=1;var e={get:function(e,t,i){for(var n=Array.isArray(t)?t:[t],r=e,s=0;s<n.length;s++){if(null==r)return i;r=r[n[s]]}return void 0===r?i:r},extend:function(e){if(null==e)return e;for(var t=1;t<arguments.length;t++){var i=arguments[t];if(null!=i)for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},isObject:function(e){return null!==e&&"object"==typeof e},find:function(e,t){if(null!=e){if(Array.isArray(e))return e.find(t);for(var i=Object.keys(e),n=0;n<i.length;n++){var r=e[i[n]];if(t(r,i[n],e))return r}}},keys:function(e){return Object.keys(e)},isString:function(e){return"string"==typeof e},filter:function(e,t){return Array.isArray(e)?e.filter(t):Object.keys(e).reduce(function(i,n){return t(e[n],n,e)&&i.push(e[n]),i},[])},omit:function(e){var t=Array.isArray(arguments[1])?arguments[1]:Array.prototype.slice.call(arguments,1),i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&-1===t.indexOf(n)&&(i[n]=e[n]);return i},isUndefined:function(e){return void 0===e},isNumber:function(e){return"number"==typeof e},isArray:function(e){return Array.isArray(e)},each:function(e,t){return Array.isArray(e)?e.forEach(t):null!=e&&Object.keys(e).forEach(function(i){t(e[i],i,e)}),e},contains:function(e,t){return-1!==e.indexOf(t)},values:function(e){return Object.keys(e).map(function(t){return e[t]})},isFunction:function(e){return"function"==typeof e},isEmpty:function(e){return null==e||(Array.isArray(e)||"string"==typeof e?0===e.length:0===Object.keys(e).length)},clone:function(t){return Array.isArray(t)?t.slice():e.extend({},t)},reject:function(e,t){return Array.isArray(e)?e.filter(function(e){return!t(e)}):Object.keys(e).reduce(function(i,n){return t(e[n],n,e)||i.push(e[n]),i},[])},reduce:function(e,t,i){return Array.isArray(e)?e.reduce(t,i):(Object.keys(e).forEach(function(n){i=t(i,e[n],n,e)}),i)},isBoolean:function(e){return!0===e||!1===e},isNaN:function(e){return"number"==typeof e&&e!=e},isEqual:function(e,t){return JSON.stringify(e)===JSON.stringify(t)},pluck:function(e,t){return e.map(function(e){return e[t]})},findIndex:function(e,t){var i="function"==typeof t?t:function(e){return null!=e&&Object.keys(t).every(function(i){return e[i]===t[i]})};return e.findIndex(i)},findLastIndex:function(e,t){for(var i="function"==typeof t?t:function(e){return null!=e&&Object.keys(t).every(function(i){return e[i]===t[i]})},n=e.length-1;n>=0;n--)if(i(e[n],n,e))return n;return-1},findWhere:function(e,t){return e.find(function(e){return null!=e&&Object.keys(t).every(function(i){return e[i]===t[i]})})},without:function(e){var t=Array.prototype.slice.call(arguments,1);return e.filter(function(e){return-1===t.indexOf(e)})},sortBy:function(e,t){var i="function"==typeof t?t:function(e){return e[t]};return e.slice().sort(function(e,t){var n=i(e),r=i(t);return n<r?-1:n>r?1:0})},rest:function(e,t){return e.slice(void 0===t?1:t)},indexOf:function(e,t){return e.indexOf(t)},intersection:function(){var e=Array.prototype.slice.call(arguments);return e[0].filter(function(t){return e.every(function(e){return-1!==e.indexOf(t)})})}};return v=e}var I=_(E());let T=[],V=[],P=[],A=document.getElementsByTagName("HEAD")[0],D=document.getElementsByTagName("BODY")[0],C=class e{static xchangeHLSUrl(e,t,i,n,r,s){var o="unknown",a="unknown";t&&(o=t),i&&(a=i);var d="https://hlsxchange.claspws.tv/"+o+"/"+a;return e&&e.indexOf(d)>=0?e:(n&&r&&s&&(d+="/"+n+"/"+r+"/"+s),d+="/x.m3u8?hlsurl="+e)}static getRandomIntInclusive(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}static buildErrorEvent(e,t,i){return{code:e,reason:t,data:i}}static loadStyleSheet(e){if(!e||!(e instanceof String||"string"==typeof e))throw new TypeError("Util::loadStyleSheet - Url must be a string.");var t=document.createElement("link");t.setAttribute("rel","stylesheet"),t.setAttribute("type","text/css"),A.appendChild(t),P.push(t),t.setAttribute("href",e)}static loadSynchronousScripts(t){var i=i||void 0;if(i||(i=S()),void 0===e.loadSynchronousScripts.scripts&&(e.loadSynchronousScripts.scripts=[],e.loadSynchronousScripts.index=-1,e.loadSynchronousScripts.loading=!1,e.loadSynchronousScripts.next=function(){if(!e.loadSynchronousScripts.loading){e.loadSynchronousScripts.loading=!0;var t=e.loadSynchronousScripts.scripts[++e.loadSynchronousScripts.index],i=document.getElementsByTagName("head")[0],n=document.createElement("script");n.type="text/javascript",n.src=t.src,n.onload=()=>{e.loadSynchronousScripts.loading=!1,e.loadSynchronousScripts.index<e.loadSynchronousScripts.scripts.length-1&&e.loadSynchronousScripts.next(),t.resolve()},i.appendChild(n)}}),t){for(var n=0;n<e.loadSynchronousScripts.scripts.length;n++)if(e.loadSynchronousScripts.scripts[n].src==t)return e.loadSynchronousScripts.scripts[n].promise;var r={src:t};r.promise=new i(e=>{r.resolve=e}),e.loadSynchronousScripts.scripts.push(r),e.loadSynchronousScripts.next()}return e.loadSynchronousScripts.scripts[e.loadSynchronousScripts.scripts.length-1].promise}static loadScript(e,t,i){if(!e||!(e instanceof String||"string"==typeof e))throw new TypeError("Util::loadScript - Url must be a string.");t=!(!t&&void 0!==t);var n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("async",t),n.onload=i||(()=>{}),A.appendChild(n),T.push(n),n.setAttribute("src",e)}static loadScriptToBody(e,t,i){if(!e||!(e instanceof String||"string"==typeof e))throw new TypeError("Util::loadScript - Url must be a string.");t=!(!t&&void 0!==t);var n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("async",t),n.onload=i||(()=>{}),D.appendChild(n),V.push(n),n.setAttribute("src",e)}static clearLoadedScripts(){for(let e=0;e<T.length;e++)T[e]&&T[e]instanceof Node&&(A.removeChild(T[e]),delete T[e])}static clearBodyLoadedScripts(){for(let e=0;e<V.length;e++)V[e]&&V[e]instanceof Node&&(D.removeChild(V[e]),delete V[e])}static clearLoadedStyleSheets(){for(let e=0;e<P.length;e++)P[e]&&P[e]instanceof Node&&(P[e].disabled=!0,A.removeChild(P[e]),delete P[e])}static clearAllLoadedScriptsAndStyleSheets(){e.clearLoadedScripts(),e.clearLoadedStyleSheets()}static addClass(e,t){if(t){var i=t.className;if(-1!=i.indexOf(e))return;""!=i&&(e=" "+e),t.className=i+e}}static removeClass(e,t){if(t){var i=t.className,n=new RegExp(e,"g");i=i.replace(n,""),t.className=i}}static hasClass(e,t){return(" "+e.className+" ").indexOf(" "+t+" ")>-1}static elementInViewport(e,t,i){var n=e.getBoundingClientRect(),r=n.top,s=n.bottom,o=n.left,a=n.right,d=document.documentElement.clientHeight,l=document.documentElement.clientWidth,c=window.innerHeight,u=window.innerWidth;return i&&(r-=i),t?r>=0&&s<=window.innerHeight:r>=0&&r<=(c||d)&&o>=0&&o<=(u||l)||s>=0&&s<=(c||d)&&a>=0&&a<=(u||l)}static smoothScroll(t,i){var n=t,r=t;do{if(!(n=n.parentNode))return;n.scrollTop+=1}while(0==n.scrollTop);var s=0;do{if(t==n)break;s+=t.offsetTop}while(t=t.offsetParent);e.myscroll(r,i,n,n.scrollTop,s-i,0)}static myscroll(t,i,n,r,s,o){++o>10||t.children.length>0&&e.elementInViewport(t.children.item(0),!0,i)||(n.scrollTop=r+(s-r)/10*o,setTimeout(function(){e.myscroll(t,i,n,r,s,o)},20))}static xhr(e){var t=t||void 0;return t||(t=S()),new t(function(t,i){var n=0===e.retries?0:e.retries||3;!function r(){var s=new XMLHttpRequest;e.disableSSL||(e.url=e.url.replace(/^http:\/\//i,"https://")),s.open(e.method||"GET",e.url,!0),Object.keys(e.headers||{}).forEach(function(t){s.setRequestHeader(t,e.headers[t])});var o=void 0;s.onreadystatechange=function(a){var d,l;if(2==s.readyState&&(d=s.getAllResponseHeaders().trim().split(/[\r\n]+/),l={},d.forEach(function(e){var t=e.split(": "),i=t.shift(),n=t.join(": ");l[i]=n}),o=l),4===s.readyState)if(-1===[200,201,202,203,204,304].indexOf(s.status))n>0?(n--,r()):e.isFullResponse?i(s):i(new Error("Server responded with a status of "+s.status));else try{var c=a.target;e.format=e.format||"json","json"===e.format?(c=c.response?JSON.parse(c.response):{}).headers?Object.assign(c.headers,o):c.headers=o:"xml"===e.format&&(c=c.responseXML),e.isFullResponse?t({xhr:a.target,data:c,headers:o}):t(c)}catch(a){n>0?(n--,r()):e.isFullResponse?i(s):i("JSON parse error with Server response")}},e.timeout&&(s.timeout=e.timeout,s.ontimeout=function(t){n>0?(n--,r()):i(new Error("Server timeout "+e.timeout+"ms"))}),s.send(e.data)}()})}static timeSnapToMs(e){e.split(".").length<=1&&(e+=".000");let t=e.split(":"),i=t.pop().split("."),n=1e3*Number(i[0])+Number(i[1]);return n+=1e3*Number(t.pop())*60,n+=1e3*Number(t.pop())*60*60,n}static millisecondsToString(e,t){var i="",n=Math.floor(e%31536e3%86400%3600%60);i=isNaN(n)||n<=0?":00":n<10?":0"+n:":"+n;var r=Math.floor(e%31536e3%86400%3600/60);i=isNaN(r)||r<=0?"00"+i:r<10?"0"+r+i:r+i;var s=Math.floor(e%31536e3%86400/3600);return t?i=isNaN(s)||s<=0?"00:"+i:s<10?"0"+s+":"+i:s+":"+i:s>0&&(i=s+":"+i),i}static getUrlVars(e=window.location.href){for(var t,i={},n=e.slice(e.indexOf("?")+1).split("&"),r=0;r<n.length;r++)i[(t=n[r].split("="))[0]]=decodeURIComponent(t[1]);return i}static updateUrlQueryParams(e,t){if(!e)return VizbeeUtils.logger.warn("Util::updateUrlQueryParams - INVALID inputUrl, doing nothing"),e;if(I.isEmpty(t))return VizbeeUtils.logger.warn("Util::updateUrlQueryParams - INVALID inputParams, doing nothing"),e;try{let i=new URL(e),n=new URLSearchParams(i.search);Object.keys(t).forEach(e=>n.set(e,t[e])),i.search=n.toString();let r=i.toString();return VizbeeUtils.logger.debug("Util::updateUrlQueryParams - updated url="+r),r}catch(t){return VizbeeUtils.logger.error("Util::updateUrlQueryParams - failed to update query params for url="+e),e}}static get docCookies(){return{getItem:function(e){return e&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null},setItem:function(e,t,i,n,r,s){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e))return!1;var o="";if(i)switch(i.constructor){case Number:o=i===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+i;break;case String:o="; expires="+i;break;case Date:o="; expires="+i.toUTCString()}return document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+o+(r?"; domain="+r:"")+(n?"; path="+n:"")+(s?"; secure":""),!0},removeItem:function(e,t,i){return!!this.hasItem(e)&&(document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"+(i?"; domain="+i:"")+(t?"; path="+t:""),!0)},hasItem:function(e){return!!e&&new RegExp("(?:^|;\\s*)"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:function(){for(var e=document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:\=[^;]*)?;\s*/),t=e.length,i=0;i<t;i++)e[i]=decodeURIComponent(e[i]);return e},eraseCookieFromAllPaths:function(e){var t=location.pathname.split("/"),i=" path=";document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;";for(var n=0;n<t.length;n++)i+=("/"!=i.substr(-1)?"/":"")+t[n],document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;"+i+";"}}}static invert(e){for(var t={},i=Object.keys(e),n=0,r=i.length;n<r;n++)t[e[i[n]]]=i[n];return t}static deepMerge(t,i){var n=Array.isArray(i),r=n&&[]||{};return n?(t=t||[],r=r.concat(t),i.forEach(function(i,n){void 0===r[n]?r[n]=i:"object"==typeof i?r[n]=e.deepMerge(t[n],i):-1===t.indexOf(i)&&r.push(i)})):("object"==typeof t&&null!==t&&Object.keys(t).forEach(function(e){r[e]=t[e]}),Object.keys(i).forEach(function(n){"object"==typeof i[n]&&i[n]&&t[n]?r[n]=e.deepMerge(t[n],i[n]):r[n]=i[n]})),r}static isEqual(e,t){return I.isEqual(e,t)}static flatten(e){var t={};return function e(i,n){if(Object(i)!==i)t[n]=i;else if(Array.isArray(i)){for(var r=0,s=i.length;r<s;r++)e(i[r],n+"["+r+"]");0==s&&(t[n]=[])}else{var o=!0;for(var a in i)o=!1,e(i[a],n?n+"."+a:a);o&&n&&(t[n]={})}}(e,""),t}static unflatten(e){if(Object(e)!==e||Array.isArray(e))return e;var t=/\.?([^.\[\]]+)|\[(\d+)\]/g,i={};for(var n in e){for(var r,s=i,o="";r=t.exec(n);)s=s[o]||(s[o]=r[2]?[]:{}),o=r[2]||r[1];s[o]=e[n]}return i[""]||i}static decodeB64Recurse(t,i){if(!t||!i)return t;for(var n in t){var r=t[n];if("object"==typeof r)e.decodeB64Recurse(r,i);else if(n.indexOf(i)>-1){var s=n.replace(i,"");if(t[s]=t[n],delete t[n],"string"==typeof t[s]){var o=decodeURIComponent(escape(atob(t[s])));t[s]=e.parseFunction(o)}}}return t}static parseFunction(e){var t=e.indexOf("{"),i=e.substring(t+1,e.lastIndexOf("}")),n=e.substring(0,t),r=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).split(",");function s(){return Function.apply(this,r)}return r.push(i),s.prototype=Function.prototype,new s}static padStart(t,i,n){return i|=0,n=String(void 0!==n?n:" "),t.length>i?String(t):((i-=t.length)>n.length&&(n+=e.repeat(n,i/n.length)),n.slice(0,i)+String(t))}static padEnd(t,i,n){return i|=0,n=String(void 0!==n?n:" "),t.length>i?String(t):((i-=t.length)>n.length&&(n+=e.repeat(n,i/n.length)),String(t)+n.slice(0,i))}static repeat(e,t){if(!e)throw new TypeError("can't convert "+e+" to object");var i=""+e;if((t=+t)!=t&&(t=0),t<0)throw new RangeError("repeat count must be non-negative");if(t==1/0)throw new RangeError("repeat count must be less than infinity");if(t=Math.floor(t),0==i.length||0==t)return"";if(i.length*t>=1<<28)throw new RangeError("repeat count must not overflow maximum string size");var n=i.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)i+=i,t--;return i+i.substring(0,n-i.length)}static getShortString(e,t){if(!I.isString(t))return e;if(!I.isString(e))return e;if(-1!=e.indexOf(t)){let i=e.trim().split(t);return I.reduce(i,(e,t)=>e+t.charAt(0),"")}return e}static toCamelCase(e){return void 0===e?e:(e=e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))).charAt(0).toLowerCase()+e.slice(1)}static matchStringWithRegex(e,t){return null!=t&&null!=e&&new RegExp(e,"i").test(t)}static isValidIPv4Address(t){return null!=t&&e.matchStringWithRegex(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,t)}static convertObjectsToString(e){if(!e)return e;if(!Array.isArray(e))return e;for(let t=0;t<e.length;t++){let i=e[t];try{"object"==typeof i&&(i=JSON.stringify(i))}catch(e){}e[t]=i}return e}static getUpdatedStringWithReplacedValues(e,t){return I.isString(e)?!t||Array.isArray(t)||"object"!=typeof t?(VizbeeUtils.logger.d("Util","getUpdatedStringWithReplacedValues","INVALID input json, NOT updating input string"),e):(Object.keys(t).forEach(i=>{e=e.replace(new RegExp(i,"gi"),t[i])}),e):(VizbeeUtils.logger.warn("Util::getUpdatedStringWithReplacedValues - INVALID inputString, NOT updating input string"),e)}static uuidv4(){return crypto&&crypto.getRandomValues?([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)):Math.floor(1e10*Math.random()).toString()}static checkIfImageExists(e){var t=t||void 0;return t||(t=S()),new t(function(t,i){const n=new Image;n.src=e,n.complete?t(!0):(n.onload=()=>{t(!0)},n.onerror=()=>{t(!1)})})}static getFormEncodedUriFormat(e){if(I.isObject(e)){var t=[];for(var i in e){var n=encodeURIComponent(i),r=encodeURIComponent(e[i]);t.push(n+"="+r)}return t.join("&")}}},k=!1;class w extends g{constructor(e){if(super(),VizbeeTV.logger.debug("constructing BaseTVRemote"),this.eventType=p,!(e&&e instanceof l))throw new Error("BaseTVRemote::constructor() -- platform cannot be empty or invalid.");this.platform=e}static get keys(){return{up:1,down:2,left:3,right:4,select:5,play:6,pause:7,stop:8,ffw:9,rw:10,back:11,exit:12,play_pause:13,alt_up:14,alt_down:15,alt_left:16,alt_right:17,skip_next:18,skip_prev:19}}get keyNameMap(){return{1:"up",2:"down",3:"left",4:"right",5:"select",6:"play",7:"pause",8:"stop",9:"fast-forward",10:"rewind",11:"back",12:"exit",13:"play-pause",14:"alt_up",15:"alt_down",16:"alt_left",17:"alt_right",18:"skip_next",19:"skip_prev"}}get keyCodeMap(){throw new TypeError("Abstract method - BaseTVRemote::keyMap getter.")}registerListener(){try{k=!0;let e="keydown";document.addEventListener(e,e=>{this.dispatchEvent(new p(e,this))})}catch(e){VizbeeTV.logger.error("registerListener error - ",e.message,e)}}sendKeyEvent(e){try{var t=C.invert(this.keyCodeMap)[e],i=new Event("keydown");i.keyCode=t,i.charCode=t,document.dispatchEvent(i)}catch(e){VizbeeTV.logger.error("sendKeyEvent error ",e.message,e)}}sendPlay(){this.sendKeyEvent(w.keys.play)}sendPause(){this.sendKeyEvent(w.keys.pause)}sendStop(){this.sendKeyEvent(w.keys.stop)}}class N extends w{get keyCodeMap(){return{38:w.keys.up,40:w.keys.down,37:w.keys.left,39:w.keys.right,13:w.keys.select,415:w.keys.play,19:w.keys.pause,413:w.keys.stop,417:w.keys.ffw,412:w.keys.rw,461:w.keys.back,1e3:w.keys.exit}}}class O{init(){this.player=void 0}setPlayer(e){this.player=e}getPlayer(){return this.player}getTracks(e){return[]}getEnabledTracks(e){return[]}enableTracks(e=[]){}disableTracks(e){}}class R{static getInstance(e,t){}}class M extends O{constructor(){super(),this.init()}init(){this.subtitleInstance=void 0,this.playerType=void 0,this.subtitleType=void 0,this.videoPlayer=void 0}setPlayerWithType(e,t){e?t?(this.playerType=e,this.playerType==s?this.videoPlayer=t.bitmovinPlayer:this.playerType==o?this.videoPlayer=t.playerElement:this.playerType==a?this.videoPlayer=t.playerInstance:this.playerType==d?this.videoPlayer=t.shakaPlayer:this.videoPlayer=t,this._setSubtitleInstance()):VizbeeTV.logger.warn("VirtualSubtitle::setPlayer - invalid parameter 'videoPlayer'"):VizbeeTV.logger.warn("VirtualSubtitle::setPlayer - invalid parameter 'playerType'")}getPlayer(){return this.videoPlayer}setSubtitleType(e){this.subtitleType=e,this._setSubtitleInstance()}_setSubtitleInstance(){this.playerType&&this.videoPlayer&&this.subtitleType&&(this.subtitleInstance=R.getInstance(this.playerType,this.subtitleType),this.subtitleInstance&&(this.subtitleInstance.init(),this.subtitleInstance.setPlayer(this.videoPlayer)))}isReady(){return!!this.subtitleInstance}getTracks(e){return VizbeeTV.logger.verbose("VirtualSubtitle::getTracks - trackType = ",e),this.subtitleInstance?this.subtitleInstance.getTracks(e):(VizbeeTV.logger.verbose("VirtualSubtitle::getTracks - sending empty data as there is no valid subtitle instance"),[])}getEnabledTracks(e){return VizbeeTV.logger.verbose("VirtualSubtitle::getTracks - trackType = ",e),this.subtitleInstance?this.subtitleInstance.getEnabledTracks(e):(VizbeeTV.logger.verbose("VirtualSubtitle::getEnabledTracks - sending empty data as there is no valid subtitle instance"),[])}enableTracks(e=[]){this.subtitleInstance&&this.subtitleInstance.enableTracks(e)}disableTracks(e){this.subtitleInstance&&this.subtitleInstance.disableTracks(e)}}const L={en:"English","en-US":"English (United States)","en-GB":"English (United Kingdom)","en-CA":"English (Canada)","en-AU":"English (Australia)",es:"Spanish","es-ES":"Spanish (Spain)","es-MX":"Spanish (Mexico)",fr:"French","fr-FR":"French (France)","fr-CA":"French (Canada)","fr-BE":"French (Belgium)",de:"German","de-DE":"German (Germany)","de-AT":"German (Austria)","de-CH":"German (Switzerland)",it:"Italian","it-IT":"Italian (Italy)",pt:"Portuguese","pt-PT":"Portuguese (Portugal)","pt-BR":"Portuguese (Brazil)",ru:"Russian","ru-RU":"Russian (Russia)",zh:"Chinese","zh-CN":"Chinese (Simplified)","zh-TW":"Chinese (Traditional)",ja:"Japanese",ko:"Korean",ar:"Arabic","ar-SA":"Arabic (Saudi Arabia)","ar-EG":"Arabic (Egypt)",hi:"Hindi",bn:"Bengali",pa:"Punjabi",mr:"Marathi",te:"Telugu",tr:"Turkish",vi:"Vietnamese",th:"Thai",id:"Indonesian",ms:"Malay",tl:"Tagalog",sw:"Swahili",fi:"Finnish",sv:"Swedish",no:"Norwegian",da:"Danish",pl:"Polish",hu:"Hungarian",cs:"Czech",sk:"Slovak",el:"Greek",ro:"Romanian",bg:"Bulgarian",sr:"Serbian",hr:"Croatian",uk:"Ukrainian",he:"Hebrew",ur:"Urdu",fa:"Persian",gu:"Gujarati",kn:"Kannada",ml:"Malayalam",ta:"Tamil",si:"Sinhalese",cy:"Welsh",sq:"Albanian",mk:"Macedonian",bs:"Bosnian",et:"Estonian",lv:"Latvian",lt:"Lithuanian",ka:"Georgian",am:"Amharic",yo:"Yoruba",ig:"Igbo",zu:"Zulu",xh:"Xhosa",ne:"Nepali",ms:"Malay","hi-IN":"Hindi (India)","bn-IN":"Bengali (India)","pa-IN":"Punjabi (India)"};class x{init(){this.player=void 0,this._reset()}setPlayer(e){this.player=e}getPlayer(){return this.player}getTracks(e){return[]}getEnabledTracks(e){return[]}setActiveTrack(e){}_setTrackIdStringToNumberMap(e){if(!this.trackIdStringToNumberMap[e]){let t=parseInt(e);I.isNaN(t)&&(t=Object.keys(this.trackIdStringToNumberMap).length+1),this.trackIdStringToNumberMap[e]=t,VizbeeTV.logger.verbose("BaseAudio::_setTrackIdStringToNumberMap - updated trackIdStringToNumberMap = ",this.trackIdStringToNumberMap)}}_setTrackLanguageCodeToNameMap(e){!e&&this.trackLanguageCodeToNameMap[e]||(this.trackLanguageCodeToNameMap[e]=L[e]||e,VizbeeTV.logger.verbose("BaseAudio::_setTrackLanguageCodeToNameMap - updated _setTrackLanguageCodeToNameMap = ",this.trackLanguageCodeToNameMap))}_reset(){this.trackIdStringToNumberMap={},this.trackLanguageCodeToNameMap={}}}class z{static getInstance(e){}}class K extends x{constructor(){super(),this.init()}init(){this.audioInstance=void 0,this.playerType=void 0,this.videoPlayer=void 0}setPlayerWithType(e,t){VizbeeTV.logger.debug("VirtualAudio::setPlayerWithType - playerType = ",e,", playerInstance = ",t),e?t?(this.playerType=e,this.playerType==s?this.videoPlayer=t.bitmovinPlayer:this.playerType==o?this.videoPlayer=t.playerElement:this.playerType==d?this.videoPlayer=t.shakaPlayer:this.videoPlayer=t,this._setAudioInstance()):VizbeeTV.logger.warn("VirtualAudio::setPlayerWithType - invalid parameter 'videoPlayer'"):VizbeeTV.logger.warn("VirtualAudio::setPlayerWithType - invalid parameter 'playerType'")}getPlayer(){return this.videoPlayer}_setAudioInstance(){this.playerType&&this.videoPlayer&&(VizbeeTV.logger.debug("VirtualAudio::_setAudioInstance - playerType = ",this.playerType),VizbeeTV.logger.debug("VirtualAudio::_setAudioInstance - videoPlayer = ",this.videoPlayer),this.audioInstance=z.getInstance(this.playerType),this.audioInstance&&(VizbeeTV.logger.debug("VirtualAudio::_setAudioInstance - setting audio instance"),this.audioInstance.init(),this.audioInstance.setPlayer(this.videoPlayer)))}isReady(){return!!this.audioInstance}getTracks(e){return VizbeeTV.logger.verbose("VirtualAudio::getTracks - trackType = ",e),this.audioInstance?this.audioInstance.getTracks(e):(VizbeeTV.logger.verbose("VirtualAudio::getTracks - sending empty data as there is no valid audio instance"),[])}getEnabledTracks(e){return VizbeeTV.logger.verbose("VirtualAudio::getEnabledTracks - trackType = ",e),this.audioInstance?this.audioInstance.getEnabledTracks(e):(VizbeeTV.logger.verbose("VirtualAudio::getEnabledTracks - sending empty data as there is no valid audio instance"),[])}setActiveTrack(e){this.audioInstance&&this.audioInstance.setActiveTrack(e)}}class U{constructor(){this.adPodStartedTimeInMs=0,this.adPodEndedTimeInMs=0,this.loadReceivedByAppTimeInMs=0,this.loadReceivedByPlayerTimeInMs=0,this.metadataLoadedTimeInMs=0,this.playerReadyToPlayTimeInMs=0,this.playbackStartedTimeInMs=0}toJSON(){return{adPodStartedTimeInMs:this._adPodStartedTimeInMs,adPodEndedTimeInMs:this._adPodEndedTimeInMs,loadReceivedByAppTimeInMs:this._loadReceivedByAppTimeInMs,loadReceivedByPlayerTimeInMs:this._loadReceivedByPlayerTimeInMs,metadataLoadedTimeInMs:this._metadataLoadedTimeInMs,playerReadyToPlayTimeInMs:this._playerReadyToPlayTimeInMs,playbackStartedTimeInMs:this._playbackStartedTimeInMs}}fromJSON(e){e&&(e.adPodStartedTimeInMs&&(this.adPodStartedTimeInMs=e.adPodStartedTimeInMs),e.adPodEndedTimeInMs&&(this.adPodEndedTimeInMs=e.adPodEndedTimeInMs),e.loadReceivedByAppTimeInMs&&(this.loadReceivedByAppTimeInMs=e.loadReceivedByAppTimeInMs),e.loadReceivedByPlayerTimeInMs&&(this.loadReceivedByPlayerTimeInMs=e.loadReceivedByPlayerTimeInMs),e.metadataLoadedTimeInMs&&(this.metadataLoadedTimeInMs=e.metadataLoadedTimeInMs),e.playerReadyToPlayTimeInMs&&(this.playerReadyToPlayTimeInMs=e.playerReadyToPlayTimeInMs),e.playbackStartedTimeInMs&&(this.playbackStartedTimeInMs=e.playbackStartedTimeInMs))}reset(){this.adPodStartedTimeInMs=0,this.adPodEndedTimeInMs=0,this.loadReceivedByAppTimeInMs=0,this.loadReceivedByPlayerTimeInMs=0,this.metadataLoadedTimeInMs=0,this.playerReadyToPlayTimeInMs=0,this.playbackStartedTimeInMs=0}set adPodStartedTimeInMs(e){this._adPodStartedTimeInMs=e}get adPodStartedTimeInMs(){return this._adPodStartedTimeInMs}set adPodEndedTimeInMs(e){this._adPodEndedTimeInMs=e}get adPodEndedTimeInMs(){return this._adPodEndedTimeInMs}set loadReceivedByAppTimeInMs(e){this._loadReceivedByAppTimeInMs=e}get loadReceivedByAppTimeInMs(){return this._loadReceivedByAppTimeInMs}set loadReceivedByPlayerTimeInMs(e){this._loadReceivedByPlayerTimeInMs=e}get loadReceivedByPlayerTimeInMs(){return this._loadReceivedByPlayerTimeInMs}set metadataLoadedTimeInMs(e){this._metadataLoadedTimeInMs=e}get metadataLoadedTimeInMs(){return this._metadataLoadedTimeInMs}set playerReadyToPlayTimeInMs(e){this._playerReadyToPlayTimeInMs=e}get playerReadyToPlayTimeInMs(){return this._playerReadyToPlayTimeInMs}set playbackStartedTimeInMs(e){this._playbackStartedTimeInMs=e}get playbackStartedTimeInMs(){return this._playbackStartedTimeInMs}}function F(e){try{return decodeURIComponent(e)}catch(t){return e}}class B{constructor(e){if(VizbeeTV.logger.debug("BasePlayer::constructor() platform =",e),"BasePlayer"===this.constructor.name)throw new TypeError("BasePlayer::constructor() -- Abstract class.");if(!(e&&e instanceof l))throw new Error("BasePlayer::constructor() -- platform cannot be empty or invalid.");this.playerState={IDLE:"idle",PREPARING:"preparing",LOADING:"loading",STARTED:"started",PLAYING:"playing",PAUSED:"paused",BUFFERING:"buffering",INTERRUPTED:"interrupted",ENDED:"ended",ERROR:"error"},this.currentState=this.playerState.IDLE,this.platform=e,this.platformConfig=e.config,this.videoInfo={},this.hlsxchange=!0,this.currentSrc="",this.startVideoTimestampInMS=0,this.onStartedTimestampInMS=0,this.resetListeners(),this.subtitlesDelegate=new M,this.audioDelegate=new K,this.streamQualityInfo=new U}reconstruct(e){}set enableHLSExchange(e){this.hlsxchange=e}set onLoading(e){"function"==typeof e&&this._loadingListeners.push(e)}dispatchOnLoading(){this.currentState=this.playerState.LOADING;for(var e=this._loadingListeners.length-1;e>-1;e--)if(this._loadingListeners[e]())return}set onStarted(e){"function"==typeof e&&this._startedListeners.push(e)}dispatchOnStarted(){this.onStartedTimestampInMS=(new Date).getTime(),this.currentState=this.playerState.STARTED;for(var e=this._startedListeners.length-1;e>-1;e--)if(this._startedListeners[e]())return}set onPlaying(e){"function"==typeof e&&this._playingListeners.push(e)}dispatchOnPlaying(){this.currentState=this.playerState.PLAYING;for(var e=this._playingListeners.length-1;e>-1;e--)if(this._playingListeners[e]())return}set onPaused(e){"function"==typeof e&&this._pausedListeners.push(e)}dispatchOnPaused(){this.currentState=this.playerState.PAUSED;for(var e=this._pausedListeners.length-1;e>-1;e--)if(this._pausedListeners[e]())return}set onTimeUpdate(e){"function"==typeof e&&this._timeupdateListeners.push(e)}dispatchOnTimeUpdate(e){this.currentState=this.playerState.PLAYING;for(var t=this._timeupdateListeners.length-1;t>-1;t--)if(this._timeupdateListeners[t](e))return}set onBuffering(e){"function"==typeof e&&this._bufferingListeners.push(e)}dispatchOnBuffering(e){this.currentState=this.playerState.BUFFERING;for(var t=this._bufferingListeners.length-1;t>-1;t--)if(this._bufferingListeners[t](e))return}set onBufferingComplete(e){"function"==typeof e&&this._bufferingCompleteListeners.push(e)}dispatchOnBufferingComplete(e){for(var t=this._bufferingCompleteListeners.length-1;t>-1;t--)if(this._bufferingCompleteListeners[t](e))return}set onEnded(e){"function"==typeof e&&this._endedListeners.push(e)}dispatchOnEnded(){VizbeeTV.logger.info(this.constructor.name+"::dispatchOnEnded ["+this.currentState+"] sending ended"),this.currentState=this.playerState.ENDED;for(var e=this._endedListeners.length-1;e>-1;e--)if(this._endedListeners[e]())return;this.currentState=this.playerState.IDLE}set onInterrupted(e){"function"==typeof e&&this._interruptedListeners.push(e)}dispatchOnInterrupted(e){if(!this._canBeInterrupted())return VizbeeTV.logger.warn(this.constructor.name+"::dispatchOnInterrupted ["+this.currentState+"] tried to send interrupted in wrong state ",e),!1;VizbeeTV.logger.info(this.constructor.name+"::dispatchOnInterrupted ["+this.currentState+"] sending interrupted ",e),this.currentState=this.playerState.INTERRUPTED;for(var t=this._interruptedListeners.length-1;t>-1;t--)if(this._interruptedListeners[t](e))return;return this.currentState=this.playerState.IDLE,!0}_canBeInterrupted(){return this.currentState==this.playerState.STARTED||this.currentState==this.playerState.PLAYING||this.currentState==this.playerState.PAUSED||this.currentState==this.playerState.BUFFERING}set onError(e){"function"==typeof e&&this._errorListeners.push(e)}dispatchOnError(e){if(!this._canBeErrored())return VizbeeTV.logger.warn(this.constructor.name+"::dispatchOnError ["+this.currentState+"] tried to send error in wrong state ",e),!1;VizbeeTV.logger.info(this.constructor.name+"::dispatchOnError ["+this.currentState+"] sending error ",e),this.currentState=this.playerState.ERROR;for(var t=this._errorListeners.length-1;t>-1;t--)if(this._errorListeners[t](e))return;return this.currentState=this.playerState.IDLE,!0}_canBeErrored(){return this.currentState!=this.playerState.IDLE}set onEvent(e){"function"==typeof e&&this._eventListeners.push(e)}dispatchOnEvent(e){for(var t=this._eventListeners.length-1;t>-1;t--)if(this._eventListeners[t](e))return}resetListeners(){this._startedListeners=[],this._loadingListeners=[],this._playingListeners=[],this._pausedListeners=[],this._timeupdateListeners=[],this._bufferingListeners=[],this._bufferingCompleteListeners=[],this._endedListeners=[],this._interruptedListeners=[],this._errorListeners=[],this._eventListeners=[]}start(e){VizbeeTV.logger.debug(this.constructor.name+"::Start() BEGINNING - CURRENT_PLAYER_STATE -- ",this.currentState),this.videoInfo=e,this.currentState=this.playerState.PREPARING,this.startVideoTimestampInMS=(new Date).getTime(),this.subtitlesDelegate.init();let t=this.getPlayerType();this.subtitlesDelegate.setPlayerWithType(t,this);let i=this.getSubtitleTypeFromVideoInfo(e);this.subtitlesDelegate.setSubtitleType(i),this.audioDelegate.init(),this.audioDelegate.setPlayerWithType(t,this),VizbeeTV.logger.debug(this.constructor.name+"::Start() ENDING - CURRENT_PLAYER_STATE -- ",this.currentState)}play(){throw new TypeError(this.constructor.name+"::play() - Abstract method.")}pause(){throw new TypeError(this.constructor.name+"::pause() - Abstract method.")}togglePlayPause(){throw new TypeError(this.constructor.name+"::togglePlayPause() - Abstract method.")}seek(e){throw new TypeError(this.constructor.name+"::seek() - Abstract method.")}stop(e){throw new TypeError(this.constructor.name+"::stop() - Abstract method.")}currentTime(){throw new TypeError(this.constructor.name+"::currentTime() - Abstract method.")}getDuration(){throw new TypeError(this.constructor.name+"::getDuration() - Abstract method.")}getStartTime(){return this.startVideoTimestampInMS>0&&this.onStartedTimestampInMS>this.startVideoTimestampInMS?this.onStartedTimestampInMS-this.startVideoTimestampInMS:0}getBufferLevel(){return{current:0,target:0}}getAudioBufferLevel(){return{current:0,target:0,didDetectSeparateAudio:!1}}getCurrentState(){return this.currentState}getName(){return this.constructor.name}getPlayerType(){let e,t=this.getName().toLowerCase();return-1!=t.indexOf("bitmovin")?e=s:-1!=t.indexOf("videojs")?e=o:-1!=t.indexOf("theo")?e=a:-1!=t.indexOf("shaka")?e=d:-1!=t.indexOf("avplayer")&&(e="avplayer"),e}getCurrentVersion(){return""}getHlsxchangeUrl(){return this.hlsxchange&&(this.videoInfo.src.lastIndexOf(".m3u8")>=0||this.videoInfo.src.lastIndexOf("m3u")>=0)?C.xchangeHLSUrl(this.videoInfo.src,this.videoInfo.appID,this.platform.cloudPlatformName,this.videoInfo.minBitrate,this.videoInfo.maxBitrate,1):this.videoInfo.src}getAppVideoStartErrorInfo(e,t){let i=function(e){if(!function(e){return"string"==typeof e&&-1!=e.indexOf("start_video_failure")}(e))return null;const t=function(e){const t={},i=e.indexOf("?");if(-1==i)return t;const n=e.slice(i+1).split("#")[0].split("&");for(let e=0;e<n.length;e++){const i=n[e].indexOf("=");i>0&&(t[n[e].slice(0,i)]=F(n[e].slice(i+1)))}return t}(e),i={errorCode:t.errorCode,errorReason:t.errorReason},n=t.backendErrorSource;return n&&(i.backendError={source:n,code:t.backendErrorCode,name:t.backendErrorName,httpStatus:t.backendHttpStatus,sessionId:t.backendSessionId}),i}(this.videoInfo&&this.videoInfo.videourl);return i&&i.errorCode&&i.errorReason?{errorCode:i.errorCode,errorReason:i.errorReason}:{errorCode:e,errorReason:t}}buildErrorEvent(e,t,i){return{player:this.constructor.name,code:e,reason:t,data:i}}doAction(e){}reset(){this.resetListeners()}destroy(){this.resetListeners()}getTracks(e){return e==n?this.subtitlesDelegate&&this.subtitlesDelegate.isReady()?this.subtitlesDelegate.getTracks(e):[]:e==r&&this.audioDelegate&&this.audioDelegate.isReady()?this.audioDelegate.getTracks(e):[]}getEnabledTracks(e){return e==n?this.subtitlesDelegate&&this.subtitlesDelegate.isReady()?this.subtitlesDelegate.getEnabledTracks(e):[]:e==r&&this.audioDelegate&&this.audioDelegate.isReady()?this.audioDelegate.getEnabledTracks(e):[]}getSubtitleTypeFromVideoInfo(e){return"any"}enableTracks(e){this.subtitlesDelegate.isReady()&&this.subtitlesDelegate.enableTracks(e)}disableTracks(e){this.subtitlesDelegate.isReady()&&this.subtitlesDelegate.disableTracks(e)}changeAudioTrack(e){this.audioDelegate.isReady()?this.audioDelegate.setActiveTrack(e):VizbeeTV.logger.warn(this.constructor.name+"::changeAudioTrack - audio delegate is not ready")}getStreamQualityInfo(){return this.streamQualityInfo&&this.streamQualityInfo.toJSON()}setStreamQualityInfo(e){this.streamQualityInfo&&this.streamQualityInfo.fromJSON(e)}resetStreamQualityInfo(){this.streamQualityInfo&&this.streamQualityInfo.reset()}setTracks(e){}getCurrentTrack(){var e;return this.videoInfo.tracks&&this.videoInfo.tracks.length>0&&isFinite(this.videoInfo.activeTrackId)&&(e=this.videoInfo.tracks.find(e=>this.videoInfo.activeTrackId==e.trackId)),e}}class G extends B{constructor(e){super(e),this._positionMs=-1,this._durationMs=-1}setPositionMs(e){this._positionMs="number"==typeof e&&e>=0?e:-1}setDurationMs(e){this._durationMs="number"==typeof e&&e>=0?e:-1}currentTime(){return this._positionMs>=0?this._positionMs/1e3:0}getDuration(){return this._durationMs>=0?this._durationMs/1e3:0}getStartTime(){return 0}dispatchOnTimeUpdate(e){for(var t=this._timeupdateListeners.length-1;t>-1;t--)if(this._timeupdateListeners[t](e))return}_canBeInterrupted(){return!0}_canBeErrored(){return!0}start(e){this.videoInfo=e||{},this.currentState=this.playerState.PREPARING}play(){}pause(){}togglePlayPause(){}seek(){}stop(){}setTracks(){}getTracks(){return[]}getEnabledTracks(){return[]}enableTracks(){}disableTracks(){}changeAudioTrack(){}wrapAVPlayerListener(e){return e}getName(){return this.platformConfig&&this.platformConfig.playerType||"VirtualPlayer"}getCurrentVersion(){return""}destroy(){super.destroy(),this._positionMs=-1,this._durationMs=-1}}var H=null,W=null,j=null,q=null,Y=null;class J extends B{extend(){throw new TypeError("BasePlayerExtensible::extend() - Abstract method.")}beforeStart(){throw new TypeError("BasePlayerExtensible::beforeStart() - Abstract method.")}}class Q extends J{constructor(e,t){if(super(e),!t)throw ReferenceError("LGDynamicPlayerSelector::constructor | platformPlayers is not passed.");this.nativePlayerClass=t.nativePlayer,this.htmlPlayerClass=t.htmlPlayer,this.currentPlayer=void 0,this.nativePlayer=void 0,this.htmlPlayer=void 0;let i=e.config.vtvPlayerListConfig||[{type:"native"}];i.forEach(e=>{this._createPlayer(e)}),this._selectPlayer(i[0])}reconstruct(e){this.platform.config=e,e.standalone&&this._destroyAllPlayers();let t=!e.vtvPlayerListConfig||Array.isArray(e.vtvPlayerListConfig)&&0===e.vtvPlayerListConfig.length?[{type:"native"}]:e.vtvPlayerListConfig;t.forEach(e=>{this._createPlayer(e)}),this._selectPlayer(t[0])}_destroyAllPlayers(){this.nativePlayer&&(this.nativePlayer.destroy(),this.nativePlayer=void 0),this.htmlPlayer&&(this.htmlPlayer.destroy(),this.htmlPlayer=void 0),this.currentPlayer=void 0}_createPlayer(e){"html"===(e&&e.type)?void 0===this.htmlPlayer&&(this.htmlPlayer=new this.htmlPlayerClass(this.platform)):void 0===this.nativePlayer&&(this.nativePlayer=new this.nativePlayerClass(this.platform))}_selectPlayer(e){e&&e.type?"html"===e.type?this._preparePlayer(this.htmlPlayer):this._preparePlayer(this.nativePlayer):void 0===this.currentPlayer&&this._preparePlayer(this.nativePlayer)}_preparePlayer(e){e&&(this.currentPlayer&&this.currentPlayer.constructor.name===e.constructor.name||(this.currentPlayer&&this.currentPlayer.constructor.name!==e.constructor.name&&this._removePlayerListeners(this.currentPlayer),this.currentPlayer=e,this._addPlayerListeners(this.currentPlayer)))}beforeStart(e){super.start(e)}start(e){this.beforeStart(e),e.vtvPlayerConfig&&(this._createPlayer(e.vtvPlayerConfig),this._selectPlayer(e.vtvPlayerConfig)),this.currentPlayer.enableHLSExchange=e.useHLSExchange,this.currentPlayer.start(e)}play(){this.currentPlayer&&this.currentPlayer.play()}pause(){this.currentPlayer&&this.currentPlayer.pause()}togglePlayPause(){this.currentPlayer&&this.currentPlayer.togglePlayPause()}stop(e){this.currentPlayer&&this.currentPlayer.stop(e)}seek(e){this.currentPlayer&&this.currentPlayer.seek(e)}currentTime(){return this.currentPlayer?this.currentPlayer.currentTime():-1}getDuration(){return this.currentPlayer?this.currentPlayer.getDuration():-1}getStartTime(){return this.currentPlayer?this.currentPlayer.getStartTime():-1}getCurrentState(){return this.currentPlayer?this.currentPlayer.getCurrentState():"IDLE"}getBufferLevel(){return this.currentPlayer?this.currentPlayer.getBufferLevel():{current:0,target:0}}getAudioBufferLevel(){return this.currentPlayer?this.currentPlayer.getAudioBufferLevel():{current:0,target:0,didDetectSeparateAudio:!1}}getName(){return this.currentPlayer.getName()}getCurrentVersion(){return this.currentPlayer.getCurrentVersion()}doAction(e){return this.currentPlayer.doAction(e)}wrapAVPlayerListener(e){return this.currentPlayer.wrapAVPlayerListener(e)}setTracks(e){if(this.currentPlayer)return this.currentPlayer.setTracks(e)}getTracks(e){return this.currentPlayer?this.currentPlayer.getTracks(e):[]}getEnabledTracks(e){return this.currentPlayer?this.currentPlayer.getEnabledTracks(e):[]}enableTracks(e){this.currentPlayer&&this.currentPlayer.enableTracks(e)}disableTracks(e){this.currentPlayer&&this.currentPlayer.disableTracks(e)}changeAudioTrack(e){this.currentPlayer&&this.currentPlayer.changeAudioTrack(e)}getStreamQualityInfo(){return this.currentPlayer?this.currentPlayer.getStreamQualityInfo():{}}setStreamQualityInfo(e){this.currentPlayer&&this.currentPlayer.setStreamQualityInfo(e)}resetStreamQualityInfo(){this.currentPlayer&&this.currentPlayer.resetStreamQualityInfo()}destroy(){super.destroy(),this._destroyAllPlayers()}_addPlayerListeners(e){e.onLoading=e=>{this.dispatchOnLoading.call(this,e)},e.onStarted=e=>{this.dispatchOnStarted.call(this,e)},e.onPlaying=e=>{this.dispatchOnPlaying.call(this,e)},e.onPaused=e=>{this.dispatchOnPaused.call(this,e)},e.onBuffering=e=>{this.dispatchOnBuffering.call(this,e)},e.onBufferingComplete=e=>{this.dispatchOnBufferingComplete.call(this,e)},e.onTimeUpdate=e=>{this.dispatchOnTimeUpdate.call(this,e)},e.onInterrupted=e=>{this.dispatchOnInterrupted.call(this,e)},e.onEnded=e=>{this.dispatchOnEnded.call(this,e)},e.onError=e=>{this.dispatchOnError.call(this,e)},e.onEvent=e=>{this.dispatchOnEvent.call(this,e)}}_removePlayerListeners(e){e.resetListeners()}}class ${constructor(){if("BaseDeviceID"===this.constructor.name)throw new TypeError("BaseDeviceID::constructor() - Abstract class.");this.deviceIdAlgorithm="VTV_DEFAULT",this.deviceIdKey="deviceid",this.deviceIdSource=void 0}uniqueDeviceID(e,t){VizbeeTV.logger.error("BaseDeviceID::uniqueDeviceID - subclass did not override; no deviceId available"),t()}get algorithm(){return this.deviceIdAlgorithm}get source(){return this.deviceIdSource}}class Z extends ${constructor(){super(),this.deviceIdAlgorithm="VTV_URL_PARAMS",this.storageDeviceIdKey="VTV_"+this.deviceIdKey}uniqueDeviceID(e,t){var i=(C.getUrlVars()||{})[this.deviceIdKey];if(i)C.docCookies.setItem(this.storageDeviceIdKey,i,1/0,"/");else{var n=C.docCookies.getItem(this.storageDeviceIdKey);if(!n)return VizbeeTV.logger.error("URLParamsDeviceID::uniqueDeviceID - didn't find deviceID in URL or storage"),void t();i=n}e(i)}}class X{constructor(){}isLaunchedbyVizbee(){throw new TypeError("BaseLaunchParams::isLaunchedbyVizbee() - Abstract method. This method must be implemented by derived classes.")}getLaunchParams(e){}setLaunchParams(e){}waitUntilReady(){return this._readyPromise||Promise.resolve()}}class ee extends X{constructor(){super()}isLaunchedbyVizbee(){let e=this.getLaunchParams();return e?(VizbeeTV.logger.debug("URLLaunchParams::isLaunchedbyVizbee() - params present",e),"y"==e.vzb):(VizbeeTV.logger.debug("URLLaunchParams::isLaunchedbyVizbee() - params not present"),!1)}getLaunchParams(){let e,t={};if(e=window.location.href,!this.isValidUrl(e))return;let i=!1,n=e.indexOf("?");if(n>=0){let r=e.slice(n+1).split("&");for(let e=0;e<r.length;e++){let n,s;n=r[e].split("="),2==n.length&&n[0].length&&n[1].length&&(i=!0,s=n[0],t[s]=n[1])}}return i?t:void 0}isValidUrl(e){return/(http|https):\/\//.test(e)}}class te{constructor(){var e,t,i,n,r;this._uaParser=(e=navigator.userAgent,i={name:"",version:""},n={name:"",version:""},r={name:"",version:""},(t=/Web0S(?:\.TV)?(?:[;\s/]*([\d.]+))?/i.exec(e))?(i.name="webOS",i.version=t[1]||""):(t=/Windows\s*(?:NT\s*)?([\d.]+)?/i.exec(e))?(i.name="Windows",i.version=t[1]||""):(t=/Mac OS X\s*([\d_.]+)?/i.exec(e))?(i.name="Mac OS",i.version=(t[1]||"").replace(/_/g,".")):(t=/CrOS[\s/]*([\w.]+)?/i.exec(e))?(i.name="Chromium OS",i.version=t[1]||""):(t=/Android\s*([\d.]+)?/i.exec(e))?(i.name="Android",i.version=t[1]||""):(t=/(?:iPhone|iPad).*OS\s*([\d_]+)/i.exec(e))?(i.name="iOS",i.version=(t[1]||"").replace(/_/g,".")):(t=/Linux/i.exec(e))&&(i.name="Linux"),(t=/(?:Edg|EdgA|EdgIOS)\/([\d.]+)/i.exec(e))?(n.name="Edge",n.version=t[1]):(t=/OPR\/([\d.]+)/i.exec(e))?(n.name="Opera",n.version=t[1]):(t=/Firefox\/([\d.]+)/i.exec(e))?(n.name="Firefox",n.version=t[1]):(t=/Chrome\/([\d.]+)/i.exec(e))?(n.name="Chrome",n.version=t[1]):(t=/Safari\/([\d.]+)/i.exec(e))&&/Version\/([\d.]+)/.test(e)&&(n.name="Safari",n.version=/Version\/([\d.]+)/.exec(e)[1]),(t=/AppleWebKit\/([\d.]+)/i.exec(e))?(r.name="WebKit",r.version=t[1]):(t=/Gecko\/([\d.]+)/i.exec(e))?(r.name="Gecko",r.version=t[1]):(t=/Trident\/([\d.]+)/i.exec(e))&&(r.name="Trident",r.version=t[1]),{os:i,browser:n,engine:r})}get deviceId(){return t}get make(){return t}get model(){return t}get modelYear(){return t}get serialNumber(){return t}get friendlyName(){return t}get macAddress(){return t}get userAgent(){return navigator.userAgent}get os(){return{name:this._uaParser.os.name,sdkVersion:this._uaParser.os.version,version:this._uaParser.os.version}}get browser(){return{name:this._uaParser.browser.name,version:this._uaParser.browser.version,engine_name:this._uaParser.engine.name,engine_version:this._uaParser.engine.version}}get screen(){return{height:document.body.clientHeight,width:document.body.clientWidth}}}const ie={6:"webOS TV 6.0",7:"webOS TV 22",8:"webOS TV 23",9:"webOS TV 24"};class ne extends te{constructor(){super(),this._deviceInfo={};try{setTimeout(()=>{window.webOS&&webOS.deviceInfo(e=>{e&&(setTimeout(()=>{},1e4),this._deviceInfo=I.extend({},this._deviceInfo,e))})},1e4)}catch(e){setTimeout(()=>{VizbeeTV.logger.warn("LGWebOSDeviceInfo::constructor - failed to fetch deviceId and modelName",e)},1e4)}}get deviceId(){return this._deviceInfo.id||t}get model(){return this._deviceInfo.modelName||t}get make(){return this._deviceInfo.manufacturer||t}get modelYear(){return t}get friendlyName(){return t}get macAddress(){return t}get os(){return{name:"WebOS",sdkVersion:this._deviceInfo.sdkVersion||t,version:ie[(this._deviceInfo.sdkVersion||t).split(".")[0]]||t}}}class re{constructor(){}get internalIP(){return t}get externalIP(){return t}get isWifiConnected(){return!0}get connectionType(){return t}get bssid(){return t}get ssid(){return t}}class se extends re{constructor(){super()}}class oe{constructor(){this.eventMap={}}addHandler(e,t){this.eventMap[e]||(this.eventMap[e]=[]),this.eventMap[e].push(t)}removeHandler(e,t){if(this.eventMap&&this.eventMap[e]){let i,n=this.eventMap[e];if(n&&n.length&&(i=n.reduce((e,i,n)=>this._isFunction(i)&&i==t?e=n:e,-1),i>-1))return n.splice(i,1),this.eventMap[e]=n,!0}return!1}emit(e,t){e&&(VizbeeTV.logger.i("BaseAppLifeCycleManager","emit","eventName=",e,"; eventData=",t),this.eventMap&&this.eventMap[e]&&this.eventMap[e].forEach(i=>{VizbeeTV.logger.i("BaseAppLifeCycleManager","emit","calling handler for event=",e),i.apply({},t)}))}reset(){this.eventMap={}}_isFunction(e){return"function"==typeof e||!1}}class ae extends oe{constructor(){super(),this._didBackgroundOnce=!1,this._didEnd=!1}init(){document&&this._listen()}_listen(){let e;void 0!==document.hidden?e="visibilitychange":void 0!==document.webkitHidden&&(e="webkitvisibilitychange"),document.addEventListener(e,()=>{try{document.hidden?(VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_listen - application is in background"),this._emitOnBackground()):(VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_listen - application is in foreground"),this._emitOnForeground())}catch(e){VizbeeTV.logger.error("LGWebOSAppLifeCycleManager::_listen - error reading lifecycle events",e)}}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("pagehide",e=>{e&&e.persisted||this._emitOnEnd()}),window.addEventListener("beforeunload",()=>{this._emitOnEnd()}))}_emitOnEnd(){this._didEnd||(this._didEnd=!0,VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnEnd - application is exiting"),this.emit(i,[{isTeardown:!0}]))}_emitOnBackground(){this._didBackgroundOnce=!0,this.eventMap.onBackground.forEach(e=>{VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnBackground"),e.apply({})})}_emitOnForeground(){this._didBackgroundOnce&&this.eventMap.onForeground.forEach(e=>{VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnForeground"),e.apply({})})}}class de extends l{constructor(e){super(e),this.deviceId=new Z,this.launchParams=new ee,this._deviceInfo=new ne,this._networkInfo=new se,this.lgWebOSAppLifeCycleManager=new ae,this.lgWebOSAppLifeCycleManager.init()}createPlayer(){let e={};return navigator.userAgent.indexOf("webOS.TV-2014")>-1?(VizbeeTV.logger.d("LGWebOS","createPlayer","WebOS 2014 detected - using webOS player"),e.nativePlayer=G,e.htmlPlayer=G):(VizbeeTV.logger.d("LGWebOS","createPlayer","WebOS 2014 detected - using html player"),e={nativePlayer:G,htmlPlayer:G,bitmovinPlayer:W,modularBitmovinPlayer:W,videoJSPlayer:j,theoPlayer:q,shakaPlayer:Y,topPlayer:H}),this.player=new Q(this,e),this.player}createInputDevice(){let e=new N(this);return this.inputDevice=e,e}exit(){VizbeeTV.tv.player.stop(),super.exit(),"function"==typeof window.NetCastBack?window.NetCastBack():"function"==typeof window.NetCastExit?window.NetCastExit():window.close()}get defaultAppletAppId(){return"vzb0000001"}get cloudPlatformName(){return"lg_webos"}get launchParamsDeferral(){return this.launchParams}get deviceInfo(){return this._deviceInfo}get networkInfo(){return this._networkInfo}get appLifeCycleManager(){return this.lgWebOSAppLifeCycleManager}}class le extends ${constructor(){super(),this.deviceIdAlgorithm="VTV_INTERNAL_IP"}}class ce extends le{constructor(){super()}uniqueDeviceID(e,t){let i,n;const r=()=>{if(void 0!==n&&(clearTimeout(n),n=void 0),i){try{i.close()}catch(e){}i=void 0}};try{const s=new Promise((e,t)=>{n=setTimeout(()=>{t(new Error("WebRTC IP detection timed out after 5 seconds"))},5e3)}),o=new Promise((e,t)=>{i=this._getInternalIPWithWebRTC(i=>{if(i&&i.length>0){for(var n="",r=0;r<i.length;r++)if(C.isValidIPv4Address(i[r])){n=i[r];break}if(!n)return void t(new Error("No valid IPv4 address found in WebRTC candidates"));e(n)}else t(new Error("No IP addresses found"))})});Promise.race([o,s]).then(t=>{r(),e(t)}).catch(e=>{r(),VizbeeTV.logger.error("IPWithWebRTCDeviceID::uniqueDeviceID - error fetching IPAddress:",e.message),t(e)})}catch(e){r(),VizbeeTV.logger.error("IPWithWebRTCDeviceID::uniqueDeviceID - error fetching network info",e),t(e)}}_getInternalIPWithWebRTC(e){var t=[],i=new(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection)({iceServers:[]});return i.createDataChannel(""),i.onicecandidate=function(n){if(n.candidate){var r=/^candidate:.+ (\S+) \d+ typ/.exec(n.candidate.candidate)[1];-1==t.indexOf(r)&&t.push(r)}else{try{i.close()}catch(e){}e(t)}},i.createOffer(function(e){i.setLocalDescription(e)},function(){}),i}}class ue extends X{constructor(){super()}isLaunchedbyVizbee(){let e=this.getLaunchParams();return!(!e||void 0===e.vzb)}getLaunchParams(){return window.webOSDev?webOSDev.launchParams():void 0}}const pe={6:"webOS TV 6.0",7:"webOS TV 22",8:"webOS TV 23",9:"webOS TV 24"};class he extends te{constructor(){super(),this._deviceInfo={};try{window.webOS&&(webOS.service.request("luna://com.webos.service.sm",{method:"deviceid/getIDs",parameters:{idType:["LGUDID"]},onSuccess:e=>{e&&e.idList&&e.idList[0]&&(this._deviceInfo.id=e.idList[0].idValue,VizbeeTV.logger.debug("LGWebOSNativeDeviceInfo::constructor - got deviceId",this._deviceInfo.id))},onFailure:e=>{VizbeeTV.logger.warn('LGWebOSNativeDeviceInfo::constructor - "deviceid/getIDs" failed to fetch deviceId')}}),webOS.service.request("luna://com.webos.service.tv.systemproperty",{method:"getSystemInfo",parameters:{keys:["modelName","firmwareVersion","UHD","sdkVersion"]},onComplete:e=>{e.returnValue?this._deviceInfo=I.extend({},this._deviceInfo,e):VizbeeTV.logger.warn('LGWebOSNativeDeviceInfo::constructor - "getSystemInfo" failed to fetch deviceInfo')}}),webOS.deviceInfo(e=>{e&&(this._deviceInfo=I.extend({},this._deviceInfo,e))}))}catch(e){VizbeeTV.logger.warn('LGWebOSNativeDeviceInfo::constructor - "webOS.deviceInfo" failed to fetch deviceInfo')}}get deviceId(){return this._deviceInfo.id||t}get model(){return this._deviceInfo.modelName||t}get make(){return this._deviceInfo.manufacturer||t}get modelYear(){return t}get friendlyName(){return t}get macAddress(){return t}get os(){return{name:"WebOS",sdkVersion:this._deviceInfo.sdkVersion||t,version:pe[(this._deviceInfo.sdkVersion||t).split(".")[0]]||t}}}class ge extends re{constructor(){super(),this._networkInfo={},window.webOS&&window.webOS.service&&webOS.service.request("luna://com.webos.service.connectionmanager",{method:"getStatus",parameters:{},onSuccess:e=>{this._networkInfo=e},onFailure:e=>{}})}get connectionType(){let e=t;return"connected"===I.get(this._networkInfo,["wifi","state"])?e="WIFI":"connected"===I.get(this._networkInfo,["wired","state"])&&(e="WIRED"),e}get isWifiConnected(){return"connected"===I.get(this._networkInfo,["wifi","state"])}get internalIP(){return I.get(this._networkInfo,["wifi","ipAddress"],t)}get ssid(){return I.get(this._networkInfo,["wifi","ssid"],t)}}class fe extends l{constructor(e){super(e),this.deviceId=new ce,this.launchParams=new ue,this._deviceInfo=new he,this._networkInfo=new ge,this.lgWebOSAppLifeCycleManager=new ae,this.lgWebOSAppLifeCycleManager.init()}createPlayer(){let e={};return navigator.userAgent.indexOf("webOS.TV-2014")>-1?(VizbeeTV.logger.debug("LGWebOSNative::Factory::createPlayer() - WebOS 2014 detected - using webOS player"),e.nativePlayer=G,e.htmlPlayer=G):(VizbeeTV.logger.debug("LGWebOSNative::Factory::createPlayer() > WebOS 2014 detected - using html player"),e={nativePlayer:G,htmlPlayer:G,bitmovinPlayer:W,modularBitmovinPlayer:W,videoJSPlayer:j,theoPlayer:q,shakaPlayer:Y,topPlayer:H}),this.player=new Q(this,e),this.player}createInputDevice(){let e=new N(this);return this.inputDevice=e,e}exit(){super.exit(),window.close()}get defaultAppletAppId(){return"vzb0000001"}get cloudPlatformName(){return"lg_webos"}get launchParamsDeferral(){return this.launchParams}get deviceInfo(){return this._deviceInfo}get networkInfo(){return this._networkInfo}get appLifeCycleManager(){return this.lgWebOSAppLifeCycleManager}}class ve extends l{constructor(e){super(e);const t=this._loadWebOSLibrary();let i=ve.getPlatformType().toLowerCase();this.__platform="lgwebosnative"==i?new fe(e):new de(e),this.__platform.launchParamsDeferral&&(this.__platform.launchParamsDeferral._readyPromise=t)}get cloudPlatformName(){return this.__platform.cloudPlatformName}uniqueDeviceID(e,t){this.__platform.uniqueDeviceID(e,t)}set deviceIDAlgorithm(e){return this.__platform.deviceIDAlgorithm=e}get deviceIDAlgorithm(){return this.__platform.deviceIDAlgorithm}get deviceIDSource(){return this.__platform.deviceIDSource}get platformModel(){return this.__platform.platformModel}get deviceInfo(){return this.__platform.deviceInfo}get platformVersion(){return this.__platform.platformVersion}get networkInfo(){return this.__platform.networkInfo}get adId(){return this.__platform.adId}get isAdTrackingDisabled(){return this.__platform.isAdTrackingDisabled}createInputDevice(){return this.__platform.createInputDevice()}get inputDevice(){return this.__platform.inputDevice}set screenSaverEnabled(e){e=e||!1,void 0!==this.__platform&&this.__platform.enableScreenSaver&&(VizbeeTV.logger.d("LGWebOSVirtualPlatform","creatInputDevice","screenSaverEnabled = "+e),this.__platform.enableScreenSaver(e))}get defaultAppletAppId(){return this.__platform.defaultAppletAppId}get launchParamsDeferral(){return this.__platform.launchParamsDeferral}get appLifeCycleManager(){return this.__platform.appLifeCycleManager}exit(){VizbeeTV.logger.d("LGWebOSVirtualPlatform","exit","exiting the application"),void 0!==this.__platform&&this.__platform.exit&&this.__platform.exit()}set isAppExiting(e){this.__platform.isAppExiting=e}get isAppExiting(){return this.__platform.isAppExiting}reset(){this.__platform.reset()}createPlayer(){return this.__platform.createPlayer()}get player(){return this.__platform.player}set player(e){e&&(this.__platform.player=e)}destroyPlayer(){this.__platform.destroyPlayer()}static getPlatformType(){return window.PalmServiceBridge?"LGWebOSNative":"LGWebOS"}set enableHLSExchange(e){this.__platform.enableHLSExchange=e}_loadWebOSLibrary(){var e=[];return window.webOS||e.push("https://sdk.claspws.tv/libs/webos/webOSTV_1.2.11.js"),window.webOSDev||e.push("https://sdk.claspws.tv/libs/webos/webOSTV_dev_1.2.12.js"),0===e.length?Promise.resolve():e.reduce((e,t)=>e.then(()=>new Promise((e,i)=>{var n=document.createElement("script");n.setAttribute("type","text/javascript"),n.onload=e,n.onerror=i,document.head.appendChild(n),n.setAttribute("src",t)})).catch(e=>{throw VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - FAILED to load library",e),e}),Promise.resolve()).then(()=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - SUCCESS to load library")}).catch(e=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - library load failed, proceeding without it",e)})}}class ye extends le{constructor(){super()}uniqueDeviceID(e,t){var i=this.deviceAPIID||"lg_netcast_device",n=document.getElementById(i);n&&n.net_isConnected?e(n.net_ipAddress):(VizbeeTV.logger.error("LGNetCastDeviceID::uniqueDeviceID - didn't find device API or device not connected"),t())}}class me extends te{constructor(){super()}}class be extends re{constructor(){super()}}const Se={lgwebos:ve,lgnetcast:class extends l{constructor(e){super(e),this.deviceId=new ye,this.deviceId.deviceAPIID=e.deviceAPIID,this.launchParams=new ee,this._deviceInfo=new me,this._networkInfo=new be}createPlayer(){VizbeeTV.logger.debug("LGNetCast::Factory::createPlayer() - creating LG HTML Player");let e={nativePlayer:G,htmlPlayer:G,bitmovinPlayer:W,modularBitmovinPlayer:W,videoJSPlayer:j,theoPlayer:q,shakaPlayer:Y,topPlayer:H};return this.player=new Q(this,e),this.player}createInputDevice(){let e=new N(this);return this.inputDevice=e,e}exit(){"function"==typeof window.NetCastBack?window.NetCastBack():"function"==typeof window.NetCastExit?window.NetCastExit():window.close()}get defaultAppletAppId(){return"vzb0000000"}get cloudPlatformName(){return"lg_netcast"}get launchParamsDeferral(){return this.launchParams}get deviceInfo(){return this._deviceInfo}get networkInfo(){return this._networkInfo}}};let _e,Ee;class Ie extends l{constructor(e,t){if(super(t),e=e.toLowerCase(),!Se[e])throw new TypeError("LGVirtualPlatform::constructor() - platform "+e+" does not exist.");this.__platform=new Se[e](t),this.player,this.inputDevice}static getPlatformType(){if((window.navigator&&window.navigator.userAgent||"").toLowerCase().indexOf("webos.tv")>-1||window.PalmServiceBridge)return"LGWebOS"}static detectPlatformWhenReady(e){e(Ie.getPlatformType())}reset(){_e&&(_e.stop(),VizbeeTV.logger.debug("player reset",_e)),Ee&&(Ee.reset(),Ee=void 0)}uniqueDeviceID(e,t){this.__platform.uniqueDeviceID(e,t)}set enableHLSExchange(e){_e.enableHLSExchange=e}set deviceIDAlgorithm(e){return this.__platform.deviceIDAlgorithm=e}get deviceIDAlgorithm(){return this.__platform.deviceIDAlgorithm}get player(){return void 0===_e&&(_e=this.__platform.createPlayer()),_e}set player(e){e&&(_e=e)}destroyPlayer(){_e.destroy().then(()=>{_e=void 0})}get inputDevice(){return void 0===Ee&&(Ee=this.__platform.createInputDevice()),Ee}set screenSaverEnabled(e){e=e||!1,void 0!==this.__platform&&this.__platform.enableScreenSaver&&(VizbeeTV.logger.debug("LGVirtualPlatform::screenSaverEnabled = "+e),this.__platform.enableScreenSaver(e))}exit(){void 0!==this.__platform&&this.__platform.exit&&this.__platform.exit()}set isAppExiting(e){this.__platform.isAppExiting=e}get isAppExiting(){return this.__platform.isAppExiting}get defaultAppletAppId(){return this.__platform.defaultAppletAppId}get cloudPlatformName(){return this.__platform.cloudPlatformName}get platformModel(){return this.__platform.platformModel}get platformVersion(){return this.__platform.platformVersion}get adId(){return this.__platform.adId}get isAdTrackingDisabled(){return this.__platform.isAdTrackingDisabled}get appLifeCycleManager(){return this.__platform.appLifeCycleManager}get launchParamsDeferral(){return this.__platform.launchParamsDeferral}get deviceInfo(){return this.__platform.deviceInfo}get networkInfo(){return this.__platform.networkInfo}}class Te extends Ie{constructor(e,t){super(e,t),this.setUIStyleConfig("transparent","white","black")}extendPlayer(e,t){VizbeeTV.logger.debug("ExtendPlayer - ",this.player.constructor.name),this.player=new e(this.player,t)}unextendPlayer(){try{if(this.player.extendedPlayer){var e=this.player.extendedPlayer;this.player.reset(),this.player=e}}catch(e){VizbeeTV.logger.error("Error while unextending Player",e,this.player,this.player.extendedPlayer)}}wrapExtension(e,t){this.extendPlayer(e,t)}unwrapExtensionToBasePlayer(){for(;this.player.extendedPlayer;)this.unextendPlayer();this.player.reset()}unwrapExtensionToStandardPlayerControls(){for(;!(this.player instanceof StandardPlayerControls);)this.unextendPlayer()}setUIStyleConfig(e,t,i){this.config.primaryColor=e||this.config.primaryColor,this.config.secondaryColor=t||this.config.secondaryColor,this.config.tertiaryColor=i||this.config.tertiaryColor}}class Ve{constructor(){this.currentLevel=this.LEVEL.CRITICAL,this.enableLogging=!0,this.logPrefix=""}static enableRemoteLogging(e,t){window.console.log=window.console.info=window.console.error=window.console.warn=window.console.debug=function(){let i=new XMLHttpRequest;try{let n=Array.prototype.slice.call(arguments);n=C.convertObjectsToString(n);let r=[t];Array.prototype.push.apply(r,n);let s=encodeURIComponent(JSON.stringify({data:r.join(" ")}));i.open("GET",e+s,!0),i.send(null)}catch(e){}}}get LEVEL(){return{CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4,VERBOSE:5}}setLevel(e){this.currentLevel=e}setPrefix(e){this.logPrefix=e}enable(){this.enableLogging=!0}disable(){this.enableLogging=!1}c(){let e=this._getLogArguments.apply(this,arguments);e&&this.critical.apply(this,e)}critical(){if(this.shouldLog(this.LEVEL.CRITICAL)){var e=Array.prototype.slice.call(arguments);e=C.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [CRITICAL]:"];Array.prototype.push.apply(t,e),console.error.apply(console,t)}}e(){let e=this._getLogArguments.apply(this,arguments);e&&this.error.apply(this,e)}error(){if(this.shouldLog(this.LEVEL.ERROR)){var e=Array.prototype.slice.call(arguments);e=C.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [ERROR]:"];Array.prototype.push.apply(t,e),console.error.apply(console,t)}}w(){let e=this._getLogArguments.apply(this,arguments);e&&this.warn.apply(this,e)}warn(){if(this.shouldLog(this.LEVEL.WARN)){var e=Array.prototype.slice.call(arguments);e=C.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [WARN]:"];Array.prototype.push.apply(t,e),console.warn.apply(console,t)}}i(){let e=this._getLogArguments.apply(this,arguments);e&&this.info.apply(this,e)}info(){if(this.shouldLog(this.LEVEL.INFO)){var e=Array.prototype.slice.call(arguments);e=C.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [INFO]:"];Array.prototype.push.apply(t,e),console.info.apply(console,t)}}d(){let e=this._getLogArguments.apply(this,arguments);e&&this.debug.apply(this,e)}debug(){if(this.shouldLog(this.LEVEL.DEBUG)){var e=Array.prototype.slice.call(arguments);e=C.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [DEBUG]:"];Array.prototype.push.apply(t,e),console.log.apply(console,t)}}v(){let e=this._getLogArguments.apply(this,arguments);e&&this.verbose.apply(this,e)}verbose(){if(this.shouldLog(this.LEVEL.VERBOSE)){var e=Array.prototype.slice.call(arguments);e=C.convertObjectsToString(e);let t=[this.getCurrentTimeString()+" "+this.logPrefix+" [VERBOSE]:"];Array.prototype.push.apply(t,e),console.log.apply(console,t)}}shouldLog(e){return!!this.enableLogging&&e<=this.currentLevel}_getLogArguments(){let e=Array.prototype.slice.call(arguments);if(e&&e.length>=2){let t=[this._getClassAndMethodNamePrefix(e[0],e[1])],i=Array.prototype.slice.call(arguments,2);return Array.prototype.push.apply(t,i),t}}_getClassAndMethodNamePrefix(e,t){return e&&t?C.padEnd(e+"::",40," ")+C.padEnd(t,30," ")+" - ":""}getCurrentTimeString(){return"["+(new Date).toISOString()+"]"}}class Pe extends Ve{constructor(){super()}critical(){try{super.critical(...arguments);let e=Array.prototype.slice.call(arguments);if(e.length>0){let t=e[e.length-1],i=window.Raven||window.Sentry;this._shouldLogException()&&i&&(I.isObject(t)||I.isString(t))&&i.captureException(t)}}catch(e){}}_shouldLogException(){return!0}}var Ae,De;function Ce(){if(De)return Ae;De=1;var e,t={getItem:function(e){return e&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null},setItem:function(e,t,i,n,r,s){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e))return!1;var o="";if(i)switch(i.constructor){case Number:o=i===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+i;break;case String:o="; expires="+i;break;case Date:o="; expires="+i.toUTCString()}return document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+o+(r?"; domain="+r:"")+(n?"; path="+n:"")+(s?"; secure":""),!0},removeItem:function(e,t,i){return!!this.hasItem(e)&&(document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT"+(i?"; domain="+i:"")+(t?"; path="+t:""),!0)},hasItem:function(e){return!!e&&new RegExp("(?:^|;\\s*)"+encodeURIComponent(e).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:function(){for(var e=document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:\=[^;]*)?;\s*/),t=e.length,i=0;i<t;i++)e[i]=decodeURIComponent(e[i]);return e},eraseCookieFromAllPaths:function(e){var t=location.pathname.split("/"),i=" path=";document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;";for(var n=0;n<t.length;n++)i+=("/"!=i.substr(-1)?"/":"")+t[n],document.cookie=encodeURIComponent(e)+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT;"+i+";"}},i=(e=function(){for(var e,t={},i=decodeURIComponent(window.location.href),n=i.slice(i.indexOf("?")+1).split("&"),r=0;r<n.length;r++)t[(e=n[r].split("="))[0]]=e[1];return t}()||{},{getQueryParamForKey:function(t){return e[t]||!1},getQueryParams:function(){return e}});return Ae={chain:function(e,t){return e?function(){e.call(this,arguments),t.call(this,arguments)}:t},xhr:function(e){return new Promise(function(t,i){var n=e.retries||2;!function r(){var s=new XMLHttpRequest;e.url=e.url.replace(/^http:\/\//i,"https://"),s.open(e.method||"GET",e.url,!0),Object.keys(e.headers||{}).forEach(function(t){s.setRequestHeader(t,e.headers[t])}),s.onreadystatechange=function(o){if(4===s.readyState)if(-1===[200,304].indexOf(s.status))VizbeeSDK.logger.error("xhr error",o),n>0?(n--,r()):i(new Error("Server responded with a status of "+s.status));else try{e.format=e.format||"json";var a=o.target;"json"===e.format?a=JSON.parse(a.response):"xml"===e.format&&(a=a.responseXML),VizbeeSDK.logger.debug("Util::xhr() -- response object --",a),t(a)}catch(o){n>0?(n--,r()):i("JSON parse error with Server response")}},e.timeout&&(s.timeout=e.timeout,s.ontimeout=function(t){n>0?(n--,r()):i(new Error("Server timeout "+e.timeout+"ms"))}),s.send(e.data)}()})},log:function(){var e=Array.prototype.slice.call(arguments);e.unshift("VIZBEE [LOG]"),console.log.apply(console,e)},docCookies:t,urlParser:i},Ae}function ke(e,t,i){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}window.VizbeeTV={logger:function(){const e=new Pe;return e.setPrefix("[VTVLIB]"),e}(),init:function(e,t,i){this.logger=new Pe,this.logger.setPrefix("[VTVLIB]"),this.Util=C,i?this.tv instanceof Te?this.tv.config=I.extend(this.tv.config,t):this.tv=new Te(e,t):this.tv instanceof Ie?this.tv.config=I.extend(this.tv.config,t):this.tv=new Ie(e,t)}};const we=C,Ne="https://events.claspws.tv/v1/event";var Oe=new class{send(e,t,i){try{const n=i||Ne,r=btoa(unescape(encodeURIComponent(JSON.stringify({event:e,properties:t})))),s=window.encodeURIComponent(r),o={timeout:1e4,retries:2};s.length>1e4?(o.url=n,o.method="POST",o.data=JSON.stringify({data:s})):(o.url=n+"?data="+s,o.method="GET"),we.xhr(o).then(()=>{VizbeeSDK.logger.d("DiagnosticsEventSender","send",e,"SUCCESS")}).catch(t=>{VizbeeSDK.logger.w("DiagnosticsEventSender","send",e,"ERROR",t)})}catch(t){VizbeeSDK.logger.w("DiagnosticsEventSender","send",e,"failed to send",t)}}};let Re=class{static setItem(e,t,i,n,r,s,o){if(e)if("undefined"!=typeof Storage)vizbee.logger.debug("StorageUtil::setItem - Storage supported!"),"session"==i?(vizbee.logger.debug("StorageUtil::setItem - storing in session!"),sessionStorage.setItem(e,t)):(vizbee.logger.debug("StorageUtil::setItem - storing in local!"),localStorage.setItem(e,t));else{if(vizbee.logger.debug("StorageUtil::setItem - Storage NOT supported!"),"session"==i)return;vizbee.logger.debug("StorageUtil::setItem - storing in cookies!"),C.docCookies.setItem(e,t,n,r,s,o)}}static getItem(e,t){if(e){if("undefined"!=typeof Storage)return vizbee.logger.debug("StorageUtil::getItem - Storage supported!"),"session"==t?(vizbee.logger.debug("StorageUtil::getItem - getting from session!"),sessionStorage.getItem(e)):(vizbee.logger.debug("StorageUtil::getItem - getting from local!"),localStorage.getItem(e)||sessionStorage.getItem(e));if(vizbee.logger.debug("StorageUtil::getItem - Storage NOT supported!"),"session"!=t)return vizbee.logger.debug("StorageUtil::getItem - getting from cookies!"),C.docCookies.getItem(e)}}static removeItem(e,t,i,n){if(e)if("undefined"!=typeof Storage)"session"==t?sessionStorage.removeItem(e):localStorage.removeItem(e)||sessionStorage.removeItem(e);else{if("session"==t)return;C.docCookies.removeItem(e,i,n)}}};const Me=Re,Le="UNKNOWN",xe=/status of (\d+)/,ze="SCREEN_SDK_ID",Ke="PLATFORM_DETECTION",Ue="SDK_START",Fe="CONFIG_FETCH",Be="DEVICE_ID",Ge="SYNC_INIT",He="UNKNOWN",We="CONFIG_INVALID_RESPONSE",je="CONFIG_HTTP_ERROR",qe="UNCAUGHT_EXCEPTION";var Ye,Je,Qe,$e,Ze,Xe,et=new class{constructor(){ke(this,"appId",void 0),ke(this,"startTime",Date.now()),ke(this,"stage",Ke),ke(this,"config",void 0),ke(this,"isEnabled",!1),ke(this,"didReport",!1),ke(this,"didLaunch",!1)}start(e){this.appId=e,this.startTime=Date.now(),this.stage=Ke,this.config=void 0,this.isEnabled=!0,this.didReport=!1,this.didLaunch=!1}setStage(e){this.stage=e}setConfig(e){this.config=e}markLaunched(){this.didLaunch=!0}report(e,t,i,n){try{if(!this.isEnabled||this.didReport||this.didLaunch)return;this.didReport=!0;const r=Object.assign(this.buildProperties(e,t,i),this.buildFailureInfoProperties(this.buildFailureInfo(e,t,i,n)));VizbeeSDK.logger.e("LaunchFailureReporter","report",e,t,r.FAILURE_VALUE),this.send(r)}catch(e){VizbeeSDK.logger.w("LaunchFailureReporter","report","failed to report",e)}}getConfigFetchFailureCode(e){const t=this.toString(e);return 0==t.indexOf("Server timeout")?"CONFIG_TIMEOUT":0==t.indexOf("Server responded with a status of 0")?"CONFIG_NETWORK_ERROR":0==t.indexOf("Server responded with a status of")?je:We}getMetricsUrl(){var e;return(null===(e=this.config)||void 0===e||null===(e=e.metricsParams)||void 0===e?void 0:e.vizbee_url)||Ne}buildProperties(e,t,i){const n=this.getScreenSdkId(),r=this.config||{},s={APP_ID:this.appId||r.appId||Le,FAILURE_STAGE:e,FAILURE_CODE:t,FAILURE_VALUE:this.toString(i).substring(0,500),LAST_STAGE:this.stage,ELAPSED_MS:Date.now()-this.startTime,distinct_id:this.getPlatformDeviceId()||r.deviceId||n,SCREEN_SDK_ID:n,SCREEN_SDK_VERSION:window.VZB?window.VZB.VERSION:Le,SCREEN_DEVICE_TYPE:this.getCloudPlatformName(),SCREEN_DEVICE_ID:r.deviceId||Le,SCREEN_DEVICE_USERAGENT:window.navigator&&window.navigator.userAgent||Le,EXTERNAL_IP_ADDRESS:r.externalIp||Le,TIMEZONE:this.getTimezone(),VZB_TIMESTAMP:Date.now()};return e==Ke&&Object.assign(s,this.getPlatformSignals()),s}buildFailureInfo(e,t,i,n){const r=n&&"object"==typeof n?n:{},s=this.config||{},o=Object.assign({},r.errorDetails);return s.ipv6Address&&(o.ipv6Address=s.ipv6Address),{vizbeeError:t,source:r.source||(e==Fe?"VIZBEE_CONFIG_SERVICE":"VIZBEE_SDK"),operation:r.operation||e,errorCode:void 0!==r.errorCode?r.errorCode:this.getHttpStatus(t,i),errorMessage:(r.errorMessage||this.toString(i)).substring(0,200)||void 0,errorDetails:Object.keys(o).length>0?this.toDetailsJson(o):void 0}}buildFailureInfoProperties(e){const t={FAILURE_VALUE_VIZBEE_ERROR:e.vizbeeError,FAILURE_VALUE_SOURCE:e.source,FAILURE_VALUE_OPERATION:e.operation,FAILURE_VALUE_ERROR_CODE:e.errorCode,FAILURE_VALUE_ERROR_MESSAGE:e.errorMessage,FAILURE_VALUE_ERROR_DETAILS:e.errorDetails},i={};return Object.keys(t).forEach(e=>{null!=t[e]&&(i[e]=t[e])}),i}getHttpStatus(e,t){if(e!=je)return;const i=xe.exec(this.toString(t));return i?parseInt(i[1],10):void 0}toDetailsJson(e){try{return JSON.stringify(e).substring(0,2e3)}catch(e){return""}}getPlatformDeviceId(){try{const e=VizbeeTV.tv&&VizbeeTV.tv.deviceInfo&&VizbeeTV.tv.deviceInfo.deviceId;return e&&e!=Le?""+e:void 0}catch(e){return}}getPlatformSignals(){const e=window;let t=Le;try{t=Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily}catch(e){}return{HAS_WINDOW_CAST:!!e.cast,HAS_WEBAPIS:!!e.webapis,HAS_VIZIO:!!e.VIZIO,HAS_PALM_SERVICE_BRIDGE:!!e.PalmServiceBridge,HAS_WINDOWS_RT:"undefined"!=typeof Windows,HAS_WEBVIEW2_HOST:!!(e.vizbeeXboxHost&&e.chrome&&e.chrome.webview),WINDOWS_DEVICE_FAMILY:t}}getScreenSdkId(){try{let e=Me.getItem(ze);return e||(e=Math.floor(1e10*Math.random()).toString()+"_"+Date.now(),Me.setItem(ze,e,"local",31536e3,"/")),e}catch(e){return Le}}getCloudPlatformName(){try{return VizbeeTV.tv&&VizbeeTV.tv.cloudPlatformName||Le}catch(e){return Le}}getTimezone(){const e=-(new Date).getTimezoneOffset(),t=e>=0?"+":"-",i=Math.abs(e);return"GMT"+t+("0"+Math.floor(i/60)).slice(-2)+":"+("0"+i%60).slice(-2)}toString(e){if(null==e)return"";if("string"==typeof e)return e;if(e.message)return""+e.message;try{return JSON.stringify(e)}catch(t){return""+e}}send(e){Oe.send("SCREEN_LAUNCH_FAILURE",e,this.getMetricsUrl())}},tt=Ce().xhr,it=E(),nt={appId:null,config:null,pub_key:"pub-c-1e4f216f-168e-4fdc-8a2b-a29ffe05cb5b",sub_key:"sub-c-6da25f1b-58d7-4f17-bd10-21a30198a794"},rt={appConfig:nt,getConfig:function(e,t){nt.appId=e.appId,nt.platform=e.platform,nt.platformModel=e.platformModel,nt.hostProxy=e.hostProxy,function(){var e="config.claspws.tv";nt.hostProxy&&(e=nt.hostProxy),Ye=nt.platform,Je=nt.platformModel;var t="//"+e+"/api/v2/";t+="apps/"+nt.appId+"/screen/"+Ye,Je&&(t+="."+Je);let i=!1;if(window&&window.navigator&&window.navigator.language){var n=window.navigator.language.split("-");n.length>1&&(t+="?country="+n[1],i=!0)}return t+=(i?"&":"?")+"seed="+Math.round(1e3*Math.random()),VizbeeSDK.logger.debug("Config:getAPIConfig - didn't find any saved config from local storage. Calling config server ..."),t="https:"+t,VizbeeSDK.logger.debug("Config:getAPIConfig - URL = "+t),tt({url:t,retries:3,timeout:3e4,headers:{Accept:"application/json"}}).then(function(e){if(e&&e.error&&100==e.error.code)return VizbeeSDK.logger.error("Config:getAPIConfig - received error code and message = ",e.error.code,e.error.message),VizbeeSDK.logger.error("Config:getAPIConfig - screen device may not be allowed or setup. Screen device platform = ",nt.platform),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),et.report(Fe,"CONFIG_APP_NOT_ALLOWED",e.error.message),Promise.reject(e.error);if(e&&e.data&&e.data.items&&e.data.items[0]){if(e.data.items[0].channelKeys.pub_key&&e.data.items[0].channelKeys.sub_key){var t=e.data.items[0];return t.externalIp=e.externalIpAddress,VizbeeSDK.logger.debug("Config:getAPIConfig - valid config returned by API",t),VizbeeSDK.logger.debug("Config:getAPIConfig - SDK init SUCCESS!"),t}return VizbeeSDK.logger.error("Config:getAPIConfig - got config response but no channel pub keys or sub keys!"),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),et.report(Fe,"CONFIG_MISSING_CHANNEL_KEYS"),Promise.reject("No pub sub keys for given appId")}return VizbeeSDK.logger.error("Config:getAPIConfig - invalid response (but no error!) returned by server"),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),et.report(Fe,We),Promise.reject("Invalid response")}).catch(function(e){return VizbeeSDK.logger.error("Config:getAPIConfig - XHR request to get config failed"),VizbeeSDK.logger.error("Config:getAPIConfig - SDK init FAILED!"),et.report(Fe,et.getConfigFetchFailureCode(e),e),Promise.reject(e)})}().then(function(e){if(VizbeeSDK.logger.debug("Config:getConfig - got apiConfig",e),it.extend(nt,e),e.channelKeys.pub_key&&e.channelKeys.sub_key&&(nt.pub_key=e.channelKeys.pub_key,nt.sub_key=e.channelKeys.sub_key),"function"==typeof t){VizbeeSDK.logger.debug("Config:getConfig - calling callback with extended config =",nt);try{t(nt)}catch(e){throw et.report(He,qe,e),e}}}).catch(function(e){et.report(Fe,We,e);var t="SDK CONFIG FETCH FAILED";null!=e&&(t+=" - "+e.message);var i=new Error(t);VizbeeSDK.logger.critical("Config::getConfig - SDK CONFIG FETCH FAILED",i),VizbeeSDK.logger.error("Config::getConfig - NOTE - could be a failure in the callback passed to getConfig!")})}},st={getIpv6Address:function(e){C.xhr({url:"https://ip.claspws.tv",timeout:5e3,retries:3}).then(t=>{var i=t&&t.headers&&t.headers["x-vzb-client-ip"];i?(VizbeeSDK.logger.debug("Ipv6::getIpv6Address - ipv6Address=",i),e(i)):(VizbeeSDK.logger.warn("Ipv6::getIpv6Address - ipv6Address=empty"),e())}).catch(t=>{VizbeeSDK.logger.warn("Ipv6::getIpv6Address - failed",t),e()})}};function ot(){if($e)return Qe;function e(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function t(e){return"function"==typeof e}function i(e){return"object"==typeof e&&null!==e}function n(e){return void 0===e}return $e=1,Qe=e,e.EventEmitter=e,e.prototype._events=void 0,e.prototype._maxListeners=void 0,e.defaultMaxListeners=10,e.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},e.prototype.emit=function(e){var r,s,o,a,d,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((r=arguments[1])instanceof Error)throw r;var c=new Error('Uncaught, unspecified "error" event. ('+r+")");throw c.context=r,c}if(n(s=this._events[e]))return!1;if(t(s))switch(arguments.length){case 1:s.call(this);break;case 2:s.call(this,arguments[1]);break;case 3:s.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),s.apply(this,a)}else if(i(s))for(a=Array.prototype.slice.call(arguments,1),o=(l=s.slice()).length,d=0;d<o;d++)l[d].apply(this,a);return!0},e.prototype.addListener=function(r,s){var o;if(!t(s))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",r,t(s.listener)?s.listener:s),this._events[r]?i(this._events[r])?this._events[r].push(s):this._events[r]=[this._events[r],s]:this._events[r]=s,i(this._events[r])&&!this._events[r].warned&&(o=n(this._maxListeners)?e.defaultMaxListeners:this._maxListeners)&&o>0&&this._events[r].length>o&&(this._events[r].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[r].length),"function"==typeof console.trace&&console.trace()),this},e.prototype.on=e.prototype.addListener,e.prototype.once=function(e,i){if(!t(i))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,i.apply(this,arguments))}return r.listener=i,this.on(e,r),this},e.prototype.removeListener=function(e,n){var r,s,o,a;if(!t(n))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(o=(r=this._events[e]).length,s=-1,r===n||t(r.listener)&&r.listener===n)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,n);else if(i(r)){for(a=o;a-- >0;)if(r[a]===n||r[a].listener&&r[a].listener===n){s=a;break}if(s<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(s,1),this._events.removeListener&&this.emit("removeListener",e,n)}return this},e.prototype.removeAllListeners=function(e){var i,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(i in this._events)"removeListener"!==i&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events={},this}if(t(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},e.prototype.listeners=function(e){return this._events&&this._events[e]?t(this._events[e])?[this._events[e]]:this._events[e].slice():[]},e.prototype.listenerCount=function(e){if(this._events){var i=this._events[e];if(t(i))return 1;if(i)return i.length}return 0},e.listenerCount=function(e,t){return e.listenerCount(t)},Qe}function at(){if(Xe)return Ze;Xe=1;var e,t=new(0,ot().EventEmitter);return Ze={reset:function(){e=void 0},getApp:function(){return e},setApp:function(i){i&&(e=i,VizbeeSDK.logger.debug("AppAdapter::setApp in setApp"),t.emit("app",{type:"app",obj:i}))},isAppSet:function(){return!!e},preInit:function(){VizbeeSDK.logger.debug("AppAdapter::preInit() called"),e&&e.preInit?e.preInit():VizbeeSDK.logger.error("AppAdapter::preInit() - app.preInit() callback not provided by host app")},willStartVideo:function(t,i){e&&e.willStartVideo?e.willStartVideo(t,i):VizbeeSDK.logger.info("AppAdapter::willStartVideo() - app.willStartVideo() callback not provided by host app")},startVideo:function(t){e&&e.startVideo?e.startVideo(t):VizbeeSDK.logger.info("AppAdapter::StartVideo() - app.startVideo() callback not provided by host app")},playVideo:function(){return VizbeeSDK.logger.info("AppAdapter::PlayVideo() called"),e&&e.playVideo?e.playVideo():(VizbeeSDK.logger.info("AppAdapter::PlayVideo() - app.playVideo() callback not provided by host app"),!1)},pauseVideo:function(){return VizbeeSDK.logger.info("AppAdapter::PauseVideo() called"),e&&e.pauseVideo?e.pauseVideo():(VizbeeSDK.logger.info("AppAdapter::PauseVideo() - app.pauseVideo() callback not provided by host app"),!1)},stopVideo:function(t){return VizbeeSDK.logger.info("AppAdapter::StopVideo() called",t,e),VizbeeSDK.logger.debug("AppAdapter::StopVideo() called"),e&&e.stopVideo?(VizbeeSDK.logger.info("AppAdapter::StopVideo() called",t),e.stopVideo(t)):(VizbeeSDK.logger.info("AppAdapter::StopVideo() - app.stopVideo() callback not provided by host app"),!1)},seekVideo:function(t){return VizbeeSDK.logger.info("AppAdapter::SeekVideo() called",t),e&&e.seekVideo?e.seekVideo(t):(VizbeeSDK.logger.info("AppAdapter::SeekVideo() - app.seekVideo() callback not provided by host app"),!1)},getVideoInfo:function(){if(e&&e.getVideoInfo)return e.getVideoInfo()},getTracks:function(){return e&&e.getTracks?e.getTracks():(VizbeeSDK.logger.verbose("AppAdapter::getTracks() - app.getTracks() callback not provided by host app"),!1)},getEnabledTracks:function(){return e&&e.getEnabledTracks?e.getEnabledTracks():(VizbeeSDK.logger.verbose("AppAdapter::getEnabledTracks() - app.getEnabledTracks() callback not provided by host app"),!1)},enableTracks:function(t){return VizbeeSDK.logger.verbose("AppAdapter::enableTracks() called"),e&&e.enableTracks?e.enableTracks(t):(VizbeeSDK.logger.verbose("AppAdapter::enableTracks() - app.enableTracks() callback not provided by host app"),!1)},disableTracks:function(t){return VizbeeSDK.logger.verbose("AppAdapter::disableTracks() called"),e&&e.disableTracks?e.disableTracks(t):(VizbeeSDK.logger.verbose("AppAdapter::disableTracks() - app.disableTracks() callback not provided by host app"),!1)},getAudioTracks:function(){return e&&e.getAudioTracks?e.getAudioTracks():(VizbeeSDK.logger.verbose("AppAdapter::getAudioTracks() - app.getAudioTracks() callback not provided by host app"),!1)},getActiveAudioTrack:function(){return e&&e.getActiveAudioTrack?e.getActiveAudioTrack():(VizbeeSDK.logger.verbose("AppAdapter::getActiveAudioTrack() - app.getActiveAudioTrack() callback not provided by host app"),!1)},changeAudioTrack:function(t){return VizbeeSDK.logger.info("AppAdapter::changeAudioTrack() called"),e&&e.changeAudioTrack?e.changeAudioTrack(t):(VizbeeSDK.logger.info("AppAdapter::changeAudioTrack() - app.changeAudioTrack() callback not provided by host app"),!1)},onEvent:function(t){VizbeeSDK.logger.debug("AppAdapter::onEvent() called"),e&&e.onEvent?e.onEvent(t):VizbeeSDK.logger.info("AppAdapter::onEvent() - callback not provided by host app")},updatePresence:function(t){VizbeeSDK.logger.debug("AppAdapter::updatePresence() called"),e&&e.updatePresence?e.updatePresence(t):VizbeeSDK.logger.info("AppAdapter::updatePresence() - callback not provided by host app")},addListener:function(e){t.addListener("app",e)}},Ze}var dt,lt,ct=E(),ut=new(0,ot().EventEmitter),pt=at(),ht=void 0,gt={isInProgress:!1},ft=!1,vt=0,yt="videoadapter_video",mt="videoadapter_ad";function bt(e){var t,i,n=!ct.contains(["timeupdate"],e.type);gt.isInProgress||(ht&&"app"!==ht.app.state?(t=new _t,e.type,"loading"===e.type&&(i="BUFFERING"),"playing"===e.type&&(i="PLAYING"),"paused"===e.type&&(i="PAUSED_BY_USER"),"ended"==e.type&&(i="FINISHED"),"interrupted"==e.type&&(i="INTERRUPTED"),"error"===e.type&&(i="INTERRUPTED",e.data&&e.data.reason&&"stop_by_user"!=e.data.reason.toLowerCase()&&(i="FAILED",t.error=e.data,t.error.data={})),i&&(t.state=i),ut.emit(yt,t,n)):VizbeeSDK.logger.verbose('VideoAdapter::videoEventHandler - app.state = "app"'))}function St(e,t){var i=e.playing||e.preparing;(i||!i&&gt.isInProgress)&&ut.emit(mt,e,t),gt.isInProgress=i||!1,gt.isInProgress||(ft=!1),"FINISHED"==e.state||e.state}function _t(e){var t={type:"video",position:-1,duration:-1,cc:{},tr:{}};return lt?(t.position=1e3*lt.currentTime(),t.duration=1e3*lt.getDuration(),t.startTime=lt.getStartTime(),t.videoBufferLevel=lt.getBufferLevel(),t.audioBufferLevel=lt.getAudioBufferLevel(),t.qos=lt.getStreamQualityInfo(),t.volume=100,t.muted=!1):(t.position=-1,t.duration=-1,t.startTime=0,t.videoBufferLevel=0,t.audioBufferLevel=0,t.volume=1,t.muted=!1),t.qos||(t.qos={adPodStartedTimeInMs:0,adPodEndedTimeInMs:0,loadReceivedByAppTimeInMs:0,loadReceivedByPlayerTimeInMs:0,metadataLoadedTimeInMs:0,playerReadyToPlayTimeInMs:0,playbackStartedTimeInMs:0}),ct.extend(t,e)}var Et=["stop_reason_before_next_video","stop_implicit"];function It(){gt.isInProgress&&dt.reset()}var Tt,Vt,Pt,At,Dt,Ct,kt,wt,Nt,Ot,Rt,Mt,Lt,xt,zt={setVideo:function(e){!function(e){var t=++vt;function i(){return t!==vt&&(VizbeeSDK.logger.debug("VideoAdapter::registerVideoEvents - dropping event from superseded player",t,vt),!0)}e.onLoading=function(e){i()||gt.isInProgress||(bt({type:"loading"}),ft=!1)},e.onPlaying=function(e){i()||gt.isInProgress||(bt({type:"playing"}),ft=!0)},e.onPaused=function(e){i()||gt.isInProgress||(bt({type:"paused"}),ft=!1)},e.onBuffering=function(e){i()||gt.isInProgress||(bt({type:"loading"}),ft=!1)},e.onError=function(e){i()||gt.isInProgress||(bt({type:"error",data:e}),ft=!1)},e.onInterrupted=function(e){i()||gt.isInProgress||(bt({type:"interrupted",data:e}),ft=!1)},e.onEnded=function(){i()||gt.isInProgress||(bt({type:"ended"}),ft=!1)},e.onTimeUpdate=function(e){i()||gt.isInProgress||(ft?bt({type:"timeupdate"}):(ft=!0,bt({type:"playing"})))}}(e),lt=e},setVideoInfo:function(e){e&&ht&&ht.setCurrentVideoInfo(e)},setId:function(e,t){if(ht){if(ht.video&&ht.video.id&&e&&ht.video.id!=e){VizbeeSDK.logger.debug("VideoAdapter::setId - SENDING INTERRUPTED");var i=new _t({id:ht.video.id,state:"INTERRUPTED"});ut.emit(yt,i,!0)}var n=new _t({id:e});n.position=n.duration=-1,n.state="UNKNOWN",ut.emit(yt,n,!0),VizbeeSDK.logger.debug("VideoAdapter::setId - setting currentGUID = "+e),ht.setCurrentVideoInfo(ct.extend(ht.getCurrentVideoInfo()||{},{id:e,islive:t}))}},setVideoStop:function(){gt&&gt.isInProgress&&dt&&(gt.isInProgress=!1,dt.reset()),bt({type:"error"})},willStart:function(e,t){pt.willStartVideo(e,t)},start:function(e){bt({type:"loadedmetadata"}),It(),pt.startVideo(e)},play:function(){pt.playVideo()||VizbeeTV.tv.inputDevice.sendPlay()},pause:function(){pt.pauseVideo()||VizbeeTV.tv.inputDevice.sendPause()},seek:function(e){pt.seekVideo(e)||ct.isNumber(e)&&lt.seek(e)},stop:function(e){if(pt.stopVideo(e))ct.contains(Et,e)&&(VizbeeSDK.logger.debug("VideoAdapter::stop - host handled switch stop; sending INTERRUPTED state"),ut.emit(yt,new _t({state:"INTERRUPTED"}),!0));else{VizbeeTV.tv.inputDevice.sendStop(),VizbeeSDK.logger.debug("VideoAdapter::stop - sending INTERRUPTED state");var t=new _t({state:"INTERRUPTED"});ut.emit(yt,t,!0),It()}},exit:function(){var e=new _t({state:"INTERRUPTED"});ut.emit(yt,e,!0)},setTracks:function(e){lt.setTracks(e)},getTracks:function(e){e=e||n;var t=pt.getTracks();return!1!==t?t:lt.getTracks(e)},getEnabledTracks:function(e){e=e||n;var t=pt.getEnabledTracks();return!1!==t?t:lt.getEnabledTracks(e)},enableTracks:function(e){pt.enableTracks(e)||lt.enableTracks(e)},disableTracks:function(e){pt.disableTracks(e)||lt.disableTracks(e)},getAudioTracks:function(e){e=e||r;var t=pt.getAudioTracks();return!1!==t?t:lt.getTracks(e)},getActiveAudioTrack:function(e){e=e||r;var t=pt.getActiveAudioTrack();return!1!==t?t:(lt.getEnabledTracks(e)||[])[0]},changeAudioTrack:function(e){pt.changeAudioTrack(e)||lt.changeAudioTrack(e)},mute:function(e){},volumeUp:function(){ut.emit(yt,new _t,!0)},volumeDown:function(){ut.emit(yt,new _t,!0)},onEvent:function(e){pt.onEvent(e)},setAdAdapter:function(e){dt&&dt.removeListener(St),(dt=e)&&dt.addListener(St)},setAppStateManager:function(e){ht=e},reset:function(){lt=void 0,gt={playing:!1}},addListener:function(e){ut.addListener(yt,e),ut.addListener(mt,e)},removeListener:function(e){ut.removeListener(yt,e),ut.removeListener(mt,e)}};function Kt(){if(Vt)return Tt;Vt=1;var e,t=E();return Tt={reset:function(){e=void 0},setVideoAdapter:function(t){e=t},isAdapterSet:function(){return!!e},getCurrentTime:function(){var i=0;return e&&t.isFunction(e.getCurrentTime)&&(i=e.getCurrentTime()),i},getDuration:function(){var i=0;return e&&t.isFunction(e.getDuration)&&(i=e.getDuration()),i}}}function Ut(){if(At)return Pt;At=1;var e=new(0,ot().EventEmitter),t=zt,i=Kt(),n=void 0;function r(t,r){"video"==t.type&&(t=function(e,t){return t||e.position<=-1||e.duration<=-1||e.position>e.duration||i.isAdapterSet()&&(e.position=i.getCurrentTime(),e.duration=i.getDuration(),VizbeeSDK.logger.debug("ssaivideoadapater::modifyStatus",e.position,e.duration)),e}(t,n&&n.getSyncVideoInfo().islive)),function(t,i){e.emit("ssaivideoadapter_video",t,i)}(t,r)}return Pt={init:function(){t.addListener(r)},setVideo:t.setVideo,setVideoInfo:t.setVideoInfo,setId:t.setId,setVideoStop:t.setVideoStop,willStart:t.willStart,start:t.start,play:t.play,pause:t.pause,seek:t.seek,stop:t.stop,exit:t.exit,setTracks:t.setTracks,getTracks:t.getTracks,getEnabledTracks:t.getEnabledTracks,enableTracks:t.enableTracks,disableTracks:t.disableTracks,getAudioTracks:t.getAudioTracks,getActiveAudioTrack:t.getActiveAudioTrack,changeAudioTrack:t.changeAudioTrack,mute:t.mute,volumeUp:t.volumeUp,volumeDown:t.volumeDown,onEvent:t.onEvent,setAppStateManager:function(e){n=e,t.setAppStateManager(e)},setAdAdapter:t.setAdAdapter,reset:function(){n=void 0,t.removeListener(r),t.reset()},addListener:function(t){e.addListener("ssaivideoadapter_video",t)},removeListener:function(t){e.removeListener("ssaivideoadapter_video",t)}}}function Ft(){if(Ct)return Dt;Ct=1;var e=E(),t=new(0,ot().EventEmitter),i=Ut(),n=at(),r={state:"app"},s={},o={},a="default",d={},l={};function c(e){d=e}function u(t,i){"app"===t.type&&p(),"video"===t.type&&function(t,i){e.extend(s,t),["FINISHED","INTERRUPTED","FAILED"].indexOf(s.state)>-1?(VizbeeSDK.logger.debug("AppStateManager::videoEventHanlder() -- setting app.state to 'app'."),h(),r.state="app",g()):(r.state="video",i&&h())}(t,i),"ad"===t.type&&function(t,i){let a=i;t.playing||t.preparing?(r.state="ad",s.state="PAUSED_BY_AD",e.extend(o,t)):(o.preparing=!1,o.playing=!1,"INTERRUPTED"==t.state?(r.state="app",s.state="INTERRUPTED",a=!0):"PAUSED_BY_AD"==s.state&&(s.state="UNKNOWN"),!function(){let e=!1;l&&l.id&&(e=!d||d.id&&d.id!=l.id||!d.id?l.islive:d.islive);let t=n.getVideoInfo();return t&&void 0!==t.islive&&(e=t.islive),!0===e||"true"===e}()&&s.duration<=s.position&&s.duration>0&&(r.state="app",s.state="FINISHED",a=!0)),a&&h()}(t,i)}function p(){VizbeeSDK.logger.debug("AppStateManager:appEventHandler appIsSet is TRUE"),t.emit("state",{type:"appIsSet"})}function h(){t.emit("state",{})}function g(){VizbeeSDK.logger.debug("AppStateManager:reset() previous video and ad objects = ",s,o,d),s.id="",s.state="UNKNOWN",s.position=-1,s.duration=-1,s.elapsedTime=0,s.tr={},s.error={},o.id="",o.state="UNKNOWN",o.position=-1,o.duration=-1,a={},VizbeeSDK.logger.debug("AppStateManager:reset() complete : current video and ad objects = ",s,o,d)}return g(),i.addListener(u),n.addListener(u),n.isAppSet()&&p(),Dt={type:"AppStateManager",app:r,video:s,ad:o,reset:g,syncStartVideoSource:a,syncVideoInfo:d,setSyncVideoInfo:c,getSyncVideoInfo:function(){return d},currentVideoInfo:l,setCurrentVideoInfo:function(e){l=e,d&&e&&d.id!=e.id&&c({})},getCurrentVideoInfo:function(){return l},wasVideoStartedByVizbee:function(){return!!(l&&l.senderInfo&&l.senderInfo.st)||!(!d||!l||d.id!=l.id)},addListener:function(e){t.addListener("state",e)},removeListener:function(e){t.removeListener("state",e)}}}function Bt(){return Ot?Nt:(Ot=1,Nt={setVGA:function(t){t&&(e=t,VizbeeSDK.logger.debug("VGAAdapter::setVGA in setVGA"))},onSubscribedToSync:function(){VizbeeSDK.logger.debug("VGAAdapter::subscribedToSync in subscribedToSync"),e&&e.onSubscribedToSync&&e.onSubscribedToSync()},reset:function(){e=void 0}});var e}function Gt(){if(Mt)return Rt;Mt=1;var e=new(0,ot().EventEmitter),t="sync_proxy_video_cmds";return Rt={send:function(i){e.emit(t,i)},reset:function(){e.removeAllListeners(t)},addListener:function(i){e.addListener(t,i)}}}class Ht{constructor(e){this.appConfig=e||{},this._eventListeners=[]}connect(e){throw new TypeError("BaseSync::connect() - Abstract method.")}disconnect(){this._eventListeners=[]}send(e){}set onReceive(e){"function"==typeof e&&this._eventListeners.push(e)}dispatchReceive(e){for(var t=this._eventListeners.length-1;t>-1;t--)this._eventListeners[t](e)}}class Wt{constructor(e,t){this.type=e,this.data=t}}class jt{static get SYNC_CONNECT(){return"sync-connect"}static get SYNC_MESSAGE(){return"sync-message"}static get SYNC_PRESENCE(){return"sync-presence"}}var qt,Yt,Jt,Qt,$t=_(function(){if(xt)return Lt;xt=1;var e=Ce().docCookies,t="screen_device_id",i="should_verify_screen_device_id",n="screen_device_id_verified_intermediate",r="screen_device_id_verified",s=e.getItem(r),o=e.getItem(t);return Lt={getDeviceId:function(){return o},getDeviceIdFromStorage:function(){return e.getItem(t)},isDeviceIdVerified:function(){return s},isDeviceIdVerifiedFlagStored:function(){return e.getItem(r)},isIntermediateVerifcationCookieSet:function(){return e.getItem(n)},isShouldVerifyDeviceIdFlagSet:function(){return e.getItem(i)},setDeviceId:function(r){s||(o!==r&&this.isIntermediateVerifcationCookieSet()&&e.eraseCookieFromAllPaths(n),o=r,e.setItem(t,o,1/0,"/"),e.setItem(i,"yes",1/0,"/"))},verifyDeviceId:function(){e.getItem(i)&&(e.getItem(r)||(e.getItem(n)?(s="yes",e.setItem(r,s,1/0,"/"),VizbeeSDK.logger.debug("SETTING VERIFIED COOKIE *** ",e.getItem(r))):(e.setItem(n,"yes",1/0,"/"),VizbeeSDK.logger.debug("SETTING INTERMEDIATE COOKIE *** ",e.getItem(n)))),e.eraseCookieFromAllPaths(i))},reset:function(){for(var a=[t,r,i,n],d=0;d<a.length;d++)e.eraseCookieFromAllPaths(a[d]);s=null,o=null}}}()),Zt={exports:{}},Xt={exports:{}};function ei(){return qt||(qt=1,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t={rotl:function(e,t){return e<<t|e>>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&t.rotl(e,8)|4278255360&t.rotl(e,24);for(var i=0;i<e.length;i++)e[i]=t.endian(e[i]);return e},randomBytes:function(e){for(var t=[];e>0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],i=0,n=0;i<e.length;i++,n+=8)t[n>>>5]|=e[i]<<24-n%32;return t},wordsToBytes:function(e){for(var t=[],i=0;i<32*e.length;i+=8)t.push(e[i>>>5]>>>24-i%32&255);return t},bytesToHex:function(e){for(var t=[],i=0;i<e.length;i++)t.push((e[i]>>>4).toString(16)),t.push((15&e[i]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],i=0;i<e.length;i+=2)t.push(parseInt(e.substr(i,2),16));return t},bytesToBase64:function(t){for(var i=[],n=0;n<t.length;n+=3)for(var r=t[n]<<16|t[n+1]<<8|t[n+2],s=0;s<4;s++)8*n+6*s<=8*t.length?i.push(e.charAt(r>>>6*(3-s)&63)):i.push("=");return i.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/gi,"");for(var i=[],n=0,r=0;n<t.length;r=++n%4)0!=r&&i.push((e.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<2*r|e.indexOf(t.charAt(n))>>>6-2*r);return i}},Xt.exports=t),Xt.exports;var e,t}function ti(){if(Jt)return Yt;Jt=1;var e={utf8:{stringToBytes:function(t){return e.bin.stringToBytes(unescape(encodeURIComponent(t)))},bytesToString:function(t){return decodeURIComponent(escape(e.bin.bytesToString(t)))}},bin:{stringToBytes:function(e){for(var t=[],i=0;i<e.length;i++)t.push(255&e.charCodeAt(i));return t},bytesToString:function(e){for(var t=[],i=0;i<e.length;i++)t.push(String.fromCharCode(e[i]));return t.join("")}}};return Yt=e}var ii,ni,ri,si=(Qt||(Qt=1,function(){var e=ei(),t=ti().utf8,i=ti().bin,n=function(r,s){r.constructor==String?r=s&&"binary"===s.encoding?i.stringToBytes(r):t.stringToBytes(r):"undefined"!=typeof Buffer&&"function"==typeof Buffer.isBuffer&&Buffer.isBuffer(r)?r=Array.prototype.slice.call(r,0):Array.isArray(r)||(r=r.toString());for(var o=e.bytesToWords(r),a=8*r.length,d=1732584193,l=-271733879,c=-1732584194,u=271733878,p=0;p<o.length;p++)o[p]=16711935&(o[p]<<8|o[p]>>>24)|4278255360&(o[p]<<24|o[p]>>>8);o[a>>>5]|=128<<a%32,o[14+(a+64>>>9<<4)]=a;var h=n._ff,g=n._gg,f=n._hh,v=n._ii;for(p=0;p<o.length;p+=16){var y=d,m=l,b=c,S=u;d=h(d,l,c,u,o[p+0],7,-680876936),u=h(u,d,l,c,o[p+1],12,-389564586),c=h(c,u,d,l,o[p+2],17,606105819),l=h(l,c,u,d,o[p+3],22,-1044525330),d=h(d,l,c,u,o[p+4],7,-176418897),u=h(u,d,l,c,o[p+5],12,1200080426),c=h(c,u,d,l,o[p+6],17,-1473231341),l=h(l,c,u,d,o[p+7],22,-45705983),d=h(d,l,c,u,o[p+8],7,1770035416),u=h(u,d,l,c,o[p+9],12,-1958414417),c=h(c,u,d,l,o[p+10],17,-42063),l=h(l,c,u,d,o[p+11],22,-1990404162),d=h(d,l,c,u,o[p+12],7,1804603682),u=h(u,d,l,c,o[p+13],12,-40341101),c=h(c,u,d,l,o[p+14],17,-1502002290),d=g(d,l=h(l,c,u,d,o[p+15],22,1236535329),c,u,o[p+1],5,-165796510),u=g(u,d,l,c,o[p+6],9,-1069501632),c=g(c,u,d,l,o[p+11],14,643717713),l=g(l,c,u,d,o[p+0],20,-373897302),d=g(d,l,c,u,o[p+5],5,-701558691),u=g(u,d,l,c,o[p+10],9,38016083),c=g(c,u,d,l,o[p+15],14,-660478335),l=g(l,c,u,d,o[p+4],20,-405537848),d=g(d,l,c,u,o[p+9],5,568446438),u=g(u,d,l,c,o[p+14],9,-1019803690),c=g(c,u,d,l,o[p+3],14,-187363961),l=g(l,c,u,d,o[p+8],20,1163531501),d=g(d,l,c,u,o[p+13],5,-1444681467),u=g(u,d,l,c,o[p+2],9,-51403784),c=g(c,u,d,l,o[p+7],14,1735328473),d=f(d,l=g(l,c,u,d,o[p+12],20,-1926607734),c,u,o[p+5],4,-378558),u=f(u,d,l,c,o[p+8],11,-2022574463),c=f(c,u,d,l,o[p+11],16,1839030562),l=f(l,c,u,d,o[p+14],23,-35309556),d=f(d,l,c,u,o[p+1],4,-1530992060),u=f(u,d,l,c,o[p+4],11,1272893353),c=f(c,u,d,l,o[p+7],16,-155497632),l=f(l,c,u,d,o[p+10],23,-1094730640),d=f(d,l,c,u,o[p+13],4,681279174),u=f(u,d,l,c,o[p+0],11,-358537222),c=f(c,u,d,l,o[p+3],16,-722521979),l=f(l,c,u,d,o[p+6],23,76029189),d=f(d,l,c,u,o[p+9],4,-640364487),u=f(u,d,l,c,o[p+12],11,-421815835),c=f(c,u,d,l,o[p+15],16,530742520),d=v(d,l=f(l,c,u,d,o[p+2],23,-995338651),c,u,o[p+0],6,-198630844),u=v(u,d,l,c,o[p+7],10,1126891415),c=v(c,u,d,l,o[p+14],15,-1416354905),l=v(l,c,u,d,o[p+5],21,-57434055),d=v(d,l,c,u,o[p+12],6,1700485571),u=v(u,d,l,c,o[p+3],10,-1894986606),c=v(c,u,d,l,o[p+10],15,-1051523),l=v(l,c,u,d,o[p+1],21,-2054922799),d=v(d,l,c,u,o[p+8],6,1873313359),u=v(u,d,l,c,o[p+15],10,-30611744),c=v(c,u,d,l,o[p+6],15,-1560198380),l=v(l,c,u,d,o[p+13],21,1309151649),d=v(d,l,c,u,o[p+4],6,-145523070),u=v(u,d,l,c,o[p+11],10,-1120210379),c=v(c,u,d,l,o[p+2],15,718787259),l=v(l,c,u,d,o[p+9],21,-343485551),d=d+y>>>0,l=l+m>>>0,c=c+b>>>0,u=u+S>>>0}return e.endian([d,l,c,u])};n._ff=function(e,t,i,n,r,s,o){var a=e+(t&i|~t&n)+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._gg=function(e,t,i,n,r,s,o){var a=e+(t&n|i&~n)+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._hh=function(e,t,i,n,r,s,o){var a=e+(t^i^n)+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._ii=function(e,t,i,n,r,s,o){var a=e+(i^(t|~n))+(r>>>0)+o;return(a<<s|a>>>32-s)+t},n._blocksize=16,n._digestsize=16,Zt.exports=function(t,r){if(void 0!==t){var s=e.wordsToBytes(n(t,r));return r&&r.asBytes?s:r&&r.asString?i.bytesToString(s):e.bytesToHex(s)}}}()),Zt.exports),oi=_(si),ai={exports:{}},di={exports:{}},li={exports:{}},ci={exports:{}},ui={exports:{}};function pi(){return ni||(ni=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){return ii||(ii=1,e=ui,function(e){var t={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function i(){var e,t,i="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(i+="-"),i+=(12===e?4:16===e?3&t|8:t).toString(16);return i}function n(e,i){var n=t[i||"all"];return n&&n.test(e)||!1}i.isUUID=n,i.VERSION="0.1.0",e.uuid=i,e.isUUID=n}(t=ui.exports),null!==e&&(e.exports=t.uuid)),ui.exports;var e,t}(),r=(i=n)&&i.__esModule?i:{default:i};t.default={createUUID:function(){return r.default.uuid?r.default.uuid():(0,r.default)()}},e.exports=t.default}(ci,ci.exports)),ci.exports}function hi(){return ri||(ri=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),r=(i=pi())&&i.__esModule?i:{default:i},s=function(){function e(t){var i=t.setup,n=t.db;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._db=n,this.instanceId="pn-"+r.default.createUUID(),this.secretKey=i.secretKey||i.secret_key,this.subscribeKey=i.subscribeKey||i.subscribe_key,this.publishKey=i.publishKey||i.publish_key,this.sdkName=i.sdkName,this.sdkFamily=i.sdkFamily,this.partnerId=i.partnerId,this.setAuthKey(i.authKey),this.setCipherKey(i.cipherKey),this.setFilterExpression(i.filterExpression),this.origin=i.origin||"pubsub.pndsn.com",this.secure=i.ssl||!1,this.restore=i.restore||!1,this.proxy=i.proxy,this.keepAlive=i.keepAlive,this.keepAliveSettings=i.keepAliveSettings,this.autoNetworkDetection=i.autoNetworkDetection||!1,this.dedupeOnSubscribe=i.dedupeOnSubscribe||!1,this.maximumCacheSize=i.maximumCacheSize||100,this.customEncrypt=i.customEncrypt,this.customDecrypt=i.customDecrypt,"undefined"!=typeof location&&"https:"===location.protocol&&(this.secure=!0),this.logVerbosity=i.logVerbosity||!1,this.suppressLeaveEvents=i.suppressLeaveEvents||!1,this.announceFailedHeartbeats=i.announceFailedHeartbeats||!0,this.announceSuccessfulHeartbeats=i.announceSuccessfulHeartbeats||!1,this.useInstanceId=i.useInstanceId||!1,this.useRequestId=i.useRequestId||!1,this.requestMessageCountThreshold=i.requestMessageCountThreshold,this.setTransactionTimeout(i.transactionalRequestTimeout||15e3),this.setSubscribeTimeout(i.subscribeRequestTimeout||31e4),this.setSendBeaconConfig(i.useSendBeacon||!0),this.setPresenceTimeout(i.presenceTimeout||300),null!=i.heartbeatInterval&&this.setHeartbeatInterval(i.heartbeatInterval),this.setUUID(this._decideUUID(i.uuid))}return n(e,[{key:"getAuthKey",value:function(){return this.authKey}},{key:"setAuthKey",value:function(e){return this.authKey=e,this}},{key:"setCipherKey",value:function(e){return this.cipherKey=e,this}},{key:"getUUID",value:function(){return this.UUID}},{key:"setUUID",value:function(e){return this._db&&this._db.set&&this._db.set(this.subscribeKey+"uuid",e),this.UUID=e,this}},{key:"getFilterExpression",value:function(){return this.filterExpression}},{key:"setFilterExpression",value:function(e){return this.filterExpression=e,this}},{key:"getPresenceTimeout",value:function(){return this._presenceTimeout}},{key:"setPresenceTimeout",value:function(e){return this._presenceTimeout=e,this.setHeartbeatInterval(this._presenceTimeout/2-1),this}},{key:"setProxy",value:function(e){this.proxy=e}},{key:"getHeartbeatInterval",value:function(){return this._heartbeatInterval}},{key:"setHeartbeatInterval",value:function(e){return this._heartbeatInterval=e,this}},{key:"getSubscribeTimeout",value:function(){return this._subscribeRequestTimeout}},{key:"setSubscribeTimeout",value:function(e){return this._subscribeRequestTimeout=e,this}},{key:"getTransactionTimeout",value:function(){return this._transactionalRequestTimeout}},{key:"setTransactionTimeout",value:function(e){return this._transactionalRequestTimeout=e,this}},{key:"isSendBeaconEnabled",value:function(){return this._useSendBeacon}},{key:"setSendBeaconConfig",value:function(e){return this._useSendBeacon=e,this}},{key:"getVersion",value:function(){return"4.20.3"}},{key:"_decideUUID",value:function(e){return e||(this._db&&this._db.get&&this._db.get(this.subscribeKey+"uuid")?this._db.get(this.subscribeKey+"uuid"):"pn-"+r.default.createUUID())}}]),e}();t.default=s,e.exports=t.default}(li,li.exports)),li.exports}var gi,fi={exports:{}};function vi(){return gi||(gi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();r(hi());var n=r(null);function r(e){return e&&e.__esModule?e:{default:e}}var s=function(){function e(t){var i=t.config;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._config=i,this._iv="0123456789012345",this._allowedKeyEncodings=["hex","utf8","base64","binary"],this._allowedKeyLengths=[128,256],this._allowedModes=["ecb","cbc"],this._defaultOptions={encryptKey:!0,keyEncoding:"utf8",keyLength:256,mode:"cbc"}}return i(e,[{key:"HMACSHA256",value:function(e){return n.default.HmacSHA256(e,this._config.secretKey).toString(n.default.enc.Base64)}},{key:"SHA256",value:function(e){return n.default.SHA256(e).toString(n.default.enc.Hex)}},{key:"_parseOptions",value:function(e){var t=e||{};return t.hasOwnProperty("encryptKey")||(t.encryptKey=this._defaultOptions.encryptKey),t.hasOwnProperty("keyEncoding")||(t.keyEncoding=this._defaultOptions.keyEncoding),t.hasOwnProperty("keyLength")||(t.keyLength=this._defaultOptions.keyLength),t.hasOwnProperty("mode")||(t.mode=this._defaultOptions.mode),-1===this._allowedKeyEncodings.indexOf(t.keyEncoding.toLowerCase())&&(t.keyEncoding=this._defaultOptions.keyEncoding),-1===this._allowedKeyLengths.indexOf(parseInt(t.keyLength,10))&&(t.keyLength=this._defaultOptions.keyLength),-1===this._allowedModes.indexOf(t.mode.toLowerCase())&&(t.mode=this._defaultOptions.mode),t}},{key:"_decodeKey",value:function(e,t){return"base64"===t.keyEncoding?n.default.enc.Base64.parse(e):"hex"===t.keyEncoding?n.default.enc.Hex.parse(e):e}},{key:"_getPaddedKey",value:function(e,t){return e=this._decodeKey(e,t),t.encryptKey?n.default.enc.Utf8.parse(this.SHA256(e).slice(0,32)):e}},{key:"_getMode",value:function(e){return"ecb"===e.mode?n.default.mode.ECB:n.default.mode.CBC}},{key:"_getIV",value:function(e){return"cbc"===e.mode?n.default.enc.Utf8.parse(this._iv):null}},{key:"encrypt",value:function(e,t,i){return this._config.customEncrypt?this._config.customEncrypt(e):this.pnEncrypt(e,t,i)}},{key:"decrypt",value:function(e,t,i){return this._config.customDecrypt?this._config.customDecrypt(e):this.pnDecrypt(e,t,i)}},{key:"pnEncrypt",value:function(e,t,i){if(!t&&!this._config.cipherKey)return e;i=this._parseOptions(i);var r=this._getIV(i),s=this._getMode(i),o=this._getPaddedKey(t||this._config.cipherKey,i);return n.default.AES.encrypt(e,o,{iv:r,mode:s}).ciphertext.toString(n.default.enc.Base64)||e}},{key:"pnDecrypt",value:function(e,t,i){if(!t&&!this._config.cipherKey)return e;i=this._parseOptions(i);var r=this._getIV(i),s=this._getMode(i),o=this._getPaddedKey(t||this._config.cipherKey,i);try{var a=n.default.enc.Base64.parse(e),d=n.default.AES.decrypt({ciphertext:a},o,{iv:r,mode:s}).toString(n.default.enc.Utf8);return JSON.parse(d)}catch(e){return null}}}]),e}();t.default=s,e.exports=t.default}(fi,fi.exports)),fi.exports}var yi,mi,bi={exports:{}},Si={exports:{}},_i={exports:{}};function Ei(){return yi||(yi=1,e=_i,t=_i.exports,Object.defineProperty(t,"__esModule",{value:!0}),t.default={PNNetworkUpCategory:"PNNetworkUpCategory",PNNetworkDownCategory:"PNNetworkDownCategory",PNNetworkIssuesCategory:"PNNetworkIssuesCategory",PNTimeoutCategory:"PNTimeoutCategory",PNBadRequestCategory:"PNBadRequestCategory",PNAccessDeniedCategory:"PNAccessDeniedCategory",PNUnknownCategory:"PNUnknownCategory",PNReconnectedCategory:"PNReconnectedCategory",PNConnectedCategory:"PNConnectedCategory",PNRequestMessageCountExceededCategory:"PNRequestMessageCountExceededCategory"},e.exports=t.default),_i.exports;var e,t}function Ii(){return mi||(mi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),r=(i=Ei())&&i.__esModule?i:{default:i},s=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._listeners=[]}return n(e,[{key:"addListener",value:function(e){this._listeners.push(e)}},{key:"removeListener",value:function(e){var t=[];this._listeners.forEach(function(i){i!==e&&t.push(i)}),this._listeners=t}},{key:"removeAllListeners",value:function(){this._listeners=[]}},{key:"announcePresence",value:function(e){this._listeners.forEach(function(t){t.presence&&t.presence(e)})}},{key:"announceStatus",value:function(e){this._listeners.forEach(function(t){t.status&&t.status(e)})}},{key:"announceMessage",value:function(e){this._listeners.forEach(function(t){t.message&&t.message(e)})}},{key:"announceNetworkUp",value:function(){var e={};e.category=r.default.PNNetworkUpCategory,this.announceStatus(e)}},{key:"announceNetworkDown",value:function(){var e={};e.category=r.default.PNNetworkDownCategory,this.announceStatus(e)}}]),e}();t.default=s,e.exports=t.default}(Si,Si.exports)),Si.exports}var Ti,Vi,Pi,Ai={exports:{}},Di={},Ci={exports:{}};function ki(){return Ti||(Ti=1,e=Ci,t=Ci.exports,Object.defineProperty(t,"__esModule",{value:!0}),t.default={PNTimeOperation:"PNTimeOperation",PNHistoryOperation:"PNHistoryOperation",PNDeleteMessagesOperation:"PNDeleteMessagesOperation",PNFetchMessagesOperation:"PNFetchMessagesOperation",PNSubscribeOperation:"PNSubscribeOperation",PNUnsubscribeOperation:"PNUnsubscribeOperation",PNPublishOperation:"PNPublishOperation",PNPushNotificationEnabledChannelsOperation:"PNPushNotificationEnabledChannelsOperation",PNRemoveAllPushNotificationsOperation:"PNRemoveAllPushNotificationsOperation",PNWhereNowOperation:"PNWhereNowOperation",PNSetStateOperation:"PNSetStateOperation",PNHereNowOperation:"PNHereNowOperation",PNGetStateOperation:"PNGetStateOperation",PNHeartbeatOperation:"PNHeartbeatOperation",PNChannelGroupsOperation:"PNChannelGroupsOperation",PNRemoveGroupOperation:"PNRemoveGroupOperation",PNChannelsForGroupOperation:"PNChannelsForGroupOperation",PNAddChannelsToGroupOperation:"PNAddChannelsToGroupOperation",PNRemoveChannelsFromGroupOperation:"PNRemoveChannelsFromGroupOperation",PNAccessManagerGrant:"PNAccessManagerGrant",PNAccessManagerAudit:"PNAccessManagerAudit"},e.exports=t.default),Ci.exports;var e,t}function wi(){if(Vi)return Di;Vi=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.getOperation=function(){return t.default.PNTimeOperation},Di.getURL=function(){return"/time/0"},Di.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Di.prepareParams=function(){return{}},Di.isAuthSupported=function(){return!1},Di.handleResponse=function(e,t){return{timetoken:t[0]}},Di.validateParams=function(){};var e,t=(e=ki())&&e.__esModule?e:{default:e};return Di}var Ni,Oi,Ri,Mi,Li={exports:{}};function xi(){if(Ri)return Oi;function e(e){return encodeURIComponent(e).replace(/[!~*'()]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}return Ri=1,Oi={signPamFromParams:function(t){return(i=t,function(e){var t=[];return Object.keys(e).forEach(function(e){return t.push(e)}),t}(i).sort()).map(function(i){return i+"="+e(t[i])}).join("&");var i},endsWith:function(e,t){return-1!==e.indexOf(t,this.length-t.length)},createPromise:function(){var e=void 0,t=void 0;return{promise:new Promise(function(i,n){e=i,t=n}),reject:t,fulfill:e}},encodeString:e}}function zi(){return Mi||(Mi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();a(vi()),a(hi()),a(Ii());var n=a((Pi||(Pi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();!(i=wi())||i.__esModule;var r=function(){function e(t){var i=t.timeEndpoint;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._timeEndpoint=i}return n(e,[{key:"onReconnection",value:function(e){this._reconnectionCallback=e}},{key:"startPolling",value:function(){this._timeTimer=setInterval(this._performTimeLoop.bind(this),3e3)}},{key:"stopPolling",value:function(){clearInterval(this._timeTimer)}},{key:"_performTimeLoop",value:function(){var e=this;this._timeEndpoint(function(t){t.error||(clearInterval(e._timeTimer),e._reconnectionCallback())})}}]),e}();t.default=r,e.exports=t.default}(Ai,Ai.exports)),Ai.exports)),r=a((Ni||(Ni=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();!(i=hi())||i.__esModule;var r=function(){function e(t){var i=t.config;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.hashHistory=[],this._config=i}return n(e,[{key:"getKey",value:function(e){var t=function(e){var t=0;if(0===e.length)return t;for(var i=0;i<e.length;i+=1)t=(t<<5)-t+e.charCodeAt(i),t&=t;return t}(JSON.stringify(e.payload)).toString();return e.publishMetaData.publishTimetoken+"-"+t}},{key:"isDuplicate",value:function(e){return this.hashHistory.includes(this.getKey(e))}},{key:"addEntry",value:function(e){this.hashHistory.length>=this._config.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}},{key:"clearHistory",value:function(){this.hashHistory=[]}}]),e}();t.default=r,e.exports=t.default}(Li,Li.exports)),Li.exports)),s=a(xi()),o=a(Ei());function a(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(t){var i=t.subscribeEndpoint,s=t.leaveEndpoint,o=t.heartbeatEndpoint,a=t.setStateEndpoint,d=t.timeEndpoint,l=t.config,c=t.crypto,u=t.listenerManager;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._listenerManager=u,this._config=l,this._leaveEndpoint=s,this._heartbeatEndpoint=o,this._setStateEndpoint=a,this._subscribeEndpoint=i,this._crypto=c,this._channels={},this._presenceChannels={},this._heartbeatChannels={},this._heartbeatChannelGroups={},this._channelGroups={},this._presenceChannelGroups={},this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[],this._currentTimetoken=0,this._lastTimetoken=0,this._storedTimetoken=null,this._subscriptionStatusAnnounced=!1,this._isOnline=!0,this._reconnectionManager=new n.default({timeEndpoint:d}),this._dedupingManager=new r.default({config:l})}return i(e,[{key:"adaptStateChange",value:function(e,t){var i=this,n=e.state,r=e.channels,s=void 0===r?[]:r,o=e.channelGroups,a=void 0===o?[]:o;return s.forEach(function(e){e in i._channels&&(i._channels[e].state=n)}),a.forEach(function(e){e in i._channelGroups&&(i._channelGroups[e].state=n)}),this._setStateEndpoint({state:n,channels:s,channelGroups:a},t)}},{key:"adaptPresenceChange",value:function(e){var t=this,i=e.connected,n=e.channels,r=void 0===n?[]:n,s=e.channelGroups,o=void 0===s?[]:s;i?(r.forEach(function(e){t._heartbeatChannels[e]={state:{}}}),o.forEach(function(e){t._heartbeatChannelGroups[e]={state:{}}})):(r.forEach(function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]}),o.forEach(function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]}),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:r,channelGroups:o},function(e){t._listenerManager.announceStatus(e)})),this.reconnect()}},{key:"adaptSubscribeChange",value:function(e){var t=this,i=e.timetoken,n=e.channels,r=void 0===n?[]:n,s=e.channelGroups,o=void 0===s?[]:s,a=e.withPresence,d=void 0!==a&&a;this._config.subscribeKey&&""!==this._config.subscribeKey?(i&&(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=i),"0"!==this._currentTimetoken&&0!==this._currentTimetoken&&(this._storedTimetoken=this._currentTimetoken,this._currentTimetoken=0),r.forEach(function(e){t._channels[e]={state:{}},d&&(t._presenceChannels[e]={}),t._pendingChannelSubscriptions.push(e)}),o.forEach(function(e){t._channelGroups[e]={state:{}},d&&(t._presenceChannelGroups[e]={}),t._pendingChannelGroupSubscriptions.push(e)}),this._subscriptionStatusAnnounced=!1,this.reconnect()):console&&console.log}},{key:"adaptUnsubscribeChange",value:function(e,t){var i=this,n=e.channels,r=void 0===n?[]:n,s=e.channelGroups,o=void 0===s?[]:s,a=[],d=[];r.forEach(function(e){e in i._channels&&(delete i._channels[e],a.push(e)),e in i._presenceChannels&&(delete i._presenceChannels[e],a.push(e))}),o.forEach(function(e){e in i._channelGroups&&(delete i._channelGroups[e],d.push(e)),e in i._presenceChannelGroups&&(delete i._channelGroups[e],d.push(e))}),0===a.length&&0===d.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:a,channelGroups:d},function(e){e.affectedChannels=a,e.affectedChannelGroups=d,e.currentTimetoken=i._currentTimetoken,e.lastTimetoken=i._lastTimetoken,i._listenerManager.announceStatus(e)}),0===Object.keys(this._channels).length&&0===Object.keys(this._presenceChannels).length&&0===Object.keys(this._channelGroups).length&&0===Object.keys(this._presenceChannelGroups).length&&(this._lastTimetoken=0,this._currentTimetoken=0,this._storedTimetoken=null,this._region=null,this._reconnectionManager.stopPolling()),this.reconnect())}},{key:"unsubscribeAll",value:function(e){this.adaptUnsubscribeChange({channels:this.getSubscribedChannels(),channelGroups:this.getSubscribedChannelGroups()},e)}},{key:"getHeartbeatChannels",value:function(){return Object.keys(this._heartbeatChannels)}},{key:"getHeartbeatChannelGroups",value:function(){return Object.keys(this._heartbeatChannelGroups)}},{key:"getSubscribedChannels",value:function(){return Object.keys(this._channels)}},{key:"getSubscribedChannelGroups",value:function(){return Object.keys(this._channelGroups)}},{key:"reconnect",value:function(){this._startSubscribeLoop(),this._registerHeartbeatTimer()}},{key:"disconnect",value:function(){this._stopSubscribeLoop(),this._stopHeartbeatTimer(),this._reconnectionManager.stopPolling()}},{key:"_registerHeartbeatTimer",value:function(){this._stopHeartbeatTimer(),0!==this._config.getHeartbeatInterval()&&(this._performHeartbeatLoop(),this._heartbeatTimer=setInterval(this._performHeartbeatLoop.bind(this),1e3*this._config.getHeartbeatInterval()))}},{key:"_stopHeartbeatTimer",value:function(){this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null)}},{key:"_performHeartbeatLoop",value:function(){var e=this,t=[];t=(t=t.concat(this.getHeartbeatChannels())).concat(this.getSubscribedChannels());var i=[];i=(i=i.concat(this.getHeartbeatChannelGroups())).concat(this.getSubscribedChannelGroups());var n={};0===t.length&&0===i.length||(this.getSubscribedChannels().forEach(function(t){var i=e._channels[t].state;Object.keys(i).length&&(n[t]=i)}),this.getSubscribedChannelGroups().forEach(function(t){var i=e._channelGroups[t].state;Object.keys(i).length&&(n[t]=i)}),this._heartbeatEndpoint({channels:t,channelGroups:i,state:n},function(t){t.error&&e._config.announceFailedHeartbeats&&e._listenerManager.announceStatus(t),t.error&&e._config.autoNetworkDetection&&e._isOnline&&(e._isOnline=!1,e.disconnect(),e._listenerManager.announceNetworkDown(),e.reconnect()),!t.error&&e._config.announceSuccessfulHeartbeats&&e._listenerManager.announceStatus(t)}.bind(this)))}},{key:"_startSubscribeLoop",value:function(){this._stopSubscribeLoop();var e=[],t=[];if(Object.keys(this._channels).forEach(function(t){return e.push(t)}),Object.keys(this._presenceChannels).forEach(function(t){return e.push(t+"-pnpres")}),Object.keys(this._channelGroups).forEach(function(e){return t.push(e)}),Object.keys(this._presenceChannelGroups).forEach(function(e){return t.push(e+"-pnpres")}),0!==e.length||0!==t.length){var i={channels:e,channelGroups:t,timetoken:this._currentTimetoken,filterExpression:this._config.filterExpression,region:this._region};this._subscribeCall=this._subscribeEndpoint(i,this._processSubscribeResponse.bind(this))}}},{key:"_processSubscribeResponse",value:function(e,t){var i=this;if(e.error)e.category===o.default.PNTimeoutCategory?this._startSubscribeLoop():e.category===o.default.PNNetworkIssuesCategory?(this.disconnect(),e.error&&this._config.autoNetworkDetection&&this._isOnline&&(this._isOnline=!1,this._listenerManager.announceNetworkDown()),this._reconnectionManager.onReconnection(function(){i._config.autoNetworkDetection&&!i._isOnline&&(i._isOnline=!0,i._listenerManager.announceNetworkUp()),i.reconnect(),i._subscriptionStatusAnnounced=!0;var t={category:o.default.PNReconnectedCategory,operation:e.operation,lastTimetoken:i._lastTimetoken,currentTimetoken:i._currentTimetoken};i._listenerManager.announceStatus(t)}),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===o.default.PNBadRequestCategory?(this._stopHeartbeatTimer(),this._listenerManager.announceStatus(e)):this._listenerManager.announceStatus(e);else{if(this._storedTimetoken?(this._currentTimetoken=this._storedTimetoken,this._storedTimetoken=null):(this._lastTimetoken=this._currentTimetoken,this._currentTimetoken=t.metadata.timetoken),!this._subscriptionStatusAnnounced){var n={};n.category=o.default.PNConnectedCategory,n.operation=e.operation,n.affectedChannels=this._pendingChannelSubscriptions,n.subscribedChannels=this.getSubscribedChannels(),n.affectedChannelGroups=this._pendingChannelGroupSubscriptions,n.lastTimetoken=this._lastTimetoken,n.currentTimetoken=this._currentTimetoken,this._subscriptionStatusAnnounced=!0,this._listenerManager.announceStatus(n),this._pendingChannelSubscriptions=[],this._pendingChannelGroupSubscriptions=[]}var r=t.messages||[],a=this._config,d=a.requestMessageCountThreshold,l=a.dedupeOnSubscribe;if(d&&r.length>=d){var c={};c.category=o.default.PNRequestMessageCountExceededCategory,c.operation=e.operation,this._listenerManager.announceStatus(c)}r.forEach(function(e){var t=e.channel,n=e.subscriptionMatch,r=e.publishMetaData;if(t===n&&(n=null),l){if(i._dedupingManager.isDuplicate(e))return;i._dedupingManager.addEntry(e)}if(s.default.endsWith(e.channel,"-pnpres")){var o={channel:null,subscription:null};o.actualChannel=null!=n?t:null,o.subscribedChannel=null!=n?n:t,t&&(o.channel=t.substring(0,t.lastIndexOf("-pnpres"))),n&&(o.subscription=n.substring(0,n.lastIndexOf("-pnpres"))),o.action=e.payload.action,o.state=e.payload.data,o.timetoken=r.publishTimetoken,o.occupancy=e.payload.occupancy,o.uuid=e.payload.uuid,o.timestamp=e.payload.timestamp,e.payload.join&&(o.join=e.payload.join),e.payload.leave&&(o.leave=e.payload.leave),e.payload.timeout&&(o.timeout=e.payload.timeout),i._listenerManager.announcePresence(o)}else{var a={channel:null,subscription:null};a.actualChannel=null!=n?t:null,a.subscribedChannel=null!=n?n:t,a.channel=t,a.subscription=n,a.timetoken=r.publishTimetoken,a.publisher=e.issuingClientId,e.userMetadata&&(a.userMetadata=e.userMetadata),i._config.cipherKey?a.message=i._crypto.decrypt(e.payload):a.message=e.payload,i._listenerManager.announceMessage(a)}}),this._region=t.metadata.region,this._startSubscribeLoop()}}},{key:"_stopSubscribeLoop",value:function(){this._subscribeCall&&("function"==typeof this._subscribeCall.abort&&this._subscribeCall.abort(),this._subscribeCall=null)}}]),e}();t.default=d,e.exports=t.default}(bi,bi.exports)),bi.exports}var Ki,Ui={exports:{}};var Fi,Bi,Gi,Hi,Wi,ji={},qi={},Yi={},Ji={};function Qi(){return Wi||(Wi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),n=K(hi()),r=K(vi()),s=K(zi()),o=K(Ii()),a=K((Ki||(Ki=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var s=e.networking,d=e.config,l=null,c=null,u={};t.getOperation()===r.default.PNTimeOperation||t.getOperation()===r.default.PNChannelGroupsOperation?l=arguments.length<=2?void 0:arguments[2]:(u=arguments.length<=2?void 0:arguments[2],l=arguments.length<=3?void 0:arguments[3]),"undefined"==typeof Promise||l||(c=n.default.createPromise());var p=t.validateParams(e,u);if(p)return l?l(a(p)):c?(c.reject(new o("Validation failed, check status for details",a(p))),c.promise):void 0;var h=t.prepareParams(e,u),g=function(e,t,i){return e.usePost&&e.usePost(t,i)?e.postURL(t,i):e.getURL(t,i)}(t,e,u),f=void 0,v={url:g,operation:t.getOperation(),timeout:t.getRequestTimeout(e)};h.uuid=d.UUID,h.pnsdk=function(e){if(e.sdkName)return e.sdkName;var t="PubNub-JS-"+e.sdkFamily;return e.partnerId&&(t+="-"+e.partnerId),t+"/"+e.getVersion()}(d),d.useInstanceId&&(h.instanceid=d.instanceId),d.useRequestId&&(h.requestid=i.default.createUUID()),t.isAuthSupported()&&d.getAuthKey()&&(h.auth=d.getAuthKey()),d.secretKey&&function(e,t,i){var r=e.config,s=e.crypto;i.timestamp=Math.floor((new Date).getTime()/1e3);var o=r.subscribeKey+"\n"+r.publishKey+"\n"+t+"\n";o+=n.default.signPamFromParams(i);var a=s.HMACSHA256(o);a=(a=a.replace(/\+/g,"-")).replace(/\//g,"_"),i.signature=a}(e,g,h);var y=function(i,n){if(i.error)l?l(i):c&&c.reject(new o("PubNub call failed, check status for details",i));else{var r=t.handleResponse(e,n,u);l?l(i,r):c&&c.fulfill(r)}};if(t.usePost&&t.usePost(e,u)){var m=t.postPayload(e,u);f=s.POST(h,m,v,y)}else f=t.useDelete&&t.useDelete()?s.DELETE(h,v,y):s.GET(h,v,y);return t.getOperation()===r.default.PNSubscribeOperation?f:c?c.promise:void 0};var i=s(pi()),n=s(xi());s(hi());var r=s(ki());function s(e){return e&&e.__esModule?e:{default:e}}var o=function(){function e(t,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return n.name=n.constructor.name,n.status=i,n.message=t,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(e,Error),e}();function a(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}e.exports=t.default}(Ui,Ui.exports)),Ui.exports)),d=z(null),l=z(null),c=z(null),u=z(null),p=z(null),h=z(null),g=z(null),f=z(null),v=z(null),y=function(){if(Fi)return ji;Fi=1,Object.defineProperty(ji,"__esModule",{value:!0}),ji.getOperation=function(){return e.default.PNUnsubscribeOperation},ji.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},ji.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,o=s.length>0?s.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+t.default.encodeString(o)+"/leave"},ji.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},ji.isAuthSupported=function(){return!0},ji.prepareParams=function(e,t){var i=t.channelGroups,n=void 0===i?[]:i,r={};return n.length>0&&(r["channel-group"]=n.join(",")),r},ji.handleResponse=function(){return{}};var e=i(ki()),t=i(xi());function i(e){return e&&e.__esModule?e:{default:e}}return ji}(),m=z(y),b=z(null),S=function(){if(Bi)return qi;Bi=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.getOperation=function(){return e.default.PNHeartbeatOperation},qi.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},qi.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,o=s.length>0?s.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+t.default.encodeString(o)+"/heartbeat"},qi.isAuthSupported=function(){return!0},qi.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},qi.prepareParams=function(e,t){var i=t.channelGroups,n=void 0===i?[]:i,r=t.state,s=void 0===r?{}:r,o=e.config,a={};return n.length>0&&(a["channel-group"]=n.join(",")),a.state=JSON.stringify(s),a.heartbeat=o.getPresenceTimeout(),a},qi.handleResponse=function(){return{}};var e=i(ki()),t=i(xi());function i(e){return e&&e.__esModule?e:{default:e}}return qi}(),_=z(S),E=z(null),I=z(null),T=z(null),V=z(null),P=z(null),A=function(){if(Gi)return Yi;Gi=1,Object.defineProperty(Yi,"__esModule",{value:!0});var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};Yi.getOperation=function(){return t.default.PNPublishOperation},Yi.validateParams=function(e,t){var i=e.config,n=t.message;return t.channel?n?i.subscribeKey?void 0:"Missing Subscribe Key":"Missing Message":"Missing Channel"},Yi.usePost=function(e,t){var i=t.sendByPost;return void 0!==i&&i},Yi.getURL=function(e,t){var n=e.config,s=t.channel,o=r(e,t.message);return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+i.default.encodeString(s)+"/0/"+i.default.encodeString(o)},Yi.postURL=function(e,t){var n=e.config,r=t.channel;return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+i.default.encodeString(r)+"/0"},Yi.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Yi.isAuthSupported=function(){return!0},Yi.postPayload=function(e,t){return r(e,t.message)},Yi.prepareParams=function(t,i){var n=i.meta,r=i.replicate,s=void 0===r||r,o=i.storeInHistory,a=i.ttl,d={};return null!=o&&(d.store=o?"1":"0"),a&&(d.ttl=a),!1===s&&(d.norep="true"),n&&"object"===(void 0===n?"undefined":e(n))&&(d.meta=JSON.stringify(n)),d},Yi.handleResponse=function(e,t){return{timetoken:t[2]}};var t=n(ki()),i=n(xi());function n(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var i=e.crypto,n=e.config,r=JSON.stringify(t);return n.cipherKey&&(r=i.encrypt(r),r=JSON.stringify(r)),r}return Yi}(),D=z(A),C=z(null),k=z(null),w=z(null),N=z(wi()),O=function(){if(Hi)return Ji;Hi=1,Object.defineProperty(Ji,"__esModule",{value:!0}),Ji.getOperation=function(){return e.default.PNSubscribeOperation},Ji.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Ji.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,o=s.length>0?s.join(","):",";return"/v2/subscribe/"+n.subscribeKey+"/"+t.default.encodeString(o)+"/0"},Ji.getRequestTimeout=function(e){return e.config.getSubscribeTimeout()},Ji.isAuthSupported=function(){return!0},Ji.prepareParams=function(e,t){var i=e.config,n=t.channelGroups,r=void 0===n?[]:n,s=t.timetoken,o=t.filterExpression,a=t.region,d={heartbeat:i.getPresenceTimeout()};return r.length>0&&(d["channel-group"]=r.join(",")),o&&o.length>0&&(d["filter-expr"]=o),s&&(d.tt=s),a&&(d.tr=a),d},Ji.handleResponse=function(e,t){var i=[];t.m.forEach(function(e){var t={publishTimetoken:e.p.t,region:e.p.r},n={shard:parseInt(e.a,10),subscriptionMatch:e.b,channel:e.c,payload:e.d,flags:e.f,issuingClientId:e.i,subscribeKey:e.k,originationTimetoken:e.o,userMetadata:e.u,publishMetaData:t};i.push(n)});var n={timetoken:t.t.t,region:t.t.r};return{messages:i,metadata:n}};var e=i(ki()),t=i(xi());function i(e){return e&&e.__esModule?e:{default:e}}return Ji}(),R=z(O),M=K(ki()),L=K(Ei()),x=K(pi());function z(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}function K(e){return e&&e.__esModule?e:{default:e}}var U=function(){function e(t){var i=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var y=t.db,S=t.networking,A=this._config=new n.default({setup:t,db:y}),O=new r.default({config:A});S.init(A);var M={config:A,networking:S,crypto:O},L=a.default.bind(this,M,N),x=a.default.bind(this,M,m),z=a.default.bind(this,M,_),K=a.default.bind(this,M,I),U=a.default.bind(this,M,R),F=this._listenerManager=new o.default,B=new s.default({timeEndpoint:L,leaveEndpoint:x,heartbeatEndpoint:z,setStateEndpoint:K,subscribeEndpoint:U,crypto:M.crypto,config:M.config,listenerManager:F});this.addListener=F.addListener.bind(F),this.removeListener=F.removeListener.bind(F),this.removeAllListeners=F.removeAllListeners.bind(F),this.channelGroups={listGroups:a.default.bind(this,M,u),listChannels:a.default.bind(this,M,p),addChannels:a.default.bind(this,M,d),removeChannels:a.default.bind(this,M,l),deleteGroup:a.default.bind(this,M,c)},this.push={addChannels:a.default.bind(this,M,h),removeChannels:a.default.bind(this,M,g),deleteDevice:a.default.bind(this,M,v),listChannels:a.default.bind(this,M,f)},this.hereNow=a.default.bind(this,M,T),this.whereNow=a.default.bind(this,M,b),this.getState=a.default.bind(this,M,E),this.setState=B.adaptStateChange.bind(B),this.grant=a.default.bind(this,M,P),this.audit=a.default.bind(this,M,V),this.publish=a.default.bind(this,M,D),this.fire=function(e,t){return e.replicate=!1,e.storeInHistory=!1,i.publish(e,t)},this.history=a.default.bind(this,M,C),this.deleteMessages=a.default.bind(this,M,k),this.fetchMessages=a.default.bind(this,M,w),this.time=L,this.subscribe=B.adaptSubscribeChange.bind(B),this.presence=B.adaptPresenceChange.bind(B),this.unsubscribe=B.adaptUnsubscribeChange.bind(B),this.disconnect=B.disconnect.bind(B),this.reconnect=B.reconnect.bind(B),this.destroy=function(e){B.unsubscribeAll(e),B.disconnect()},this.stop=this.destroy,this.unsubscribeAll=B.unsubscribeAll.bind(B),this.getSubscribedChannels=B.getSubscribedChannels.bind(B),this.getSubscribedChannelGroups=B.getSubscribedChannelGroups.bind(B),this.encrypt=O.encrypt.bind(O),this.decrypt=O.decrypt.bind(O),this.getAuthKey=M.config.getAuthKey.bind(M.config),this.setAuthKey=M.config.setAuthKey.bind(M.config),this.setCipherKey=M.config.setCipherKey.bind(M.config),this.getUUID=M.config.getUUID.bind(M.config),this.setUUID=M.config.setUUID.bind(M.config),this.getFilterExpression=M.config.getFilterExpression.bind(M.config),this.setFilterExpression=M.config.setFilterExpression.bind(M.config),this.setHeartbeatInterval=M.config.setHeartbeatInterval.bind(M.config),S.hasModule("proxy")&&(this.setProxy=function(e){M.config.setProxy(e),i.reconnect()})}return i(e,[{key:"getVersion",value:function(){return this._config.getVersion()}},{key:"networkDownDetected",value:function(){this._listenerManager.announceNetworkDown(),this._config.restore?this.disconnect():this.destroy(!0)}},{key:"networkUpDetected",value:function(){this._listenerManager.announceNetworkUp(),this.reconnect()}}],[{key:"generateUUID",value:function(){return x.default.createUUID()}}]),e}();U.OPERATIONS=M.default,U.CATEGORIES=L.default,t.default=U,e.exports=t.default}(di,di.exports)),di.exports}var $i,Zi={exports:{}};var Xi,en,tn,nn={exports:{}},rn={},sn=(tn||(tn=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=a(Qi()),n=a(($i||($i=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}();r(hi());var n=r(Ei());function r(e){return e&&e.__esModule?e:{default:e}}var s=function(){function e(t){var i=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._modules={},Object.keys(t).forEach(function(e){i._modules[e]=t[e].bind(i)})}return i(e,[{key:"init",value:function(e){this._config=e,this._maxSubDomain=20,this._currentSubDomain=Math.floor(Math.random()*this._maxSubDomain),this._providedFQDN=(this._config.secure?"https://":"http://")+this._config.origin,this._coreParams={},this.shiftStandardOrigin()}},{key:"nextOrigin",value:function(){return-1===this._providedFQDN.indexOf("pubsub.")?this._providedFQDN:(this._currentSubDomain=this._currentSubDomain+1,this._currentSubDomain>=this._maxSubDomain&&(this._currentSubDomain=1),e=this._currentSubDomain.toString(),this._providedFQDN.replace("pubsub","ps"+e));var e}},{key:"hasModule",value:function(e){return e in this._modules}},{key:"shiftStandardOrigin",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._standardOrigin=this.nextOrigin(e),this._standardOrigin}},{key:"getStandardOrigin",value:function(){return this._standardOrigin}},{key:"POST",value:function(e,t,i,n){return this._modules.post(e,t,i,n)}},{key:"GET",value:function(e,t,i){return this._modules.get(e,t,i)}},{key:"DELETE",value:function(e,t,i){return this._modules.del(e,t,i)}},{key:"_detectErrorCategory",value:function(e){if("ENOTFOUND"===e.code)return n.default.PNNetworkIssuesCategory;if("ECONNREFUSED"===e.code)return n.default.PNNetworkIssuesCategory;if("ECONNRESET"===e.code)return n.default.PNNetworkIssuesCategory;if("EAI_AGAIN"===e.code)return n.default.PNNetworkIssuesCategory;if(0===e.status||e.hasOwnProperty("status")&&void 0===e.status)return n.default.PNNetworkIssuesCategory;if(e.timeout)return n.default.PNTimeoutCategory;if("ETIMEDOUT"===e.code)return n.default.PNNetworkIssuesCategory;if(e.response){if(e.response.badRequest)return n.default.PNBadRequestCategory;if(e.response.forbidden)return n.default.PNAccessDeniedCategory}return n.default.PNUnknownCategory}}]),e}();t.default=s,e.exports=t.default}(Zi,Zi.exports)),Zi.exports)),r=(Xi||(Xi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default={get:function(e){try{return localStorage.getItem(e)}catch(e){return null}},set:function(e,t){try{return localStorage.setItem(e,t)}catch(e){return null}}},e.exports=t.default}(nn,nn.exports)),nn.exports),s=a(r),o=function(){if(en)return rn;function e(e){var t=[];for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];null!=n&&t.push(encodeURIComponent(i)+"="+encodeURIComponent(n))}return t.join("&")}function t(e,t,i,n,r,s){var o=this,a=new XMLHttpRequest,d=t+(i?(t.indexOf("?")>=0?"&":"?")+i:""),l=!1,c=!1;function u(e,t){if(!c&&!l){c=!0;var i={};return i.error=null!==e,i.operation=r.operation,a.status&&(i.statusCode=a.status),e?(i.errorData=e,i.category=o._detectErrorCategory(e),s(i,null)):s(i,t)}}a.open(e,d,!0),a.timeout=r.timeout,a.onreadystatechange=function(){if(4===a.readyState){var e=a.status;if(e>=200&&e<300){var t;try{t=JSON.parse(a.responseText)}catch(t){return u({status:e,response:{}},null)}return t&&1===t.error&&t.status&&t.message&&t.service?u({status:t.status,response:{}},null):u(null,t)}return u(0===e?{status:0}:{status:e,response:{badRequest:400===e,forbidden:403===e}},null)}},a.ontimeout=function(){u({timeout:!0},null)},a.onerror=function(){u({status:0},null)};var p=null;null!=n&&(p="string"==typeof n?n:JSON.stringify(n),a.setRequestHeader("Content-Type","application/json"));try{a.send(p)}catch(e){u({status:0},null)}return{abort:function(){l=!0;try{a.abort()}catch(e){}}}}return en=1,Object.defineProperty(rn,"__esModule",{value:!0}),rn.get=function(i,n,r){return t.call(this,"GET",this.getStandardOrigin()+n.url,e(i),null,n,r)},rn.post=function(i,n,r,s){return t.call(this,"POST",this.getStandardOrigin()+r.url,e(i),n,r,s)},rn.del=function(i,n,r){return t.call(this,"DELETE",this.getStandardOrigin()+n.url,e(i),null,n,r)},rn}();function a(e){return e&&e.__esModule?e:{default:e}}function d(e){if(!navigator||!navigator.sendBeacon)return!1;navigator.sendBeacon(e)}var l=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var i=e.listenToBrowserNetworkEvents,r=void 0===i||i;e.db=s.default,e.sdkFamily="Web",e.networking=new n.default({del:o.del,get:o.get,post:o.post,sendBeacon:d});var a=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r&&(window.addEventListener("offline",function(){a.networkDownDetected()}),window.addEventListener("online",function(){a.networkUpDetected()})),a}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t}(i.default);t.default=l,e.exports=t.default}(ai,ai.exports)),ai.exports),on=_(sn);const an=["PNAccessDeniedCategory","PNTimeoutCategory","PNNetworkIssuesCategory","PNBadRequestCategory","PNMalformedResponseCategory","PNDecryptionErrorCategory","PNTLSConnectionFailedCategory","PNTLSUntrustedCertificateCategory","PNUnexpectedDisconnectCategory","PNNetworkDownCategory","PNNetworkUpCategory"];class dn extends Ht{constructor(e){super(e),this.pubnub=void 0,this.channelId=void 0,this._synchronousPublish=!1,this.generateChannel()}connect(e){VizbeeSDK.logger.debug("PubnubSync::appId - "+this.appConfig.appId+" , deviceId - "+this.appConfig.deviceId),void 0===this.pubnub&&(VizbeeSDK.logger.debug("PubnubSync::connect - initializing pubnub ..."),this.pubnub=new on({publishKey:this.appConfig.pub_key,subscribeKey:this.appConfig.sub_key,ssl:!0}),this.filterOwnMessages());let t=5;this.pubnub.addListener({status:i=>{"PNConnectedCategory"!==i.category&&"PNReconnectedCategory"!==i.category&&"PNNetworkUpCategory"!==i.category||(t=5),"PNConnectedCategory"===i.category?(this.dispatchReceive(new Wt(jt.SYNC_CONNECT,{})),e(!0)):an.indexOf(i.category)>=0&&(VizbeeSDK.logger.error("PubnubSync.Connect - PUBNUB.subscribe() error = ",i," with retries = ",t),t>0&&(t--,this.subscribePubnub()))},message:this.messageHandler.bind(this),presence:e=>{}}),this.subscribePubnub()}disconnect(){this.pubnub&&this.channelId&&(VizbeeSDK.logger.debug("PubnubSync::disconnect - invoking disconnect"),this.pubnub.unsubscribe({channels:[this.channelId]}),this.pubnub=void 0,super.disconnect())}send(e){if(this.pubnub&&this.channelId){if(this._synchronousPublish)return void this.sendSynchronously(e);this.pubnub.publish({message:e,channel:this.channelId,sendByPost:!1,storeInHistory:!1,meta:{uuid:this.pubnub.getUUID()}},(e,t)=>{e.error&&VizbeeSDK.logger.error("CommManager:CommManager - PUBNUB.publish() error")})}}enableSynchronousPublish(){this._synchronousPublish=!0}sendSynchronously(e){if(this.pubnub&&this.channelId)try{var t=this.appConfig.pub_key,i=this.appConfig.sub_key,n=this.pubnub.getUUID(),r="?uuid="+encodeURIComponent(n)+"&store=0&meta="+encodeURIComponent(JSON.stringify({uuid:n})),s="https://ps.pndsn.com/publish/"+t+"/"+i+"/0/"+this.channelId+"/0",o=JSON.stringify(e),a=s+"/"+encodeURIComponent(o)+r;if("function"==typeof fetch)return fetch(a,{method:"GET",keepalive:!0,mode:"no-cors"}).catch(function(){}),void VizbeeSDK.logger.debug("PubnubSync::sendSynchronously - sent via keepalive fetch");if("undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(s+r,o))return void VizbeeSDK.logger.debug("PubnubSync::sendSynchronously - sent via sendBeacon");var d=new XMLHttpRequest;d.open("GET",a,!1),d.send(),VizbeeSDK.logger.debug("PubnubSync::sendSynchronously - sent via synchronous XHR")}catch(e){VizbeeSDK.logger.error("PubnubSync::sendSynchronously - error publishing on teardown",e)}}generateChannel(){this.appConfig&&(this.channelId=(""+oi(this.appConfig.appId+":"+this.appConfig.deviceId)).toLowerCase()),VizbeeSDK.logger.info("PubnubSync::generateChannel",this.channelId)}subscribePubnub(){VizbeeSDK.logger.debug("PubnubSync::subscribePubnub - invoking pubnub subscribe"),this.pubnub&&this.channelId&&(VizbeeSDK.logger.debug("PubnubSync::subscribePubnub - subscribing..."),this.pubnub.subscribe({channels:[this.channelId]}))}filterOwnMessages(){if(this.pubnub){let e="uuid != '";e=e.concat(this.pubnub.getUUID()).concat("'"),this.pubnub.setFilterExpression(e)}}messageHandler(e,t,i){VizbeeSDK.logger.verbose("PubnubSync::messageHandler",e);let n=e?e.message:{};$t.verifyDeviceId(),this.dispatchReceive(new Wt(jt.SYNC_MESSAGE,n))}}class ln extends Ht{constructor(e){super(e),this.syncInstances=[]}connect(e){for(let t of this.syncInstances)t.connect(e)}disconnect(){for(let e of this.syncInstances)e.disconnect()}send(e){for(let t of this.syncInstances)t.send(e)}addSyncInstance(e){this.syncInstances.push(e),this.setReceiveListener(e)}setReceiveListener(e){e.onReceive=e=>{this.dispatchReceive.call(this,e)}}}class cn extends Ht{constructor(e,t){if(!(e instanceof Ht))throw new TypeError("BaseSyncExtension::constructor() - classToExtend must be instance of BaseSync.");super(t),this.extendedClass=e,this.extendedClass.onReceive=e=>{this.onReceiveHandler.call(this,e)}}connect(e){this.extendedClass.connect(e)}disconnect(){this.extendedClass.disconnect()}send(e){VizbeeSDK.logger.verbose(this._getLogPrefix("send")+" - FORWARDING OUT send message",e),this.extendedClass.send(e)}get baseSync(){return this.extendedClass instanceof cn?this.extendedClass.baseSync:this.extendedClass}onReceiveHandler(e){if(!e||!e.data)return void VizbeeSDK.logger.warn(this._getLogPrefix("onReceive")+" - NULL receive event",e);let t;e.type===jt.SYNC_MESSAGE?(t=this.handleSyncReceiveEvent(e),t?(VizbeeSDK.logger.verbose(this._getLogPrefix("onReceive")+" - FORWARDING IN sync receive event",t),this.dispatchReceive.call(this,t)):VizbeeSDK.logger.warn(this._getLogPrefix("onReceive")+" - DROPPING receive event",e)):(t=this.handleNonSyncReceiveEvent(e),t?(VizbeeSDK.logger.verbose(this._getLogPrefix("onReceive")+" - FORWARDING IN non-sync receive event",t),this.dispatchReceive.call(this,t)):VizbeeSDK.logger.warn(this._getLogPrefix("onReceive")+" - DROPPING non-sync receive event",e))}handleSyncReceiveEvent(e){return e}handleNonSyncReceiveEvent(e){return e}getClassName(){return this.constructor.name}_getLogPrefix(e){return(this.getClassName()+"::"+e+" ").slice(0,40)}}class un extends cn{constructor(e,t){super(e,t),this.txIdMap={}}handleSyncReceiveEvent(e){if(this.isValidMessage(e.data))return e}isValidMessage(e){let t,i,n,r,s=!1;if(!e)return VizbeeSDK.logger.warn("SanitizeHeaderRecvExtension:isValidMessage - invalid message",e),s;if(!I.isObject(e.h))return VizbeeSDK.logger.warn("SanitizeHeaderRecvExtension:isValidMessage - invalid message head",e),s;if(t=e.h.id,i=e.h.tx,n=e.h.ss,!I.isString(t))return VizbeeSDK.logger.error("SanitizeHeaderRecvExtension:isValidMessage - invalid message id",t,e),s;if(!I.isNumber(i))return VizbeeSDK.logger.error("SanitizeHeaderRecvExtension:isValidMessage - invalid message tx",i,e),s;if(r=t,n&&(r=n+r),0===i)this.txIdMap[r]=i;else{if(this.txIdMap[r]>=i)return VizbeeSDK.logger.warn("SanitizeHeaderRecvExtension:isValidMessage - duplicate message",i,this.txIdMap[r]),s;this.txIdMap[r]=i}return!0}}class pn extends cn{constructor(e,t){super(e,t)}handleSyncReceiveEvent(e){if(this.isValidMessage(e.data))return this.sanitize(e)}isValidMessage(e){let t=!1,i=e.b;if(!I.isObject(i))return t;if(!I.isObject(i.cmd))return t;if(!I.isString(i.cmd.name)||!I.isString(i.cmd.ns))return t;if("start_video"==i.cmd.name){let e=i.vinfo;if(!I.isObject(e))return t;if(!I.isString(e.id)&&!I.isString(e.url))return t}return t=!0,t}sanitize(e){let t=e.data,i=t.b.cmd;return i.name=i.name.toLowerCase(),i.ns=i.ns.toLowerCase(),i.type=i.type?i.type.toLowerCase():null,"exit"==i.name&&(i.param=i.param.toLowerCase()),t.b.cmd=i,e.data=t,e}}class hn extends cn{constructor(e,t){super(e,t)}getActiveSenders(){throw new TypeError("BaseSyncWithPresence::getSenders() - Abstract method.")}getActiveSendersCount(){throw new TypeError("BaseSyncWithPresence::getActiveSendersCount() - Abstract method.")}}class gn extends hn{constructor(e,t){if(!(e instanceof hn))throw new TypeError("BaseSyncWithPresenceExtension::constructor() - classToExtend must be instance of BaseSyncWithPresence.");super(e,t)}getActiveSenders(){return this.extendedClass.getActiveSenders()}getActiveSendersCount(){return this.extendedClass.getActiveSendersCount()}}class fn{static decodeVideoInfo(e){if(!e)return;if(!e.vinfo)return;let t={islive:!1,starttime:0,isContinuedVideo:!1};if(t.id=e.vinfo.id,t.videourl=e.vinfo.url,e.vinfo.islive&&(t.islive=e.vinfo.islive),e.vinfo.deeplink&&(t.deeplink=e.vinfo.deeplink),!I.isUndefined(e.cmd)){var i=0;I.isUndefined(e.cmd.param)||(i=parseInt(e.cmd.param,10),isNaN(i)&&(i=0),i<0&&(i=0)),t.starttime=i}if(e.vinfoext){if(e.vinfoext.cuepoints&&(t.cuepoints=e.vinfoext.cuepoints),e.vinfoext.title&&(t.title=e.vinfoext.title),e.vinfoext.subtitle&&(t.subtitle=e.vinfoext.subtitle),e.vinfoext.tracks){let i=I.get(e,["vinfoext","tracks","currentAudioTrack"]);i&&(t.preferredTracks={},t.preferredTracks.currentAudioTrack={label:i.displayName,lang:i.languageCode,id:i.screenTrackId})}e.vinfoext.imgurl&&(t.imgurl=e.vinfoext.imgurl),e.vinfoext.desc&&(t.desc=e.vinfoext.desc),e.vinfoext.customstreaminfo&&(t.customstreaminfo=e.vinfoext.customstreaminfo),e.vinfoext.custommetadata&&(t.custommetadata=e.vinfoext.custommetadata),e.vinfoext.drmtype&&(t.drmtype=e.vinfoext.drmtype),e.vinfoext.protocoltype&&(t.protocoltype=e.vinfoext.protocoltype),e.vinfoext.drmlicenseurl&&(t.drmlicenseurl=e.vinfoext.drmlicenseurl),e.vinfoext.drmcustomdata&&(t.drmcustomdata=e.vinfoext.drmcustomdata)}return t}static encodeVideoInfo(e){if(!e)return;let t={};return t.vinfo={id:e.id,islive:e.islive,url:e.videourl},t.vinfoext={videostarttime:e.starttime||0,imgurl:e.imgurl?e.imgurl:"",title:e.title?e.title:"",subtitle:e.subtitle?e.subtitle:"",desc:e.desc?e.desc:"",isContinuedVideo:null!=e.isContinuedVideo&&e.isContinuedVideo,customstreaminfo:e.customstreaminfo?e.customstreaminfo:{},custommetadata:e.custommetadata?e.custommetadata:{},drmtype:e.drmtype?e.drmtype:"NONE",drmlicenseurl:e.drmlicenseurl?e.drmlicenseurl:"",drmcustomdata:e.drmcustomdata?e.drmcustomdata:{},cuepoints:e.cuepoints?e.cuepoints:[]},t}static addInfoFromHeader(e,t){if(!e||!t)return e;let i=I.clone(t);return e.senderInfo=I.omit(i,["tx","ss"]),e}static encodeEventCmd(e){if(!e)return;let t={cmd:{ns:"video",type:"req",name:"event",param:""},einfo:{type:e.type,data:e.data}};return{type:jt.SYNC_MESSAGE,data:{h:{},b:t}}}static encodeStartVideoCmd(e){if(!e)return;e.starttime=e.starttime||0;let t={cmd:{ns:"video",type:"req",name:"start_video",param:e.starttime},internal:{videoInfo:e,startVideoSource:"queue_manager"}};return{type:jt.SYNC_MESSAGE,data:{h:{},b:t}}}static encodeVideoStatus(e){if(!e)return;let t={cmd:{name:"status",ns:"video",type:"upd"},vstatus:{du:0,id:e.id,po:-1,st:"BUFFERING",vol:100,cc:0,tr:{},er:{}}};return t=I.extend(t,fn.encodeVideoInfo(e)),t}}class vn extends gn{constructor(e,t){super(e,t)}handleSyncReceiveEvent(e){if("start_video"==e.data.b.cmd.name){let t=fn.decodeVideoInfo(e.data.b);t&&(t=fn.addInfoFromHeader(t,e.data.h)),e.data.b.internal={videoInfo:t,startVideoSource:"default",queueInfo:this._createQueueInfo(e.data)}}return e}_createQueueInfo(e){let t={id:"default",name:"default",description:"default",startIndex:0,items:[]},i=fn.decodeVideoInfo(e.b);return i&&(i=fn.addInfoFromHeader(i,e.h)),t.items.push(i),t}}class yn extends hn{constructor(e,t){VizbeeSDK.logger.d("UpdatePresenceRecvExtension","constructor"),super(e,t),this.currentAppId=t.appId,this._sentFirstHelloCheck=!1,this._sentSecondHelloCheck=!1,this._senderMap={},this._presenceIntervalTimer=void 0,this._previousSenderMapCount=0,this._startPresenceTimer()}getActiveSenders(){return this._senderMap}getActiveSendersCount(){return Object.keys(this._senderMap||{}).length}disconnect(){VizbeeSDK.logger.d("UpdatePresenceRecvExtension","disconnect"),this._senderMap={},this._previousSenderMapCount=0,this._stopPresenceTimer(),super.disconnect()}handleSyncReceiveEvent(e){let t=e.data;return"exit"===t.b.cmd.name?this._senderMap=I.omit(this._senderMap,I.keys(this._senderMap).filter(e=>e===t.h.id)):(this._sentFirstHelloCheck=!1,this._sentSecondHelloCheck=!1,this._senderMap[t.h.id]=t.h,this._senderMap[t.h.id].appId=this.currentAppId,this._senderMap[t.h.id].lastMsgReceivedTimeInMs=Date.now(),this._startPresenceTimer()),e}_startPresenceTimer(){this._stopPresenceTimer(),this._presenceIntervalTimer=window.setInterval(()=>{this._updatePresence()},1e3)}_stopPresenceTimer(){window.clearInterval(this._presenceIntervalTimer),this._presenceIntervalTimer=void 0}_checkForSenders(){!this._sentFirstHelloCheck&&this._shouldSendHelloCheckMessage(15e3)?(this._sendHelloCheckMessage(),this._sentFirstHelloCheck=!0):!this._sentSecondHelloCheck&&this._shouldSendHelloCheckMessage(25e3)&&(this._sendHelloCheckMessage(),this._sentSecondHelloCheck=!0)}_shouldSendHelloCheckMessage(e){if(0==Object.keys(this._senderMap||{}).length)return!1;let t=Date.now(),i=I.keys(this._senderMap).filter(i=>this._senderMap[i]&&null!=this._senderMap[i].lastMsgReceivedTimeInMs&&t-this._senderMap[i].lastMsgReceivedTimeInMs>e);return Object.keys(i).length>0}_sendHelloCheckMessage(){this.dispatchReceive(new Wt(jt.SYNC_MESSAGE,{b:{cmd:{ns:"video",name:"hello",type:"int"},hstatus:{id:this.appConfig.deviceId,type:"SCREEN",vip:"false"}}}))}_updatePresence(){this._checkForSenders();let e=Date.now();if(this._senderMap=I.omit(this._senderMap,I.keys(this._senderMap).filter(t=>this._senderMap[t]&&null!=this._senderMap[t].lastMsgReceivedTimeInMs&&e-this._senderMap[t].lastMsgReceivedTimeInMs>3e4)),0==Object.keys(this._senderMap||{}).length)return VizbeeSDK.logger.d("UpdatePresenceRecvExtension","_updatePresence","there are no senders now"),this._stopPresenceTimer(),this.dispatchReceive(new Wt(jt.SYNC_PRESENCE,this._senderMap)),void(this._previousSenderMapCount=0);let t=Object.keys(this._senderMap).length;t!=this._previousSenderMapCount&&(VizbeeSDK.logger.d("UpdatePresenceRecvExtension","_updatePresence","there is a change in the senders connected"),this._previousSenderMapCount=t,this.dispatchReceive(new Wt(jt.SYNC_PRESENCE,this._senderMap)))}}class mn extends gn{constructor(e,t){super(e,t),this.tx=0,this.sessionId=this.createTimestamp()}send(e){super.send(this.createMessage(null,e))}createMessage(e,t){return(t=t||{}).vers=1,{h:e=I.extend(this.createHeader(),e),b:t}}createHeader(){return this.tx++,{tx:this.tx,id:this.appConfig.senderId||this.appConfig.deviceId,ss:this.sessionId,app:this.appConfig.appId,ssinfo:this.getSenderSessionInfo()}}createTimestamp(){let e=new Date;return e.getFullYear()+":"+("0"+(e.getMonth()+1)).slice(-2)+":"+("0"+e.getDate()).slice(-2)+":"+("0"+e.getHours()).slice(-2)+":"+("0"+e.getMinutes()).slice(-2)+":"+("0"+e.getSeconds()).slice(-2)+":"+("0"+e.getMilliseconds()).slice(-3)}getSenderSessionInfo(){return{SCREEN_IDFA:this.appConfig.screenIdfa,SCREEN_IDFV:this.appConfig.screenIdfv,SCREEN_DEVICE_TYPE:this.appConfig.screenDeviceType,SCREEN_DEVICE_ID:this.appConfig.screenDeviceId,SCREEN_DEVICE_FRIENDLYNAME:this.appConfig.screenFriendlyName}}}const bn=["BUFFERING","PLAYING","PAUSED_BY_USER","INTERRUPTED","FINISHED","FAILED"];class Sn extends gn{constructor(e,t){super(e,t),this.appConfig=t,this.shouldSupportLiveDVR=I.get(t,["features","shouldSupportLiveDVR"],!1),this.liveDVRMinBufferInMs=I.get(t,["features","liveDVRMinBufferInMs"],3e5)}send(e){if(!e||!e.cmd)return void super.send(e);let t=e;"status"==e.cmd.name&&(t=this.interceptVideoStatus(e)),super.send(t)}interceptVideoStatus(e){return bn.includes(e.vstatus.st)&&e.vinfo.islive&&(e.vinfoext||(e.vinfoext={}),!0===e.vinfoext.isdvrsupported||(!this.shouldSupportLiveDVR||e.vstatus.du<this.liveDVRMinBufferInMs?(e.vinfoext.isdvrsupported=!1,e.vstatus.po=-1,e.vstatus.du=0):e.vinfoext.isdvrsupported=!0)),e}}class _n{constructor(e){this.senderConfig=e}track(e,t){if(!e||!t||!this.senderConfig.url)return;if(VizbeeSDK.logger.d(`${this.constructor.name}`,`track() - tracking event ${e}, ${JSON.stringify(t)}`),!this.shouldTrack(e))return;if(t=this.filterProperties(t),0==Object.keys(t).length)return;let i,n,r={event:e,properties:t},s=this._getBase64String(r),o=this._getURIEncodedString(s),a="GET";this._needPostRequest(o)?(i=this.senderConfig.url,a="POST",n=JSON.stringify({data:o})):(i=this.senderConfig.url+"?data="+o,a="GET",n=void 0),VizbeeSDK.logger.d(`${this.constructor.name}`,`track() - sending metrics request: URL ${i}, Method ${a}, Data ${n}`),C.xhr({url:i,method:a,data:n,timeout:1e4,retries:this.senderConfig.networkRetries}).then(e=>{e.error?VizbeeSDK.logger.e(`${this.constructor.name}`,"track - ERROR"):VizbeeSDK.logger.d(`${this.constructor.name}`,`track - SUCCESS: ${e}`)}).catch(e=>{VizbeeSDK.logger.d(`${this.constructor.name}`,`track - ERROR=${e}`)})}shouldTrack(e){return VizbeeSDK.logger.d(`${this.constructor.name}`,`shouldTrack - Filtering events with regex = ${this.senderConfig.eventFilter}`),!this.senderConfig.eventFilter||new RegExp(this.senderConfig.eventFilter,"i").test(e)}filterProperties(e){if(VizbeeSDK.logger.d(`${this.constructor.name}`,`filterProperties - Filtering properties with regex = ${this.senderConfig.attributeFilter}`),!this.senderConfig.attributeFilter)return e;e=e||{},e=JSON.parse(JSON.stringify(e));for(var t=new RegExp(this.senderConfig.attributeFilter,"i"),i=Object.keys(e),n=0;n<i.length;n++){var r=i[n];t.test(r)||delete e[r]}return e}_getBase64String(e){return btoa(unescape(encodeURIComponent(JSON.stringify(e))))}_getURIEncodedString(e){return window.encodeURIComponent(e)}_needPostRequest(e){return!!(e&&e.length>1e4)}}class En extends _n{constructor(e){let t={};e.mixpanel_url&&(t={eventFilter:e.mixpanel_filter,token:e.mixpanel_token,attributeFilter:e.attribute_filter,url:e.mixpanel_url,networkRetries:0}),super(t)}track(e,t){(t=t||{}).token=this.senderConfig.token,super.track(e,t)}}class In extends _n{constructor(e){let t={};e.vizbee_url&&(t={url:e.vizbee_url,attributeFilter:e.attribute_filter,eventFilter:e.vizbee_filter,networkRetries:0}),super(t)}}class Tn{constructor(e){this.senders=[],e&&e.vizbee_url&&this.senders.push(new In(e)),e&&e.mixpanel_url&&e.mixpanel_token&&this.senders.push(new En(e))}track(e,t){VizbeeSDK.logger.d(`${this.constructor.name}`,"track",e,t),I.each(this.senders,i=>{i.track(e,I.clone(t))})}}const Vn={RECEIVER_PAGE_LOAD_STARTED:"RECEIVER_PAGE_LOAD_STARTED",RECEIVER_SCRIPTS_LOADED:"RECEIVER_SCRIPTS_LOADED",VIZBEE_SDK_INITIALIZED:"VIZBEE_SDK_INITIALIZED",VIZBEE_CONFIG_LOADED:"VIZBEE_CONFIG_LOADED",RECEIVER_READY:"RECEIVER_READY",LOAD_REQUEST_RECEIVED:"LOAD_REQUEST_RECEIVED",STREAM_RESOLVE_STARTED:"STREAM_RESOLVE_STARTED",DVP_REQUEST_SENT:"DVP_REQUEST_SENT",DVP_RESPONSE_RECEIVED:"DVP_RESPONSE_RECEIVED",DVP_IVOD_RETRY_REQUEST_SENT:"DVP_IVOD_RETRY_REQUEST_SENT",DVP_IVOD_RETRY_RESPONSE_RECEIVED:"DVP_IVOD_RETRY_RESPONSE_RECEIVED",STREAM_RESOLVE_COMPLETED:"STREAM_RESOLVE_COMPLETED",DAI_STREAM_REQUEST_SENT:"DAI_STREAM_REQUEST_SENT",DAI_STREAM_RESPONSE_RECEIVED:"DAI_STREAM_RESPONSE_RECEIVED",PLAYER_LOAD_REQUESTED:"PLAYER_LOAD_REQUESTED",PLAYER_LOAD_STARTED:"PLAYER_LOAD_STARTED",DRM_LICENSE_REQUEST_SENT:"DRM_LICENSE_REQUEST_SENT",DRM_LICENSE_RESPONSE_RECEIVED:"DRM_LICENSE_RESPONSE_RECEIVED",MANIFEST_LOADED:"MANIFEST_LOADED",FIRST_FRAME_DECODED:"FIRST_FRAME_DECODED",PREROLL_AD_STARTED:"PREROLL_AD_STARTED",PREROLL_AD_ENDED:"PREROLL_AD_ENDED",PLAYBACK_STARTED:"PLAYBACK_STARTED",VIEW_START_REPORTED:"VIEW_START_REPORTED",VIEW_ERROR_REPORTED:"VIEW_ERROR_REPORTED"},Pn=[Vn.RECEIVER_PAGE_LOAD_STARTED,Vn.RECEIVER_SCRIPTS_LOADED,Vn.VIZBEE_SDK_INITIALIZED,Vn.VIZBEE_CONFIG_LOADED,Vn.RECEIVER_READY],An="VZBStageTimeline",Dn={now:()=>performance.now(),startsAtPageLoad:!0},Cn={now:()=>Date.now(),startsAtPageLoad:!1};function kn(e){return"STAGE_"+e+"_MS"}class wn{constructor(e=function(){return"undefined"!=typeof performance&&"function"==typeof performance.now?Dn:Cn}()){ke(this,"receiverMarks",{}),ke(this,"videoMarks",{}),ke(this,"isVideoOpen",!1),ke(this,"didReportReceiverStages",!1),ke(this,"isEnabled",!0),this.clock=e,e.startsAtPageLoad&&(this.receiverMarks[Vn.RECEIVER_PAGE_LOAD_STARTED]=0)}mark(e){try{if(!this.isEnabled||"string"!=typeof(t=e)||!Vn.hasOwnProperty(t))return;!function(e){return-1!=Pn.indexOf(e)}(e)?this.isVideoOpen&&this.markOnce(this.videoMarks,e):this.didReportReceiverStages||this.markOnce(this.receiverMarks,e)}catch(e){}var t}startVideo(){try{if(!this.isEnabled)return;this.videoMarks={},this.isVideoOpen=!0,this.mark(Vn.LOAD_REQUEST_RECEIVED)}catch(e){}}takeReport(e){try{if(!this.isVideoOpen)return{};this.mark(e),this.isVideoOpen=!1;const t=this.videoMarks[Vn.LOAD_REQUEST_RECEIVED],i={};return this.didReportReceiverStages||(this.addRelativeTimes(i,this.receiverMarks,t),this.didReportReceiverStages=!0,this.receiverMarks={}),this.addRelativeTimes(i,this.videoMarks,t),i}catch(e){return{}}}disable(){this.isEnabled=!1,this.isVideoOpen=!1,this.receiverMarks={},this.videoMarks={}}markOnce(e,t){void 0===e[t]&&(e[t]=this.clock.now())}addRelativeTimes(e,t,i){for(const n in t)t.hasOwnProperty(n)&&(e[kn(n)]=Math.round(t[n]-i))}}function Nn(){const e="undefined"!=typeof window?window:{};return e[An]||(e[An]=new wn),e[An]}const On="vzb-stage-times-overlay",Rn=[["DVP request","DVP_REQUEST_SENT","DVP_RESPONSE_RECEIVED"],["Receiver -> CAF","STREAM_RESOLVE_COMPLETED","PLAYER_LOAD_REQUESTED"],["CAF -> LOAD_START","PLAYER_LOAD_REQUESTED","PLAYER_LOAD_STARTED"],["-> Manifest","PLAYER_LOAD_STARTED","MANIFEST_LOADED"],["-> First frame","MANIFEST_LOADED","FIRST_FRAME_DECODED"],["-> PLAYING","FIRST_FRAME_DECODED","PLAYBACK_STARTED"],["VST (Conviva/Mux)","PLAYER_LOAD_STARTED","PLAYBACK_STARTED"],["LOAD -> PLAYING","LOAD_REQUEST_RECEIVED","PLAYBACK_STARTED"],["Receiver startup","RECEIVER_PAGE_LOAD_STARTED","RECEIVER_READY"]];let Mn;const Ln="VZBBackendRequestReport";function xn(){const e="undefined"!=typeof window?window:{};return e[Ln]&&"object"==typeof e[Ln]||(e[Ln]={report:null}),e[Ln]}function zn(){try{xn().report=null}catch(e){}}const Kn=2e3,Un=["BACKEND_SOURCE","BACKEND_REQUEST_RESULT","BACKEND_ERROR_CODE","BACKEND_ERROR_NAME","BACKEND_ERROR_MESSAGE","BACKEND_HTTP_STATUS","BACKEND_SESSION_ID"],Fn=/[a-z][a-z0-9+.-]*:\/\/\S+/gi;function Bn(e){let t=JSON.stringify(e);if(t.length<=Kn)return t;const i={...e},n=Object.keys(i).filter(e=>-1==Un.indexOf(e)).sort((e,t)=>String(i[t]).length-String(i[e]).length);for(const e of n)if(delete i[e],t=JSON.stringify(i),t.length<=Kn)return t;return t.substring(0,Kn)}function Gn(e){for(const t of e)if("string"==typeof t&&t||"number"==typeof t)return t}function Hn(e){const t=e.filter(e=>"string"==typeof e&&e).map(e=>e.replace(Fn,"<url>")).join(": ");return t?t.substring(0,200):void 0}const Wn="UNKNOWN",jn="NOT_FOUND";var qn=new class{constructor(){this.config={},this.commonProperties={},this.attributesProvidersList=[],this.isInitialized=!1,this.needToSetDistinctIdForVideoEvents=!0,this.isScreenLaunchedTracked=!1,this.devFeatures=!1}init(e){if(e&&this.commonProperties)if(VizbeeSDK.logger.d("MetricsManager","init",e.appId,this.commonProperties.APP_ID),this.isInitialized&&this.commonProperties.APP_ID==e.appId)VizbeeSDK.logger.d("MetricsManager","init","already initialized");else{this.config=e,this.metricsRouter=new Tn(e.metricsParams),I.get(e,["features","disableStageTimeline"])&&function(){try{Nn().disable()}catch(e){}}(),this.appSessionId=Math.floor(1e10*Math.random()).toString()+"_"+Date.now(),this.screenSdkId=Re.getItem("SCREEN_SDK_ID"),this.screenSdkId?VizbeeSDK.logger.d("MetricsManager::init","SCREEN_SDK_ID -> AVAILABLE -> REUSING IT"):(VizbeeSDK.logger.d("MetricsManager::init","SCREEN_SDK_ID -> NOT_AVAILABLE"),this.screenSdkId=Math.floor(1e10*Math.random()).toString()+"_"+Date.now(),Re.setItem("SCREEN_SDK_ID",this.screenSdkId,"local",31536e3,"/"));var t=this.prepareCommonProperties(e);this.setCommonProperties(t),e.customAttributesForMetrics&&this.setCustomProperties(e.customAttributesForMetrics),this.isInitialized=!0}else VizbeeSDK.logger.e("MetricsManager","init","called with empty config!")}refreshLaunchParamProperties(){if(VizbeeTV.tv.launchParamsDeferral){const e=VizbeeTV.tv.launchParamsDeferral.isLaunchedbyVizbee()||!1;this.commonProperties.SCREEN_LAUNCHED_WITH_VIZBEE=e,this.commonProperties.SCREEN_VZB_LAUNCH_PARAM=e?"y":jn}}prepareCommonProperties(e){var t,i,n,r={appId:e.appId,deviceId:e.deviceId,deviceType:VizbeeTV.tv.cloudPlatformName,distinctId:e.deviceId,externalIp:e.externalIp,ipv6Address:e.ipv6Address,sdkVersion:window.VZB?window.VZB.VERSION:"",appSessionId:this.appSessionId,screenSdkId:this.screenSdkId,timezoneOffset:(t=-(new Date).getTimezoneOffset(),i=t>=0?"+":"-",n=Math.abs(t),"GMT"+i+("0"+Math.floor(n/60)).slice(-2)+":"+("0"+n%60).slice(-2))};return VizbeeTV.tv.deviceInfo&&(VizbeeTV.tv.deviceInfo.deviceId&&VizbeeTV.tv.deviceInfo.deviceId!=Wn&&(r.deviceId=VizbeeTV.tv.deviceInfo.deviceId,r.distinctId=VizbeeTV.tv.deviceInfo.deviceId),r.macAddress=VizbeeTV.tv.deviceInfo.macAddress,r.deviceMake=VizbeeTV.tv.deviceInfo.make,r.deviceModel=VizbeeTV.tv.deviceInfo.model,r.deviceSerialNumber=VizbeeTV.tv.deviceInfo.serialNumber,r.friendlyName=VizbeeTV.tv.deviceInfo.friendlyName,r.osVersion=I.get(VizbeeTV.tv.deviceInfo,["os","version"],Wn),r.osNativeVersion=I.get(VizbeeTV.tv.deviceInfo,["os","sdkVersion"],Wn)),VizbeeTV.tv.adId&&(r.adId=VizbeeTV.tv.adId),null!=VizbeeTV.tv.isAdTrackingDisabled&&(r.isAdTrackingDisabled=VizbeeTV.tv.isAdTrackingDisabled),VizbeeTV.tv.networkInfo&&(r.internalIp=VizbeeTV.tv.networkInfo.internalIP,r.bssid=VizbeeTV.tv.networkInfo.bssid,r.ssid=VizbeeTV.tv.networkInfo.ssid,r.isWifiConnected=VizbeeTV.tv.networkInfo.isWifiConnected,r.connectionType=VizbeeTV.tv.networkInfo.connectionType),VizbeeTV.tv.launchParamsDeferral&&(r.isLaunchedWithVizbee=VizbeeTV.tv.launchParamsDeferral.isLaunchedbyVizbee()||!1),r}setCommonProperties(e){VizbeeSDK.logger.d("MetricsManager","setCommonProperties"),this.commonProperties.SCREEN_DEVICE_USERAGENT=Wn,this.commonProperties.SCREEN_IDFV=Wn,this.commonProperties.SCREEN_HOMESSO_USER_INFO={user_login:Wn,user_login_type:Wn,user_name:Wn,user_subscription_renewal_type:Wn,user_subscription_type:Wn,user_subscription_value:Wn},e.appId&&(this.commonProperties.APP_ID=e.appId),e.externalIp&&(this.commonProperties.EXTERNAL_IP_ADDRESS=e.externalIp),e.ipv6Address&&(this.commonProperties.IPV6_ADDRESS=e.ipv6Address),e.distinctId&&(this.commonProperties.distinct_id=e.distinctId),e.deviceId&&(this.commonProperties.SCREEN_DEVICE_ID=e.deviceId),e.appSessionId&&(this.commonProperties.SCREEN_APP_SESSION_ID=e.appSessionId),e.screenSdkId&&(this.commonProperties.SCREEN_SDK_ID=e.screenSdkId),e.internalIp&&(this.commonProperties.INTERNAL_IP_ADDRESS=e.internalIp,this.commonProperties.SCREEN_INTERNAL_IP=e.internalIp),"isWifiConnected"in e&&(this.commonProperties.WIFI_CONNECTED=e.isWifiConnected),e.connectionType&&(this.commonProperties.CONNECTION_TYPE=e.connectionType),e.bssid&&(this.commonProperties.WIFI_BSSID=e.bssid),e.ssid&&(this.commonProperties.WIFI_SSID=e.ssid),e.adId&&(this.commonProperties.SCREEN_IDFA=e.adId),null!=e.isAdTrackingDisabled&&(this.commonProperties.SCREEN_LIMIT_AD_TRACKING=e.isAdTrackingDisabled),e.macAddress&&(this.commonProperties.SCREEN_MAC_ADDRESS=e.macAddress),navigator&&navigator.userAgent&&(this.commonProperties.SCREEN_DEVICE_USERAGENT=navigator.userAgent),e.deviceType&&(this.commonProperties.SCREEN_DEVICE_TYPE=e.deviceType),e.deviceMake&&(this.commonProperties.SCREEN_DEVICE_MAKE=e.deviceMake),e.deviceModel&&(this.commonProperties.SCREEN_DEVICE_MODEL=e.deviceModel),e.deviceSerialNumber&&(this.commonProperties.SCREEN_SERIAL_NUMBER=e.deviceSerialNumber),e.friendlyName&&(this.commonProperties.SCREEN_FRIENDLY_NAME=e.friendlyName),e.osNativeVersion&&(this.commonProperties.SCREEN_NATIVE_OS_VERSION=e.osNativeVersion),e.osVersion&&(this.commonProperties.SCREEN_OS_VERSION=e.osVersion),null!=e.isLaunchedWithVizbee&&(this.commonProperties.SCREEN_LAUNCHED_WITH_VIZBEE=e.isLaunchedWithVizbee),this.commonProperties.SCREEN_LAUNCHED_WITH_VIZBEE?this.commonProperties.SCREEN_VZB_LAUNCH_PARAM="y":this.commonProperties.SCREEN_VZB_LAUNCH_PARAM=jn,e.sdkVersion&&(this.commonProperties.SCREEN_SDK_VERSION=e.sdkVersion),e.timezoneOffset&&(this.commonProperties.TIMEZONE=e.timezoneOffset),e.SCREEN_HOMESSO_USER_INFO&&(this.commonProperties.SCREEN_HOMESSO_USER_INFO=e.SCREEN_HOMESSO_USER_INFO)}setAttributesProviderProperties(e,t){if(0==this.attributesProvidersList.length)return void t(e);const i=this.attributesProvidersList.map(e=>e.provider.getAttributes());Promise.all(i).then(i=>{i.forEach(t=>{t&&(e=I.extend(e,t))}),t(e)}).catch(i=>{console.error("Error getting attributes:",i),t(e)})}setCustomProperties(e){VizbeeSDK.logger.d("MetricsManager","setCustomProperties"),I.each(e,(e,t)=>{this.commonProperties["CUSTOM_"+t]=e})}addProvider(e,t){VizbeeSDK.logger.d("MetricsManager","addProvider"),this.attributesProvidersList.push({provider:e,filterRegEx:t})}removeProvider(e){VizbeeSDK.logger.d("MetricsManager","removeProvider"),this.attributesProvidersList=I.reject(this.attributesProvidersList,t=>t.provider==e)}trackEvent(e,t){this.shouldTrack(e,t)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackEvent",e);let i=I.extend({},this.commonProperties,t);this.track(e,i)})}trackScreenLaunched(e,t){!this.isScreenLaunchedTracked&&this.shouldTrack("SCREEN_LAUNCHED",this.commonProperties)&&(this.isScreenLaunchedTracked=!0,this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenLaunched");let i=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenLaunchedProperties(e),t||{});this.track("SCREEN_LAUNCHED",i)}))}trackScreenTVViewLoad(e){this.shouldTrack("SCREEN_TV_VIEW_LOAD",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewLoad"),this.commonProperties.distinct_id=this.commonProperties.APP_ID+":"+this.commonProperties.SCREEN_DEVICE_TYPE+":"+C.uuidv4()+":"+Date.now(),this.needToSetDistinctIdForVideoEvents=!1;let t=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildNewScreenTVViewProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track("SCREEN_TV_VIEW_LOAD",t)})}trackScreenTVViewStart(e){if(!this.shouldTrack("SCREEN_TV_VIEW_START",e))return;let t=this.buildStageTimelineProperties(Vn.VIEW_START_REPORTED);zn(),this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewStart"),this.needToSetDistinctIdForVideoEvents&&(this.commonProperties.distinct_id&&-1==this.commonProperties.distinct_id.indexOf(this.commonProperties.SCREEN_DEVICE_TYPE)&&(this.commonProperties.APP_ID,this.commonProperties.SCREEN_DEVICE_TYPE,C.uuidv4(),Date.now()),this.needToSetDistinctIdForVideoEvents=!0);let i=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewStartProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildScreenTVViewStartTimeQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e),this.buildDiagnosticsJsonProperties(t));this.track("SCREEN_TV_VIEW_START",i),this.shouldShowStageTimesOverlay()&&function(e,t){try{if("undefined"==typeof document||!document.body||!e)return;const i=function(e,t){const i=[];return Rn.forEach(([t,n,r])=>{const s=e["STAGE_"+n+"_MS"],o=e["STAGE_"+r+"_MS"];"number"==typeof s&&"number"==typeof o&&i.push(t+": "+(o-s)+" ms")}),i.length>0&&t?[t].concat(i):i}(e,t);if(0==i.length)return;let n=document.getElementById(On);n||(n=document.createElement("pre"),n.id=On,n.setAttribute("style","position:fixed;top:24px;left:24px;z-index:2147483647;margin:0;padding:12px 16px;background:rgba(0,0,0,0.75);color:#fff;font:20px/1.4 monospace;pointer-events:none;"),document.body.appendChild(n)),n.textContent=i.join("\n"),n.style.display="block",clearTimeout(Mn),Mn=setTimeout(()=>{const e=document.getElementById(On);e&&(e.style.display="none")},3e4)}catch(e){}}(t,i.SCREEN_DEVICE_MODEL)})}trackScreenTVViewPause(e){this.shouldTrack("SCREEN_TV_VIEW_PAUSE",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewPause");let t=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewDurationProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track("SCREEN_TV_VIEW_PAUSE",t)})}trackScreenTVViewResume(e){this.shouldTrack("SCREEN_TV_VIEW_RESUME",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewResume");let t=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewResumeProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));this.track("SCREEN_TV_VIEW_RESUME",t)})}trackScreenTVViewDuration(e){this.shouldTrack("SCREEN_TV_VIEW_DURATION",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewDuration");let t=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewDurationProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e));t.SCREEN_HOMESSO_USER_INFO=void 0,this.track("SCREEN_TV_VIEW_DURATION",t)})}trackScreenTVViewError(e){let t="SCREEN_TV_VIEW_ERROR";if(!this.shouldTrack(t,e))return;let i=this.buildStageTimelineProperties(Vn.VIEW_ERROR_REPORTED),n=function(e){try{if(!e||!e.BACKEND_REQUEST_RESULT||"OK"==e.BACKEND_REQUEST_RESULT)return;const t=String(e.BACKEND_REQUEST_RESULT),i={vizbeeError:"BACKEND_"+t,source:"BACKEND_"+(e.BACKEND_SOURCE||"UNKNOWN"),operation:"PLAYBACK_URL_REQUEST",errorCode:Gn([e.BACKEND_ERROR_CODE,e.BACKEND_HTTP_STATUS,t]),errorMessage:Hn([t,e.BACKEND_ERROR_NAME,e.BACKEND_ERROR_MESSAGE]),errorDetails:Bn(e)};return void 0===i.errorMessage&&delete i.errorMessage,i}catch(e){return}}(this.buildBackendRequestProperties());this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVViewError");let r=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenTVViewErrorProperties(e,n),this.buildScreenTVViewDurationProperties(e),this.buildScreenTVViewQualityProperties(e),this.buildStreamInfoAndMetadataProperties(e),this.buildDiagnosticsJsonProperties(i));this.track(t,r)})}trackScreenAdView(e){this.shouldTrack("SCREEN_AD_VIEW",e)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenAdView","tracking SCREEN_AD_VIEW");let t=I.extend({},this.commonProperties,this.buildPlayerProperties(),this.buildScreenAdViewProperties(e));this.track("SCREEN_AD_VIEW",t)})}trackScreenRemoteConnected(e){e&&this.shouldTrack("SCREEN_REMOTE_CONNECTED")&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenRemoteConnected");let t=I.extend({},this.commonProperties,this.buildPlayerProperties(),this._buildSenderProperties(e));this.track("SCREEN_REMOTE_CONNECTED",t)})}trackScreenTVSignin(e){e&&this.shouldTrack("SCREEN_TV_SIGNIN")&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenTVSignin");let t=I.extend({},this.commonProperties,this.buildScreenTVSigninProperties(e));this.track("SCREEN_TV_SIGNIN",t)})}_buildSenderProperties(e){return e&&e.ssinfo?{CONNECTED_REMOTE:e.ssinfo}:{}}metricsConfig(){return this.config.metricsParams}isVideoEvent(e){return-1!=["SCREEN_TV_VIEW_LOAD","SCREEN_TV_VIEW_START","SCREEN_TV_VIEW_PAUSE","SCREEN_TV_VIEW_RESUME","SCREEN_TV_VIEW_DURATION","SCREEN_AD_VIEW"].indexOf(e)}isValidContinuityEvent(e){return-1!=["SCREEN_LAUNCHED","SCREEN_REMOTE_CONNECTED","SCREEN_TV_SIGNIN","SCREEN_TV_VIEW_LOAD","SCREEN_TV_VIEW_START","SCREEN_TV_VIEW_PAUSE","SCREEN_TV_VIEW_RESUME","SCREEN_TV_VIEW_DURATION","SCREEN_TV_VIEW_ERROR","SCREEN_AD_VIEW"].indexOf(e)}isValidHomeSSOEvent(e){return-1!=["SCREEN_HOMESSO_SIGNIN_RECEIVED","SCREEN_HOMESSO_SIGNIN_STATUS"].indexOf(e)}shouldTrack(e,t){if(0==Object.keys(this.config).length)return void VizbeeSDK.logger.e("MetricsManager","shouldTrack","called with empty config!");let i=!0;return this.isValidContinuityEvent(e)?this.isVideoEvent(e)&&this.metricsConfig()&&this.metricsConfig().shouldSendViewEventsOnlyOnCast&&t&&!t.isVideoLaunchedFromPhone&&(i=!1):this.isValidHomeSSOEvent(e)||(i=!1),i}track(e,t){t.VZB_TIMESTAMP=Date.now(),this.metricsRouter.track(e,t)}buildPlayerProperties(){let e={PLAYER_NAME:"UNKNOWN"};return VizbeeTV.tv.player&&(e.PLAYER_NAME=VizbeeTV.tv.player.getName()),e}buildScreenLaunchedProperties(e){return{SCREEN_CHANNEL_ID:e&&e.channelId||Wn,SCREEN_CHANNEL_IP_SOURCE:VizbeeTV.tv&&VizbeeTV.tv.deviceIDSource||Wn}}buildVideoProperties(e){return{VIDEO_ID:e.videoId,VIDEO_TITLE:e.videoTitle,VIDEO_START_TIME:e.videoStartTime,VIDEO_DURATION_MS:Math.round(e.videoDuration),IS_LIVE:e.isLive,IS_CONTINUED_VIEW:e.isContinuedView,IS_VIDEO_LAUNCHED_FROM_PHONE:e.isVideoLaunchedFromPhone}}buildNewScreenTVViewProperties(e){return this.buildVideoProperties(e)}buildScreenTVViewStartProperties(e){return this.buildVideoProperties(e)}buildScreenTVViewResumeProperties(e){return I.extend({VIDEO_PAUSED_TIME_MS:Math.round(e.videoPausedTimeInMs)},this.buildScreenTVViewDurationProperties(e))}buildScreenTVViewDurationProperties(e){return I.extend({VIDEO_POSITION_MS:Math.round(e.videoPosition),VIDEO_POSITION_MIN:e.videoPostitionMin,VIDEO_ELAPSED_TIME_MS:Math.round(e.videoElapsedTime),VIDEO_ELAPSED_TIME_MIN:e.videoElapsedTimeMin},this.buildVideoProperties(e))}buildStreamInfoAndMetadataProperties(e){let t={};try{if(e.customStreamInfo&&e.customMetadata){let i={customStreamInfo:e.customStreamInfo,customMetadata:e.customMetadata};t=I.extend({},C.flatten(i))}}catch(e){}return t}buildScreenTVViewQualityProperties(e){(!e.startTime||e.startTime<0)&&(e.startTime=0);let t=e.startTime/1e3,i=e.videoBufferLevel?e.videoBufferLevel.current:0,n=e.audioBufferLevel?e.audioBufferLevel.current:0,r=e.audioBufferLevel?e.audioBufferLevel.didDetectSeparateAudio:"UNKNOWN",s=2*Math.ceil(t/2),o=2*Math.ceil(i/2),a=2*Math.ceil(n/2);return I.extend({START_TIME_SEC:t||0,VIDEO_BUFFER_SEC:i||0,AUDIO_BUFFER_SEC:n||0,AUDIO_STREAM_DETECTED:r,START_TIME_2SEC_BIN:s||0,VIDEO_BUFFER_2SEC_BIN:o||0,AUDIO_BUFFER_2SEC_BIN:a||0},this.buildVideoProperties(e))}buildScreenTVViewStartTimeQualityProperties(e){return e&&this.isStartTimeFeatureOn("sendStartTimeQualityInfo")?{PRE_ROLL_AD_POD_START_TIME_MS:e.adPodStartedTimeInMs?e.adPodStartedTimeInMs:0,PRE_ROLL_AD_POD_END_TIME_MS:e.adPodEndedTimeInMs?e.adPodEndedTimeInMs:0,VIDEO_LOAD_RECEIVED_BY_APP_TIME_MS:e.loadReceivedByAppTimeInMs?e.loadReceivedByAppTimeInMs:0,VIDEO_LOAD_RECEIVED_BY_PLAYER_TIME_MS:e.loadReceivedByPlayerTimeInMs?e.loadReceivedByPlayerTimeInMs:0,VIDEO_METADATA_LOADED_TIME_MS:e.metadataLoadedTimeInMs?e.metadataLoadedTimeInMs:0,VIDEO_PLAYER_READY_TIME_MS:e.playerReadyToPlayTimeInMs?e.playerReadyToPlayTimeInMs:0,VIDEO_PLAYBACK_STARTED_TIME_MS:e.playbackStartedTimeInMs?e.playbackStartedTimeInMs:0}:{}}isStartTimeFeatureOn(e){let t=I.get(this.config,["features",e]);return void 0!==t?!!t:this.devFeatures}shouldShowStageTimesOverlay(){return this.devFeatures&&!1!==I.get(this.config,["features","showStageTimesOverlay"])}buildStageTimelineProperties(e){try{return this.isStartTimeFeatureOn("sendStartupStageTimes")?function(e){try{return Nn().takeReport(e)||{}}catch(e){return{}}}(e):{}}catch(e){return{}}}buildBackendRequestProperties(){return this.isStartTimeFeatureOn("sendBackendRequestReport")?function(){try{const e=xn(),t=e.report;return e.report=null,t?function(e){const t={};for(const i in e){if(!e.hasOwnProperty(i))continue;const n=e[i];"number"==typeof n||"boolean"==typeof n?t[i]=n:"string"==typeof n&&(t[i]=n.slice(0,500))}return t}("function"==typeof t?t():t):{}}catch(e){return{}}}():(zn(),{})}buildDiagnosticsJsonProperties(e){let t={};try{I.isEmpty(e)||(t.STAGE_TIMES_JSON=JSON.stringify(e))}catch(e){}return t}buildScreenTVViewErrorProperties(e,t){let i=I.extend({VIDEO_POSITION_MS:Math.round(e.videoPosition),FAILURE_VALUE:e.failureValue,FAILURE_CODE:e.failureCode},this.buildVideoProperties(e));return I.extend(i,this.buildFailureInfoProperties(t||e.failureInfo)),i}buildFailureInfoProperties(e){let t={};if(!e||"object"!=typeof e)return t;let i={FAILURE_VALUE_VIZBEE_ERROR:e.vizbeeError,FAILURE_VALUE_SOURCE:e.source,FAILURE_VALUE_OPERATION:e.operation,FAILURE_VALUE_ERROR_CODE:e.errorCode,FAILURE_VALUE_ERROR_MESSAGE:e.errorMessage,FAILURE_VALUE_ERROR_DETAILS:e.errorDetails};return Object.keys(i).forEach(e=>{null!=i[e]&&(t[e]=i[e])}),t}buildScreenAdViewProperties(e){return{SCREEN_AD_ID:e.adId,AD_DURATION:e.adDuration,VIDEO_ID:e.videoId,VIDEO_TITLE:e.videoTitle,VIDEO_DURATION_MS:Math.round(e.videoDuration),VIDEO_POSITION_MS:Math.round(e.videoPosition),IS_LIVE:e.isLive,IS_VIDEO_LAUNCHED_FROM_PHONE:e.isVideoLaunchedFromPhone}}buildScreenTVSigninProperties(e){return{USER_ID:e.userId,USER_LOGIN:e.userLogin,USER_LOGIN_TYPE:e.userLoginType}}_setUpdatedCommonProperties(e){let t={};this.commonProperties.adId&&this.commonProperties.adId!=Wn||(t.adId=VizbeeTV.tv.adId||Wn),this.commonProperties.isAdTrackingDisabled&&this.commonProperties.isAdTrackingDisabled!=Wn||(t.isAdTrackingDisabled=VizbeeTV.tv.isAdTrackingDisabled||Wn),VizbeeTV.tv.deviceInfo&&(VizbeeTV.tv.deviceInfo.deviceId&&VizbeeTV.tv.deviceInfo.deviceId!=Wn&&(t.deviceId=VizbeeTV.tv.deviceInfo.deviceId),VizbeeTV.tv.deviceInfo.model&&VizbeeTV.tv.deviceInfo.model!=Wn&&(t.deviceModel=VizbeeTV.tv.deviceInfo.model)),this.setAttributesProviderProperties(t,t=>{this.setCommonProperties(t),e()})}};const Yn="receiver_with_applets";class Jn extends gn{constructor(e,t){super(e,t),this.appConfig=t,this.currentVideoId=void 0,this.didLogStartVideo=!1,this.lastLoggedVideoPostition2XMin=-1,this.elapsedLastPlayingTimestamp=void 0,this.elapsedPlayingTime=0,this.targetAppType=this.appConfig&&this.appConfig.features&&this.appConfig.features.targetAppType,this.senderMap={}}connect(e){qn.init(this.appConfig),et.markLaunched();const t=VizbeeTV.tv.launchParamsDeferral;t&&"function"==typeof t.waitUntilReady&&t.waitUntilReady().then(()=>{qn.refreshLaunchParamProperties()}),super.connect(e)}send(e){if(!e||!e.cmd)return void super.send(e);let t=e;"status"==e.cmd.name&&(t=this.interceptVideoStatus(e)),super.send(t)}interceptVideoStatus(e){if(this.currentVideoId!=e.vstatus.id&&(this.currentVideoId=e.vstatus.id,this.didLogStartVideo=!1,this.lastLoggedVideoPostition2XMin=-1,this.elapsedLastPlayingTimestamp=Date.now(),this.elapsedPlayingTime=0,VizbeeSDK.logger.d("MetricsExtension","interceptVideoStatus","logging new video"),qn.trackScreenTVViewLoad({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du||-1,isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee})),"PLAYING"==e.vstatus.st&&(e.vinfo.islive||!e.vinfo.islive&&e.vstatus.po>0)){if(!this.didLogStartVideo){VizbeeSDK.logger.d("MetricsExtension","interceptVideoStatus","logging start video");var t=e.vinfoext.qos||{};qn.trackScreenTVViewStart({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:t.starttime||0,audioBufferLevel:t.audiobufferlevel||{},videoBufferLevel:t.videobufferlevel||{},adPodStartedTimeInMs:t.adPodStartedTimeInMs||0,adPodEndedTimeInMs:t.adPodEndedTimeInMs||0,loadReceivedByAppTimeInMs:t.loadReceivedByAppTimeInMs||0,loadReceivedByPlayerTimeInMs:t.loadReceivedByPlayerTimeInMs||0,metadataLoadedTimeInMs:t.metadataLoadedTimeInMs||0,playerReadyToPlayTimeInMs:t.playerReadyToPlayTimeInMs||0,playbackStartedTimeInMs:t.playbackStartedTimeInMs||0}),this.didLogStartVideo=!0}this.elapsedPlayingTime=this.elapsedPlayingTime+(Date.now()-this.elapsedLastPlayingTimestamp),this.elapsedLastPlayingTimestamp=Date.now();let i=2*Math.floor(e.vstatus.po/12e4);i>this.lastLoggedVideoPostition2XMin&&(this.lastLoggedVideoPostition2XMin=i,qn.trackScreenTVViewDuration({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:this.lastLoggedVideoPostition2XMin,videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel}))}return"FAILED"==e.vstatus.st&&qn.trackScreenTVViewError({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,isLive:e.vinfo.islive,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:this.lastLoggedVideoPostition2XMin,videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,failureValue:e.vstatus.er.reason,failureCode:e.vstatus.er.code,failureInfo:e.vstatus.er.failure,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel}),["INTERRUPTED","FINISHED","FAILED"].indexOf(e.vstatus.st)>-1&&(this.currentVideoId=void 0),e}handleSyncReceiveEvent(e){let t=e.data;if(t&&t.b&&t.b.cmd&&"video"===t.b.cmd.ns&&"event"===t.b.cmd.name&&t.b.einfo&&"tv.vizbee.homesign.signin"==t.b.einfo.type){let e=t.b.einfo.data&&t.b.einfo.data.authInfo;e&&qn.trackScreenTVSignin(e)}return e}handleNonSyncReceiveEvent(e){if(e&&e.type==jt.SYNC_CONNECT){const e={channelId:this.baseSync&&this.baseSync.channelId};qn.trackScreenLaunched(e)}if(e&&e.type==jt.SYNC_PRESENCE){let t=e.data;if(t&&this.senderMap){let e=Object.keys(this.senderMap),i=Object.keys(t);i.length>e.length?i.forEach(e=>{this.senderMap[e]||(!t[e]||"vzb0000000"===t[e].appId&&this.targetAppType===Yn||(VizbeeSDK.logger.d("MetricsExtension","handleNonSyncReceiveEvent","new sender connected, id = "+e),qn.trackScreenRemoteConnected(t[e])),this.senderMap[e]=t[e])}):i.length<e.length&&e.forEach(e=>{-1==i.indexOf(e)&&(VizbeeSDK.logger.d("MetricsExtension","handleNonSyncReceiveEvent","sender disconnected, id = "+e),delete this.senderMap[e])})}}return e}}class Qn extends gn{constructor(e,t){super(e,t),this.appConfig=t,this.currentVideoId=void 0,this.elapsedLastPlayingTimestamp=void 0,this.elapsedPlayingTime=0,this.videoPausedTimestamp=-1,this.didLogPauseVideo=!1}connect(e){qn.init(this.appConfig),super.connect(e)}send(e){if(!e||!e.cmd)return void super.send(e);let t=e;"status"==e.cmd.name&&(t=this.interceptVideoStatus(e)),super.send(t)}interceptVideoStatus(e){return this.currentVideoId!=e.vstatus.id&&(this.currentVideoId=e.vstatus.id,this.elapsedLastPlayingTimestamp=Date.now(),this.elapsedPlayingTime=0,this.videoPausedTimestamp=-1,this.didLogPauseVideo=!1),"PLAYING"==e.vstatus.st&&(e.vinfo.islive||!e.vinfo.islive&&e.vstatus.po>0)&&(this.elapsedPlayingTime=this.elapsedPlayingTime+(Date.now()-this.elapsedLastPlayingTimestamp),this.elapsedLastPlayingTimestamp=Date.now(),this.didLogPauseVideo&&(VizbeeSDK.logger.debug("FilterPauseResumeEventsExtension::interceptVideoStatus - logging resume video"),qn.trackScreenTVViewResume({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:2*Math.floor(e.vstatus.po/12e4),videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),videoPausedTimeInMs:Date.now()-this.videoPausedTimestamp,isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel})),this.videoPausedTimestamp=-1,this.didLogPauseVideo=!1),"PAUSED_BY_USER"==e.vstatus.st&&(-1==this.videoPausedTimestamp&&(this.videoPausedTimestamp=Date.now()),!this.didLogPauseVideo&&Date.now()-this.videoPausedTimestamp>=15e3&&(VizbeeSDK.logger.debug("FilterPauseResumeEventsExtension::interceptVideoStatus - logging pause video"),qn.trackScreenTVViewPause({videoId:e.vstatus.id,videoTitle:e.vinfoext.title||e.vinfo.url,videoStartTime:e.vinfoext.videostarttime,videoDuration:e.vstatus.du,videoPosition:e.vstatus.po,videoPostitionMin:2*Math.floor(e.vstatus.po/12e4),videoElapsedTime:this.elapsedPlayingTime,videoElapsedTimeMin:2*Math.floor(this.elapsedPlayingTime/12e4),isLive:e.vinfo.islive,customStreamInfo:e.vinfoext.customstreaminfo,customMetadata:e.vinfoext.custommetadata,isContinuedView:!(!e.qstatus||!e.qstatus.prev),isVideoLaunchedFromPhone:e.vinfoext.wasVideoStartedByVizbee,startTime:e.vinfoext.qos.starttime,audioBufferLevel:e.vinfoext.qos.audiobufferlevel,videoBufferLevel:e.vinfoext.qos.videobufferlevel}),this.didLogPauseVideo=!0)),["INTERRUPTED","FINISHED","FAILED"].indexOf(e.vstatus.st)>-1&&(this.currentVideoId=void 0),e}}var $n=_(Ut());class Zn extends gn{constructor(e,t){if(super(e,t),this.enable=!0,t&&t.features&&t.features.SubtitlesExtension){let e=t.features.SubtitlesExtension;null!=e.enable&&(this.enable=e.enable)}}_isEnabled(){return this.enable}handleSyncReceiveEvent(e){let t=e.data;if(VizbeeSDK.logger.verbose(`SubtitlesExtension::handleSyncReceiveEvent - received message data = ${JSON.stringify(t)}`),!(t&&t.b&&t.b.cmd))return e;let i=t.b.cmd.name;if(!(i&&["enabletrack","disabletrack"].indexOf(i.toLowerCase())>-1))return e;if(this._isEnabled()){let e=Number(t.b.cmd.param);if(!isNaN(e)){let i=[e];"enabletrack"===t.b.cmd.name?$n.enableTracks(i):$n.disableTracks(i)}}}send(e){if(!e||!e.cmd)return void super.send(e);let t=e,i="status"==e.cmd.name,n="hello"==e.cmd.name&&"rsp"==e.cmd.type&&e.vstatus;(i||n)&&(t=this._interceptVideoStatus(e)),super.send(t)}_interceptVideoStatus(e){return this._addTrackStatus(e)}_addTrackStatus(e){if(!e||!e.vstatus)return e;if(e.vstatus.tr||(e.vstatus.tr={}),!this._isEnabled())return e;let t=this._getTextTrackStatus();return e.vstatus.tr.availableTextTracks=t.availableTextTracks,e.vstatus.tr.currentTextTrack=t.currentTextTrack,e}_getTextTrackStatus(){let e={},t=$n.getTracks(n),i=$n.getEnabledTracks(n);if(t&&Array.isArray(t)&&t.length>0&&(t.forEach(t=>{let i=t.toJSON();i&&(e.availableTextTracks||(e={availableTextTracks:[],currentTextTrack:{}}),e.availableTextTracks.push({screenTrackId:i.id,languageCode:i.lang}))}),i&&Array.isArray(i)&&i.length>0)){let t=i[0].toJSON();t&&(e.currentTextTrack={screenTrackId:t.id,languageCode:t.lang})}return e}}class Xn extends gn{constructor(e,t){if(super(e,t),this.enable=!0,t&&t.features&&t.features.AudioTracksExtension){let e=t.features.AudioTracksExtension;null!=e.enable&&(this.enable=e.enable)}}_isEnabled(){return this.enable}handleSyncReceiveEvent(e){if(!this._isEnabled())return e;let t=e.data;if(VizbeeSDK.logger.verbose(`AudioTracksExtension::handleSyncReceiveEvent - received message data = ${JSON.stringify(t)}`),!(t&&t.b&&t.b.cmd))return e;let i=t.b.cmd.name;if(!i||"string"!=typeof i||"changeaudiotrack"!==i.toLowerCase())return e;let n=Number(t.b.cmd.param);isNaN(n)?VizbeeSDK.logger.debug(`AudioTracksExtension::handleSyncReceiveEvent - received changeAudioTrack command with invalid trackId = ${n}`):(VizbeeSDK.logger.debug(`AudioTracksExtension::handleSyncReceiveEvent - received changeAudioTrack command with trackId = ${n}`),$n.changeAudioTrack(n))}send(e){if(!e||!e.cmd)return void super.send(e);let t=e,i="status"==e.cmd.name,n="hello"==e.cmd.name&&"rsp"==e.cmd.type&&e.vstatus;(i||n)&&(t=this._interceptVideoStatus(e)),VizbeeSDK.logger.verbose("AudioTracksExtension::send - forwarding out message",t),super.send(t)}_interceptVideoStatus(e){return this._addAudioTrackStatus(e)}_addAudioTrackStatus(e){if(!e||!e.vstatus)return e;if(e.vstatus.tr||(e.vstatus.tr={}),!this._isEnabled())return e;let t=this._getAudioTrackStatus();return e.vstatus.tr.availableAudioTracks=t.availableAudioTracks,e.vstatus.tr.currentAudioTrack=t.currentAudioTrack,e}_getAudioTrackStatus(){let e={},t=$n.getAudioTracks(r),i=$n.getActiveAudioTrack(r);return t&&Array.isArray(t)&&t.length>0&&(t.forEach(t=>{let i=t.toJSON();i&&(e.availableAudioTracks||(e={availableAudioTracks:[],currentAudioTrack:{}}),e.availableAudioTracks.push({screenTrackId:i.id,languageCode:i.lang,displayName:i.label}))}),i&&null!=i.id&&(e.currentAudioTrack={screenTrackId:i.id,languageCode:i.lang,displayName:i.label})),e}}const er=[un,pn,yn,vn,class extends gn{constructor(e,t){VizbeeSDK.logger.debug("ExitOnLastMessageRecvExtension::constructor()"),super(e,t)}handleSyncReceiveEvent(e){let t=e.data;if(VizbeeSDK.logger.verbose(`ExitOnLastMessageRecvExtension::onReceiveHandler() ${this.appConfig.appId}`,t),VizbeeSDK.logger.verbose("ExitOnLastMessageRecvExtension::onReceiveHandler getActiveSendersCount - cmd ",this.getActiveSendersCount(),t.b?t.b.cmd.name:""),!t.b||"exit"!==t.b.cmd.name)return e;"user_invoked_disconnect"===t.b.cmd.param&&0==this.getActiveSendersCount()&&this.appConfig.features&&this.appConfig.features.shouldExitOnLastSender&&(VizbeeSDK.logger.debug("ExitOnLastMessageRecvExtension::onReceiveHandler getActiveSendersCount is zero - going to exit the receiver app"),VizbeeTV.tv.exit())}},mn,class extends gn{constructor(e,t){VizbeeSDK.logger.debug("FilterMessageSendExtension::constructor()"),super(e,t),this.shouldFilterAllMessagesOnLastSenderExit=t&&t.features&&t.features.shouldFilterAllMessagesOnLastSenderExit}send(e){if(!e||!e.cmd)return void super.send(e);let t=this.getActiveSendersCount();if(!(this.shouldFilterAllMessagesOnLastSenderExit&&t<=0))return"status"==e.cmd.name?e.vstatus&&-1!=["FINISHED","INTERRUPTED","FAILED"].indexOf(e.vstatus.st)?(VizbeeSDK.logger.debug(`FilterMessageSendExtension::send message.vstatus.st: ${e.vstatus.st}`),void super.send(e)):void(0!==t?super.send(e):VizbeeSDK.logger.verbose("FilterMessageSendExtension::send senders not available: MESSAGE NOT SENT",this.getActiveSendersCount(),e)):void super.send(e);VizbeeSDK.logger.verbose("FilterMessageSendExtension::send filtering all messages as senders are not available and shouldFilterAllMessagesOnLastSenderExit is set")}},Sn,Qn,Jn,class extends gn{constructor(e,t){VizbeeSDK.logger.debug("DisconnectSendersInBackgroundExtension::constructor()",e,t.appId),super(e,t),this._enable=!1,this._senderAliveTimeoutWithFGFlagInMs=6e4,this._senderAliveTimeoutWithoutFGFlagInMs=72e4,this._senderAliveCheckTimer=void 0,this._senderAliveTimerWithFGFlag=void 0,this._senderAlivetTimerWithoutFGFlag=void 0,this._androidSendersInBackgroundMap={},this._androidSendersWithoutFGFlagMap={},this._getExtensionConfigData(t)}_getExtensionConfigData(e){if(e&&e.features&&e.features.DisconnectSendersInBackgroundExtension){let t=e.features.DisconnectSendersInBackgroundExtension;1==t.enable&&(this._enable=!0,null!=t.senderAliveTimeoutWithFGFlagInMs&&(this._senderAliveTimeoutWithFGFlagInMs=t.senderAliveTimeoutWithFGFlagInMs),null!=t.senderAliveTimeoutWithoutFGFlagInMs&&(this._senderAliveTimeoutWithoutFGFlagInMs=t.senderAliveTimeoutWithoutFGFlagInMs))}}disconnect(){VizbeeSDK.logger.debug("DisconnectSendersInBackgroundExtension::disconnect()"),this._stopAllTimers(),this._resetToDefault(),super.disconnect()}handleSyncReceiveEvent(e){if(!this._enable)return e;let t=e.data;if(t&&t.h){let e=t.h.ty&&t.h.ty.toLowerCase(),i=t.h.st&&t.h.st.toLowerCase();e&&"remote"==e&&i&&"android"==i&&(t.h.ssinfo&&null!=t.h.ssinfo.IS_IN_FOREGROUND?0==t.h.ssinfo.IS_IN_FOREGROUND?this._androidSendersInBackgroundMap[t.h.id]||(VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::handleSyncReceiveEvent - adding new sender to the map"),this._androidSendersInBackgroundMap[t.h.id]=Date.now()):this._androidSendersInBackgroundMap={}:this._androidSendersWithoutFGFlagMap[t.h.id]||(this._androidSendersWithoutFGFlagMap[t.h.id]=Date.now(),VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::handleSyncReceiveEvent - adding new sender to the map")))}return this._startSenderAliveCheckTimer(),e}_startSenderAliveCheckTimer(){this._stopSenderAliveCheckTimer(),this._senderAliveCheckTimer=window.setInterval(()=>{this._checkSenderStatusAndSendOlleh()},1e3)}_checkSenderStatusAndSendOlleh(){this._handleSendersInBackground(),this._handleSendersWithoutFGFlag()}_handleSendersInBackground(){let e=Date.now();I.keys(this._androidSendersInBackgroundMap).filter(t=>e-this._androidSendersInBackgroundMap[t]>this._senderAliveTimeoutWithFGFlagInMs).length>0&&(VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::_handleSendersInBackground - sending olleh as there are no senders in foreground"),this._sendOllehMessage(),this._resetToDefault())}_handleSendersWithoutFGFlag(){let e=Date.now(),t=I.keys(this._androidSendersWithoutFGFlagMap),i=I.keys(this._androidSendersWithoutFGFlagMap).filter(t=>e-this._androidSendersWithoutFGFlagMap[t]>this._senderAliveTimeoutWithoutFGFlagInMs);i.length>0&&t.length==i.length&&(VizbeeSDK.logger.info("DisconnectSendersInBackgroundExtension::_handleSendersWithoutFGFlag - sending olleh as there are no senders in foreground"),this._sendOllehMessage(),this._resetToDefault())}_sendOllehMessage(){this.dispatchReceive(new Wt(jt.SYNC_MESSAGE,{b:{cmd:{ns:"video",name:"olleh",type:"int"},hstatus:{id:this.appConfig.deviceId,type:"SCREEN",vip:"false"}}}))}_resetToDefault(){this._stopAllTimers(),this._androidSendersInBackgroundMap={},this._androidSendersWithoutFGFlagMap={}}_stopAllTimers(){this._stopSenderAliveCheckTimer(),this._stopDisconnetionTimerWithIsInFGFlag(),this._stopDisconnetionTimerWithoutIsInFGFlag()}_stopSenderAliveCheckTimer(){this._senderAliveCheckTimer&&(window.clearInterval(this._senderAliveCheckTimer),this._senderAliveCheckTimer=void 0)}_stopDisconnetionTimerWithIsInFGFlag(){this._senderAliveTimerWithFGFlag&&(window.clearTimeout(this._senderAliveTimerWithFGFlag),this._senderAliveTimerWithFGFlag=void 0)}_stopDisconnetionTimerWithoutIsInFGFlag(){this._senderAliveWithoutFGFlagTimer&&(window.clearTimeout(this._senderAliveWithoutFGFlagTimer),this._senderAliveWithoutFGFlagTimer=void 0)}},Zn,Xn],tr=[un,pn,yn,vn,mn,Sn,Qn,Jn,Zn,Xn,null];let ir;class nr{createSync(e){let t=I.get(e,["syncInfo","syncMethod"],"pubnub").toLowerCase();return"googlecustom"==t?(ir=this.getGoogleCustomSyncInstanceWitExtensions(e),ir):"googledual"==t?(ir=this.getGoogleDualSyncInstanceWitExtensions(e),ir):(ir=this.getDefaultSyncInstanceWitExtensions(e),ir)}static getSync(){return ir}getGoogleCustomSyncInstanceWitExtensions(e){return this.addExtensions(e,this.getGoogleCastSync(e),tr)}getGoogleDualSyncInstanceWitExtensions(e){let t=this.addExtensions(e,new dn(e),er),i=this.addExtensions(e,this.getGoogleCastSync(e),tr),n=new ln(e);return n.addSyncInstance(t),n.addSyncInstance(i),n}getDefaultSyncInstanceWitExtensions(e){return this.addExtensions(e,new dn(e),er)}addExtensions(e,t,i){for(let n=0;n<i.length;n++)t=new(0,i[n])(t,e);return t}getGoogleCastSync(e){return cast.framework,new null(e)}}let rr=function(e){return e[e.NOT_CONNECTED=1]="NOT_CONNECTED",e[e.CONNECTING=2]="CONNECTING",e[e.CONNECTED=3]="CONNECTED",e}({});var sr,or,ar,dr,lr,cr,ur,pr,hr=E(),gr=Ft(),fr=function(){if(wt)return kt;wt=1,E();var e={},t={};function i(){VizbeeSDK.logger.debug("VGAStateManager:reset() previous video and ad objects = ",e,t),e.id="",e.state="UNKNOWN",e.position=-1,e.duration=-1,t.id="",t.state="UNKNOWN",t.position=-1,t.duration=-1}return i(),kt={type:"VGAStateManager",app:{state:"app"},video:e,ad:t,reset:i,addListener:function(e){},removeListener:function(){}}}(),vr=at(),yr=Bt(),mr=Ut(),br=Gt(),Sr=750;let _r;class Er{static getInstance(){return null==_r&&(_r=new Er),_r}getQueueManager(){return null==this.queueManager&&(this.queueManager=new null(null.getInstance())),VizbeeSDK.logger.debug("ContinuityContext::getQueueManager - returning queue manager",this.queueManager),this.queueManager}}var Ir,Tr,Vr,Pr=E(),Ar=rt,Dr=st,Cr=function(e,t){var i,n=e,r=void 0,s=void 0,o=!1,a=!1,d=!1,l=!1;let c=n&&n.features&&n.features.syncSendIntervalInMs;isNaN(c)||(Sr=c);var u,p=[],h=[],g={};return t?(o=!0,i=fr):(o=!1,i=gr,mr.setAppStateManager(gr),br.addListener(function(e){VizbeeSDK.logger.debug("synccontroller",e),"sync_proxy_video_cmds"==e.type&&("x"===e.cmd.name||"event"===e.cmd.name?(delete e.type,r.send(e)):y(e))})),{connect:function(e){VizbeeSDK.logger.debug("SyncController::connect - dumping appConfig = ",n);var t=new nr;(r=t.createSync(n)).onReceive=function(t){if(t)switch(t.type){case jt.SYNC_CONNECT:!function(e){a=!0,o&&(VizbeeSDK.logger.debug("SyncController::syncConnectHandler - setting isAppAdapterAvailable to TRUE (isVGA=true)"),d=!0),f(),e(!0)}(e);break;case jt.SYNC_MESSAGE:var i=t.data.b,n=t.data.h;if(o&&i.cmd&&-1==["launch_applet","hello"].indexOf(i.cmd.name))return;s=n,"video"===(r=i).cmd.ns&&y(r,s),"x"===r.cmd.ns&&b((l=r).b.cmd.ns,m(l));break;case jt.SYNC_PRESENCE:o||function(e){VizbeeSDK.logger.debug("SyncController::presenceHandler() - connected users count",e);var t=hr.extend({},g);g=hr.extend({},e),VizbeeSDK.logger.debug("SyncController::syncPresenceHandler - transition","from:",Object.keys(t),"to:",Object.keys(g)),function(e,t){var i=Object.keys(e||{}),n=Object.keys(t||{});VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - previousIds: ",i," newIds: ",n);var r=n.filter(function(e){return-1===i.indexOf(e)});VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - joinedIds: ",r);var s=i.filter(function(e){return-1===n.indexOf(e)});VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - leftIds: ",s),r.forEach(function(e){var i=t[e];if(i){VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - user joined: ",e);var n={event:"JOIN",member:i};h.forEach(function(e){try{e(n)}catch(e){VizbeeSDK.logger.error("SyncController::notifyPresenceListeners - Error calling listener",e)}})}}),s.forEach(function(t){VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - user left: ",t);var i=e[t];if(i){VizbeeSDK.logger.debug("SyncController::notifyPresenceListeners - user left: ",t);var n={event:"LEAVE",member:i};h.forEach(function(e){try{e(n)}catch(e){VizbeeSDK.logger.error("SyncController::notifyPresenceListeners - Error calling listener",e)}})}})}(t,g),vr.updatePresence(e)}(t.data)}var r,s,l},r.connect(e),i.addListener(_),vr.isAppSet()&&(VizbeeSDK.logger.debug("SyncController::connect appIsSet"),d=!0,f()),p.forEach(e=>{e(rr.CONNECTED)}),s=window.setInterval(E,Sr)},disconnect:function(){VizbeeSDK.logger.debug("SyncController::disconnect() called"),clearInterval(s),i.removeListener(_),p.forEach(e=>{e(rr.NOT_CONNECTED)}),v(),r.disconnect(),a=!1},isConnected:function(){return a},addSessionStateListener:function(e){p.push(e)},sessionState:function(){return a?rr.CONNECTED:rr.NOT_CONNECTED},subscribeToPresence:function(e){"function"==typeof e&&(h.push(e),VizbeeSDK.logger.debug("SyncController::subscribeToPresence - listener added"))},unsubscribeFromPresence:function(e){const t=h.indexOf(e);t>-1&&(h.splice(t,1),VizbeeSDK.logger.debug("SyncController::unsubscribeFromPresence - listener removed"))},getActiveSenders:function(){return r&&"function"==typeof r.getActiveSenders?r.getActiveSenders():{}},enableSynchronousPublish:function(){try{var e=r&&r.baseSync;e&&"function"==typeof e.enableSynchronousPublish&&e.enableSynchronousPublish()}catch(e){VizbeeSDK.logger.error("SyncController::enableSynchronousPublish - error",e)}}};function f(){if(a&&d){o&&!l&&(l=!0,yr.onSubscribedToSync()),VizbeeSDK.logger.debug("SyncController::sendJoin - sending initial JOIN HELLO UPD message");var e={cmd:{ns:"video",name:"hello",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}};r.send(e)}else VizbeeSDK.logger.debug("SyncController::sendJoin - NOT sending JOIN HELLO yet",a,d)}function v(){if(a&&d){VizbeeSDK.logger.debug("SyncController::sendOlleh - sending OLLEH UPD message");var e={cmd:{ns:"video",name:"olleh",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}};r.send(e)}else VizbeeSDK.logger.debug("SyncController::sendOlleh - NOT sending Olleh",a,d)}function y(e,t={}){var s,o,a,d;if(!("int"!==e.cmd.type&&e.hstatus&&"SCREEN"==e.hstatus.type||"req"!==e.cmd.type&&"int"!==e.cmd.type))switch(e.cmd.name){case"launch_applet":if(hr.isUndefined(e.cmd.param))return;VizbeeSDK.logger.debug("SyncController::launch_applet - called",e.cmd.param),void 0!==window.VGA&&window.VGA.launch(e.cmd.param);break;case"hello":s={cmd:{ns:"video",name:"hello",type:"rsp"},hstatus:{id:n.deviceId,type:"SCREEN"}};try{"app"!==i.app.state?((d=I()).vstatus&&(s.vstatus=d.vstatus),d.vinfo&&(s.vinfo=d.vinfo),d.vinfoext&&(s.vinfoext=d.vinfoext),s.hstatus.vip="true"):s.hstatus.vip="false","int"==e.cmd.type&&(s.cmd.type="req"),r.send(s)}catch(e){VizbeeSDK.logger.error("SyncController::videoMessgaeHandler -- hello command. error ",e)}break;case"will_start_video":if(VizbeeSDK.logger.debug("SyncController::videoMessageHandler::will_start_video called",e),!(c=e.internal.videoInfo))return;var l=e.internal.videoStartsIn;l=l||0,mr.willStart(c,l);break;case"start_video":VizbeeSDK.logger.debug("SyncController::videoMessageHandler::start_video called",e);var c=e.internal.videoInfo;let p=e.internal.startVideoSource?e.internal.startVideoSource:"default";if(!c)return;"app"!==i.app.state?(VizbeeSDK.logger.debug("SyncController::videoMessageHandler()::start_video -- CALLING VIDEOADAPTER.STOP()"),mr.stop("stop_reason_before_next_video"),setTimeout(function(){VizbeeSDK.logger.debug("SyncController::videoMessageHandler()::start_video -- CALLING START AFTER STOP"),S(c,p)},3e3)):S(c,p);break;case"pause":if("video"!==i.app.state)return void VizbeeSDK.logger.warn("pause requested when not in 'video' state",i.app.state);mr.pause();break;case"play":if("video"!==i.app.state)return void VizbeeSDK.logger.warn("play requested when not in 'video' state",i.app.state);mr.play();break;case"stop":if("app"==i.app.state)return void VizbeeSDK.logger.warn("stop requested when in 'app' state",i.app.state);VizbeeSDK.logger.info("syccontroller:: stop ",e.cmd.param);var u=e.cmd.param||"stop_reason_unknown";mr.stop(u);break;case"exit":s={cmd:{ns:"video",name:"olleh",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}},r.send(s),mr.exit();break;case"olleh":"int"==e.cmd.type&&v();break;case"status":E();break;case"seek":if(i.ad.playing)return VizbeeSDK.logger.debug("1",i.ad),void VizbeeSDK.logger.debug(i.video);if(hr.isUndefined(e.cmd.param))return void VizbeeSDK.logger.debug("2",e);if(o=parseInt(e.cmd.param,10),isNaN(o))return void VizbeeSDK.logger.debug("3",o);if(i.video&&i.video.duration&&(a=i.video.duration,VizbeeSDK.logger.debug("4",o,a),o>a))return;if(o<0)return void VizbeeSDK.logger.debug("5",o);mr.seek(o);break;case"vol_up":"function"==typeof mr.volumeUp&&mr.volumeUp();break;case"vol_down":"function"==typeof mr.volumeDown&&mr.volumeDown();break;case"mute":"function"==typeof mr.mute&&mr.mute(!0);break;case"unmute":"function"==typeof mr.mute&&mr.mute(!1);break;case"set_tracks":"function"==typeof mr.setTracks&&mr.setTracks(e.cmd.param||[]);break;case"event":"function"==typeof mr.onEvent&&e.einfo&&e.einfo.data&&(mr.onEvent(e.einfo),"tv.vizbee.homesso.signin"===e.einfo.type&&function(e,t){b(e.type,m({h:t,b:{payload:e.data}}))}(e.einfo,t))}}function m(e){const t=e.h.ssinfo,i={deviceId:t.REMOTE_DEVICE_ID,deviceType:t.REMOTE_DEVICE_TYPE,friendlyName:t.REMOTE_FRIENDLY_NAME,networkSessionId:t.REMOTE_NETWORK_SESSION_ID};return{payload:e.b.payload,senderInfo:i}}function b(e,t){if(!window.vizbee||!window.vizbee.continuity||!window.vizbee.continuity.xmessages)return void VizbeeSDK.logger.debug("SyncController::sendMessageToMessagingClient - continuity xmessages module not loaded; ignoring message");if(!window.vizbee.continuity.xmessages.VizbeeBicastSessionManager)return void VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: session manager not found");const i=new window.vizbee.continuity.xmessages.VizbeeBicastSessionManager;if(!i)return void VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: unable to create session manager instance");const n=i.getSession();if(!n)return void VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: session not found");const r=n.getMessagingClient();r?r.onReceive(e,t.payload,t.senderInfo):VizbeeSDK.logger.error("SyncController::sendMessageToMessagingClient - Failed to initialize Vizbee session: messaging client not found")}function S(e,t){VizbeeSDK.logger.debug("SyncController::doStartVideo -- called StateManager.reset()",i),i.reset(),VizbeeSDK.logger.debug("SyncController::doStartVideo -- calling setSyncVideoInfo",i,i.getSyncVideoInfo()),i.setSyncVideoInfo(e),i.syncStartVideoSource=t,VizbeeSDK.logger.debug("SyncController::doStartVideo -- calling VideoAdapter.start() with videoInfo",e),mr.start(e)}function _(e){"appIsSet"===e.type?(VizbeeSDK.logger.debug("SyncController::stateHandler appIsSet"),d=!0,f()):E()}function E(){var e;if((e=("app"===i.app.state||"UNKNOWN"===i.video.state?"not sending":"sending")+" | app = "+i.app.state+", video = "+i.video.state+", ad = "+(i.ad&&i.ad.state))!==u&&(u=e,VizbeeSDK.logger.debug("SyncController::sendUpdate -",e)),"app"!==i.app.state)if("UNKNOWN"!==i.video.state)if("PAUSED_BY_AD"!==i.video.state||"UNKNOWN"!==i.ad.state){var t=I();r&&r.send(t)}else VizbeeSDK.logger.debug("SyncController:sendUpdate - unknown video/ad state, not sending. app/video/ad.state: ",i.app.state,i.video.state,i.ad.state);else VizbeeSDK.logger.verbose("SyncController::sendUpdate - UNKNOWN video state, not sending");else"AppStateManager"==i.type&&VizbeeSDK.logger.verbose("SyncController::sendUpdate - in app state, not sending update",i)}function I(){var e,t=i.video,n=i.ad,r=i.getSyncVideoInfo(),s=i.getCurrentVideoInfo(),o={cmd:{name:"status",ns:"video",type:"upd"}};t&&(e=t.volume,t.muted&&(e=0),o.vinfo={id:t.id,url:""},r.id||(r=s),o.vinfo.islive=!1,o.vinfoext={title:"",subtitle:"",imgurl:"",desc:"",videostarttime:0,custommetadata:{},customstreaminfo:{},qos:{}},VizbeeSDK.logger.verbose("SyncController::createStatusMessage:: - ",r,s),s&&s.id&&r&&r.id&&r.id==s.id?(o.vinfo.url=r.videourl,o.vinfo.islive=r.islive,o.vinfoext={title:r.title||"",subtitle:r.subtitle||"",imgurl:r.imgurl||"",desc:r.desc||"",videostarttime:r.starttime||0,custommetadata:r.customMetadata||r.custommetadata,customstreaminfo:r.customStreamInfo||r.customstreaminfo,qos:T(t)}):s&&s.id&&(o.vinfo.url=s.videourl,o.vinfo.islive=s.islive,o.vinfoext={title:s.title||"",subtitle:s.subtitle||"",imgurl:s.imgurl||"",desc:s.desc||"",videostarttime:s.starttime||0,custommetadata:s.customMetadata||s.custommetadata,customstreaminfo:s.customStreamInfo||s.customstreaminfo,qos:T(t)}),o.vinfoext.wasVideoStartedByVizbee=i.wasVideoStartedByVizbee(),o.vstatus={du:parseInt(t.duration,10)||-1,id:t.id,po:parseInt(t.position,10)||-1,st:t.state,vol:parseInt(e),cc:t.cc,tr:t.tr,er:t.error||{}},"Infinity"!=t.duration&&"0"!=t.duration||(o.vstatus.du=0)),n&&t&&"PAUSED_BY_AD"==t.state&&(o.adstatus={du:parseInt(n.duration,10)||-1,id:n.id,po:parseInt(n.position,10)||-1,st:n.state});var a=vr.getVideoInfo();return a&&(a.id&&(o.vinfo=o.vinfo||{},o.vinfo.id=a.id,o.vstatus=o.vstatus||{},o.vstatus.id=a.id),void 0!==a.videourl&&(o.vinfo=o.vinfo||{},o.vinfo.url=a.videourl),void 0!==a.islive&&(o.vinfo=o.vinfo||{},o.vinfo.islive=a.islive),void 0!==a.title&&(o.vinfoext=o.vinfoext||{},o.vinfoext.title=a.title),void 0!==a.subtitle&&(o.vinfoext=o.vinfoext||{},o.vinfoext.subtitle=a.subtitle),void 0!==a.imgurl&&(o.vinfoext=o.vinfoext||{},o.vinfoext.imgurl=a.imgurl),void 0!==a.isdvrsupported&&(o.vinfoext=o.vinfoext||{},o.vinfoext.isdvrsupported=a.isdvrsupported),void 0!==a.state&&(o.vstatus=o.vstatus||{},o.vstatus.st=a.state),void 0!==a.position&&(o.vstatus=o.vstatus||{},o.vstatus.po=parseInt(a.position,10)),void 0!==a.duration&&(o.vstatus=o.vstatus||{},o.vstatus.du=parseInt(a.duration,10))),o}function T(e){if(!e)return{};let t=e.qos||{};return{starttime:e.startTime||0,audiobufferlevel:e.audioBufferLevel,videobufferlevel:e.videoBufferLevel,adPodStartedTimeInMs:t.adPodStartedTimeInMs||0,adPodEndedTimeInMs:t.adPodEndedTimeInMs||0,loadReceivedByAppTimeInMs:t.loadReceivedByAppTimeInMs||0,loadReceivedByPlayerTimeInMs:t.loadReceivedByPlayerTimeInMs||0,metadataLoadedTimeInMs:t.metadataLoadedTimeInMs||0,playerReadyToPlayTimeInMs:t.playerReadyToPlayTimeInMs||0,playbackStartedTimeInMs:t.playbackStartedTimeInMs||0}}},kr=Ft(),wr=at(),Nr=Bt(),Or=Ut(),Rr=Kt(),Mr=function(){if(or)return sr;or=1;var e,t,i=E(),n=new(0,ot().EventEmitter),r={preparing:!1,playing:!1,alladscomplete:!1},s=-1,o=-1,a=!1;function d(e){var n={type:"ad",position:-1,duration:-1,preparing:r.preparing,playing:r.playing,alladscomplete:r.alladscomplete};return r.playing&&(o>0?(n.position=s,n.duration=o,VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::Status using app ad timing — po:",s,"du:",o)):t&&(n.position=1e3*t.currentTime(),n.duration=1e3*t.getDuration(),VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::Status using videoEl — po:",n.position,"du:",n.duration))),i.extend(n,e)}function l(e){var s,o,a=!i.contains(["timeupdate"],e.type);(r.preparing||r.playing)&&(s=new d,"timeupdate"!==e.type&&VizbeeSDK.logger.debug("AdAdapter::handleAdEvent() - not a timeupdate event",e.type),"preparing"===e.type&&(o="LOADING",s.id="UNKNOWN"),"play"===e.type&&(o="LOADING"),"playing"===e.type&&(o="PLAYING",t&&t.basePlayer&&t.basePlayer.videoInfo&&t.basePlayer.videoInfo.src&&(s.id=t.basePlayer.videoInfo.src)),"error"===e.type&&(o="INTERRUPTED",r.playing=!1),"ended"===e.type&&(o="FINISHED",r.playing=!1),s.playing=r.playing,o&&(s.state=o),n.emit("ad",s,a))}function c(e){var t=e.type||"UNKNOWN";VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::adsManagerHandleStateChange state:",t,"data:",e.data),-1!=["ad-pod-start","ad-pod-end","ad-start","ad-playing"].indexOf(t)&&(r.preparing=!1,r.playing=!1,"ad-pod-start"===t?(a=!1,r.preparing=!0,l({type:"preparing"})):"ad-start"===t?(a=!1,l({type:"play"})):"ad-playing"===t?(r.playing=!0,e.data&&(void 0!==e.data.duration&&e.data.duration>0&&(o=e.data.duration),void 0!==e.data.position&&e.data.position>=0&&(s=e.data.position),VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::ad-playing stored timing — po:",s,"du:",o))):("ad-pod-end"===t&&(r.playing=!1,r.alladscomplete=!0,s=-1,o=-1),n.emit("ad",new d({position:-1,duration:-1,state:"UNKNOWN",preparing:r.preparing,playing:r.playing}),!1)))}function u(i){VizbeeSDK.logger.debug("VIZBEE: AdAdapter.setAdVideo()",i),i&&((t=i).onError=function(e){r.playing&&(l({type:"error"}),a=!1)},t.onEnded=function(){r.playing&&(l({type:"ended"}),a=!1)},t.onTimeUpdate=function(e){r.playing&&(a?l({type:"timeupdate"}):(a=!0,l({type:"playing"})))},e||p(t))}function p(t){VizbeeSDK.logger.debug("VIZBEE: AdAdapter.setAdsManager()",t),(e=t).onEvent=c,u(e)}return sr={setAdVideo:u,setAdsManager:p,reset:function(){r.preparing=!1,r.playing=!1,r.alladscomplete=!1,s=-1,o=-1,n.emit("ad",new d({position:-1,duration:-1,state:"UNKNOWN"}),!1)},addListener:function(e){n.addListener("ad",e)},removeListener:function(e){n.removeListener("ad",e)}}}(),Lr=function(){if(cr)return lr;cr=1,E();var e=function(){if(dr)return ar;dr=1;var e=ot().EventEmitter;const t="ad";var i=new e,n={type:t,state:"UNKNOWN",id:"UNKNOWN",position:-1,duration:-1,playing:!1,adPodStarted:!1,adPodsPlayedDuration:0,totalAdPodsDuration:0};return ar={adStatus:n,reset:function(){n.state="UNKNOWN",n.id="UNKNOWN",n.position=-1,n.duration=-1,n.playing=!1,n.adPodStarted=!1},resetTotalAdPodsDuration:function(){n.adPodsPlayedDuration=0,n.totalAdPodsDuration=0},addListener:function(e){i.addListener(t,e)},removeListener:function(e){i.removeListener(t,e)},notify:function(e){i.emit(t,n,e)}}}();const t=["loadedmetadata","play","playing","timeupdate","error","ended"];var i,n;function r(t){if(e.adStatus.adPodStarted){var r="LOADING";"loadedmetadata"==t.type||"play"==t.type?r="LOADING":"playing"==t.type?(e.adStatus.id=i.src,r="PLAYING"):"timeupdate"==t.type?r="PLAYING":"error"==t.type?r="FAILED":("ended"==t.type||i.ended)&&(r="FINISHED");var s=!1;r!=e.adStatus.state&&(s=!0,e.adStatus.state=r),e.adStatus.playing&&e.adStatus.duration>0&&n>=0?e.adStatus.position=1e3*i.currentTime-n:e.adStatus.position=-1,e.notify(s)}}function s(){e.reset(),n=-1}function o(){s(),e.notify()}return lr={setAdVideo:function(e){!function(e){e&&t.forEach(function(t){e.removeEventListener(t,r,!1)})}(i),function(e){e&&t.forEach(function(t){e.addEventListener(t,r,!1)})}(i=e)},setAdPodStart:function(t,i,n){s(),e.adStatus.adPodStarted=!0},setAdPodEnd:function(){o()},setTotalAdPodsDuration:function(t){e.adStatus.totalAdPodsDuration=t||0,e.notify(!1)},setAdStart:function(t,i){e.adStatus.playing=!0,n=t,e.adStatus.duration=i,e.adStatus.adPodsPlayedDuration+=i},setAdEnd:function(){e.adStatus.state="FINISHED",e.notify(!0),e.adStatus.playing=!1,n=-1,e.adStatus.duration=-1},getAdStatus:function(){return e.adStatus},reset:o,resetTotalAdPodsDuration:function(){e.resetTotalAdPodsDuration()},addListener:function(t){e.addListener(t)},removeListener:function(t){e.removeListener(t)}}}(),xr=Gt(),zr=(pr||(pr=1,ur={getDeviceID:function(e,t,i){if(VizbeeTV&&VizbeeTV.tv)VizbeeTV.tv.uniqueDeviceID(function(i){switch(VizbeeSDK.logger.debug("Device::getDeviceID - DeviceIDAlgorithm = "+VizbeeTV.tv.deviceIDAlgorithm),VizbeeTV.tv.deviceIDAlgorithm){case"VTV_SESSION_ID":case"VTV_DEFAULT":case"VTV_URL_PARAMS":i=e.platform+":"+i;break;case"VTV_INTERNAL_IP":i=e.platform+":"+e.externalIp.toLowerCase()+":"+i}VizbeeSDK.logger.debug("Device::getDeviceID - deviceID = "+i),t(i)},function(e){VizbeeSDK.logger.error("PROD","C:001 failed to fetch deviceId, halting SDK initialization",e),i&&i(e)},e);else{var n="VizbeeTV framework not initialized yet, halting SDK initialization";VizbeeSDK.logger.error("PROD","C:002",n),i&&i(n)}}}),ur),Kr=void 0,Ur=void 0,Fr=!1,Br=[],Gr="vzb0000000";function Hr(){if(Vr&&Vr.features&&Vr.features.shouldSyncDisconnectOnBackground){if(Fr)return;Kr?Kr.isConnected()||(VizbeeSDK.logger.i("SDK","onForeground","connecting VGA"),Fr=!0,qr(Gr,function(){Fr=!1,Ur&&!Ur.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET after VGA ",Tr.id),Fr=!0,qr(Tr.id,function(){Fr=!1}))})):Ur&&!Ur.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET ",Tr.id),Fr=!0,qr(Tr.id,function(){Fr=!1}))}}function Wr(){return VizbeeSDK.logger.i("SDK","onBackground"),Vr&&Vr.features&&Vr.features.shouldExitOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","exiting the app"),void VizbeeTV.tv.exit()):Vr&&Vr.features&&Vr.features.shouldSyncDisconnectOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","disconnecting from sync"),Kr&&Kr.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting VGA"),Kr.disconnect()),Ur&&Ur.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting APPLET"),Ur.disconnect()),void(Fr=!1)):void Zr()}function jr(e){VizbeeSDK.logger.i("SDK","onEnd","sending olleh"),e&&e.isTeardown&&(Kr&&Kr.enableSynchronousPublish(),Ur&&Ur.enableSynchronousPublish()),Zr()}function qr(e,t){et.setStage(Fe),Ar.getConfig({appId:e||Tr.id,deviceId:"",platform:VizbeeTV.tv.cloudPlatformName,platformModel:VizbeeTV.tv.platformModel,hostProxy:Tr.configServiceProxyHost},function(e){Vr=e,VizbeeSDK.logger.d("SDK","getConfig","got config=",Vr),et.setConfig(Vr),Vr.customAttributesForMetrics=Tr.customAttributesForMetrics,Vr.features&&Vr.features.enableIpv6Lookup?Dr.getIpv6Address(function(e){VizbeeSDK.logger.d("SDK","getIpv6Address","got response=",e),Vr.ipv6Address=e;try{Yr(Vr,t)}catch(e){throw et.report(He,qe,e),e}}):(VizbeeSDK.logger.d("SDK","getIpv6Address","skipped - enableIpv6Lookup not set in screen config"),Yr(Vr,t))})}function Yr(e,t){et.setStage(Be),zr.getDeviceID(e,function(i){if(VizbeeSDK.logger.d("SDK","onConfigReady","using deviceid="+i),!function(e){if(!e||"string"!=typeof e)return!1;var t=e.split(":"),i=t[t.length-1];if(!i)return!1;var n=i.toLowerCase();return"unknown_device_id"!==n&&"0.0.0.0"!==n&&"127.0.0.1"!==n&&"localhost"!==n&&"undefined"!==n&&"null"!==n}(i))return VizbeeSDK.logger.e("SDK","onConfigReady","PROD - SDK init aborted: deviceId is a default/sentinel value; sync will not be established",i),et.report(Be,"DEVICE_ID_INVALID",i),Fr=!1,void(t&&t(void 0));e.deviceId=i,function(e,t){et.setStage(Ge),function(e){if(e&&e.debug&&e.debug.clients&&e.debug.clients.length>0&&e.debug.server)for(var t=0;t<e.debug.clients.length;t++){var i=e.debug.clients[t];if(i.ip&&i.ip==e.externalIp){var n=e.appId+":"+e.platform+":"+e.externalIp,r=i.aka||n;r="["+r+"]",Pe.enableRemoteLogging(e.debug.server,r),window.VizbeeSDK&&window.VizbeeSDK.logger.setLevel(window.VizbeeSDK.logger.LEVEL.DEBUG),window.VizbeeTV&&window.VizbeeTV.logger.setLevel(window.VizbeeTV.logger.LEVEL.DEBUG),window.VGA&&window.VGA.logger.setLevel(window.VGA.logger.LEVEL.DEBUG)}}}(e);try{!function(e){e.appId==Gr||e.features&&e.features.targetAppType==Yn?(Gr=e.appId,Kr||(Kr=new Cr(e,!0)),Kr.connect(function(e){e?VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connected VGA"):VizbeeSDK.logger.e("SDK","onConfigAndDeviceIDReady","failed to connect VGA")})):(Ur||(VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","creating appletSyncController"),Ur=new Cr(e,!1),Pr.each(Br,e=>{e()})),VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connecting appletSyncController"),Ur.connect(function(e){e?VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connected APPLET"):VizbeeSDK.logger.e("SDK","onConfigAndDeviceIDReady","failed to connect APPLET")}))}(e)}catch(e){throw et.report(Ge,"SYNC_INIT_EXCEPTION",e),e}t&&t(e)}(e,t)},function(e){VizbeeSDK.logger.e("SDK","onConfigReady","PROD - SDK init aborted: deviceId fetch failed; sync will not be established",e),et.report(Be,VizbeeTV&&VizbeeTV.tv?"DEVICE_ID_FETCH_FAILED":"VIZBEETV_NOT_INITIALIZED",e,e&&e.failureInfo),Fr=!1,t&&t(void 0)})}function Jr(e){VizbeeSDK.logger.d("SDK","setApp"),wr.setApp(e)}function Qr(e){VizbeeSDK.logger.d("SDK","setVideo","video=",e),Or.setVideo(e)}function $r(e){Ir={vzb_ad_ima:null,vzb_ad_ssai:Lr,vzb_ad_ssai_avplay:null,vzb_ad_default:Mr}[e.toLowerCase()],Or.setAdAdapter(Ir)}function Zr(){xr.send({type:"sync_proxy_video_cmds",cmd:{ns:"video",name:"olleh",type:"int"}})}var Xr={ContinuityContext:Er,QueueBase:null,QueueManager:null,QueueDelegate:null,QueueDelegateFactory:null},es={VERSION:"7.9.1",wasVideoStartedByVizbee:function(){return kr&&kr.wasVideoStartedByVizbee()},init:function(e){VizbeeSDK.logger.i("SDK","init"),VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.addHandler("onForeground",Hr),VizbeeTV.tv.appLifeCycleManager.addHandler("onBackground",Wr),VizbeeTV.tv.appLifeCycleManager.addHandler("onEnd",jr)),Tr=e,VizbeeSDK.logger.i("SDK","onStart"),et.setStage(Ue),Tr&&Tr.id?(function(e){var t;VizbeeSDK.logger.d("SDK","handleInitOptions"),e.video&&Qr(e.video),e.app&&Jr(e.app),e.videoAdapter&&(t=e.videoAdapter,VizbeeSDK.logger.d("SDK","setHostVideoAdapter","video=",t),Rr.setVideoAdapter(t)),e.adType&&$r(e.adType),e.VGA&&e.isVGA&&Nr.setVGA(e.VGA)}(Tr),Or.init(),qr()):et.report(Ue,"MISSING_APP_ID")},setApp:Jr,setVideo:Qr,setVideoGuid:function(e,t){Or.setId(e,t)},setVideoInfo:function(e){VizbeeSDK.logger.d("SDK","setVideoInfo","videoInfo=",e),Or.setVideoInfo(e)},setVideoStop:function(){Or.setVideoStop()},setAdsVideo:function(e){VizbeeSDK.logger.d("SDK","setAdsVideo","video=",e),Ir?Ir.setAdVideo(e):VizbeeSDK.logger.d("SDK","setAdsVideo","AdAdapter not configured; skipping")},getAdsAdapter:function(){return Ir},setAdType:$r,sendXMessage:function(e,t,i){if(!Ur)return void VizbeeSDK.logger.e("XMessages",this.constructor.name,"sendXMessage","appletSyncController not initialized");if(Pr.get(Vr,["features","useXMessagesFormat"])){let i={type:"sync_proxy_video_cmds",cmd:{type:"req",ns:t,name:"x",param:""},payload:e};return VizbeeSDK.logger.d("XMessages",this.constructor.name,"sendXMessage",`sending message: ${JSON.stringify(i)} in new format to sync controller`),void xr.send(i)}let n={type:"sync_proxy_video_cmds",cmd:{type:"req",ns:"video",name:"event",param:""},einfo:{type:t,data:e}};VizbeeSDK.logger.d("XMessages",this.constructor.name,"sendXMessage",`sending message: ${JSON.stringify(n)} in old format to sync controller`),xr.send(n)},syncProxy:xr,addSyncReadyListener:function(e){Br.push(e)},removeSyncReadyListener:function(e){Br=Pr.without(Br,e)},getSyncController:function(){return Ur},getMetricsManager:function(){return qn},wrapVideoCallbacks:Or.wrapCallbacks,addVideoEventListener:Or.addEventListener,removeVideoEventListener:Or.removeEventListener,reset:function(){VizbeeSDK.logger.d("SDK","reset");try{Ur&&(Ur.disconnect(),Ur=void 0)}catch(e){VizbeeSDK.logger.e("SDK","reset","error disconnecting appletSyncController.",e)}try{kr.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppStateManager",e)}try{wr.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppAdapter",e)}try{Ir&&Ir.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AdAdapter",e)}try{Or.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset"," error resetting VideoAdapter",e)}try{Rr.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting HostVideoAdapter",e)}try{xr.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting SyncProxy",e)}try{VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.removeHandler("onForeground",Hr),VizbeeTV.tv.appLifeCycleManager.removeHandler("onBackground",Wr),VizbeeTV.tv.appLifeCycleManager.removeHandler("onEnd",jr))}catch(e){VizbeeSDK.logger.e("SDK","reset","error removing app lifecycle handlers",e)}},framework:Xr};window.VizbeeSDK||(window.VizbeeSDK={},VizbeeSDK.logger||(VizbeeSDK.logger=new Pe,VizbeeSDK.logger.setPrefix("[Vizbee]")));var ts=window.VZB;ts=es,window.VZB=ts;class is{constructor(){this.platformType="",this.platformConfig={},this.appAdapter=void 0,this.vgaAdapter=void 0,this.videoAdapter=void 0,this.adAdapter=void 0,this.vzbOptions={}}setOptions(e){e||(e={}),this.vzbOptions=e}getOptions(){return this.vzbOptions}initAppOnPlatform(e,t,i,n){this.appAdapter=t.appAdapter||t,this.vgaAdapter=t.vgaAdapter,this.videoAdapter=t.videoAdapter,this.adAdapter=t.adAdapter,this.platformType=i,this.platformConfig=n,this.platformConfig.appId=e,null==this.platformConfig.standalone&&(this.platformConfig.standalone=!0);try{VizbeeTV.init(this.platformType,this.platformConfig)}catch(e){throw et.report(Ke,"PLATFORM_INIT_FAILED",this.platformType+" - "+(e&&e.message)),e}var r=this.appAdapter.startVideo||function(){},s=this;this.appAdapter.startVideo=function(e,t){t=t||0,s.platformConfig.standalone||s.setVideoGuid(e.id,e.isLive||e.islive),r(e,t)};var o={id:e,app:this.appAdapter,videoAdapter:this.videoAdapter,adAdapter:this.adAdapter,customAttributesForMetrics:{}};this.vgaAdapter?(o.isVGA=!0,o.VGA=this.vgaAdapter):o.video=VizbeeTV.tv.player,o.customAttributesForMetrics=Object.assign(o.customAttributesForMetrics,this.platformConfig.customAttributesForMetrics,this.vzbOptions.customAttributesForMetrics),this.vzbOptions.configServiceProxyHost&&(o.configServiceProxyHost=this.vzbOptions.configServiceProxyHost),VZB.init(o)}setAdAdapterType(e){VZB.setAdType(e)}getAdsAdapter(){return VZB.getAdsAdapter()}setAdsVideo(e){VZB.setAdsVideo(e)}setVideoElement(e){if(!e)return"undefined"!=typeof VizbeeSDK&&VizbeeSDK.logger&&VizbeeSDK.logger.warn("BaseAPIWrapper::setVideoElement - INVALID newVideoElement"),!1;if(!this.platformConfig)return"undefined"!=typeof VizbeeSDK&&VizbeeSDK.logger&&VizbeeSDK.logger.warn("BaseAPIWrapper::setVideoElement - SDK not initialized"),!1;if(this.platformConfig.videoElement===e)return!0;this.platformConfig.videoElement=e;var t=Object.assign({},this.platformConfig,{standalone:!0});return"undefined"!=typeof VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player&&"function"==typeof VizbeeTV.tv.player.reconstruct&&VizbeeTV.tv.player.reconstruct(t),this.setAdsVideo(e),!0}setVideoGuid(e,t){VZB.setVideoGuid(e,t)}setVideoInfo(e){VZB.setVideoInfo(e),this.setVideoGuid(e.id||e.videourl,e.islive)}setVideoStop(){VZB.setVideoStop()}}const ns={};class rs extends is{get VERSION(){return window.VZB?window.VZB.VERSION:""}init(e,t,i,n){et.start(e);let r=Date.now(),s=Ie.getPlatformType();if(s)try{this.initAppOnPlatform(e,t,s,i,t.mediaManagerAdapter,n)}catch(e){throw et.report(He,qe,e),e}else et.report(Ke,"PLATFORM_NOT_DETECTED","detection wait ms = "+(Date.now()-r))}initAppOnPlatform(e,t,i,n,r,s){i=i.toLowerCase(),ns[i]&&!t.vgaAdapter?(this._apiWrapper=new ns[i],this._apiWrapper.setOptions(s),this._apiWrapper.initAppOnPlatform(e,t,i,n,r)):(this._apiWrapper=new is,this._apiWrapper.setOptions(s),this._apiWrapper.initAppOnPlatform(e,t,i,n))}setVideoGuid(e,t){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoGuid(e,t),!0}setVideoInfo(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoInfo(e),!0}setVideoStop(){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoStop(),!0}getAdsManager(){if(this._isAPIWrapperInitialized())return this._apiWrapper.getAdsManager()}setAdsVideo(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setAdsVideo(e),!0}setVideoElement(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setVideoElement(e)}setAdAdapterType(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.setAdAdapterType(e),!0}wrapAVPlayerListener(e){if(this._isAPIWrapperInitialized())return this._apiWrapper.wrapAVPlayerListener(e)}_isAPIWrapperInitialized(){return null!=this._apiWrapper}}let ss,os,as;class ds{constructor(){this.virtualAPIWrapper=Qs,this.vzbOptions={}}static getInstance(){return null==ss&&(ss=new ds),ss}startWithOptions(e,t){this.vzbOptions=t||{},this.start(e)}start(e){this.isValidAppId(e)&&this.virtualAPIWrapper.init(e,{},{},this.vzbOptions)}isValidAppId(e){if("string"!=typeof e)return!1;let t=new RegExp("^vzb[0-9]+$"),i=new RegExp("^vzb(-[A-Za-z]+)+-[0-9]+$");return t.test(e)||i.test(e)}}class ls{constructor(){this._configServiceProxyHost=void 0,this._customAttributesForMetrics=void 0}get configServiceProxyHost(){return this._configServiceProxyHost}set configServiceProxyHost(e){this._configServiceProxyHost=e}get customAttributesForMetrics(){return this._customAttributesForMetrics}set customAttributesForMetrics(e){this._customAttributesForMetrics=e}}class cs{get ContinuityContext(){return ds}get ContinuityOptions(){return ls}}class us{constructor(){this.deeplinkHandler=void 0,this.vizbeeEventHandler=void 0,this.vizbeeSigninEventHandler=void 0}setSignInHandler(e){"function"==typeof e?this.vizbeeSigninEventHandler=e:vizbee.logger.warn(this.constructor.name+"::setSignInHandler - NO SIGNIN Handler implemented by HostApp")}setDeeplinkHandler(e){"function"==typeof e?this.deeplinkHandler=e:vizbee.logger.warn(this.constructor.name+"::setDeeplinkHandler - NO DEEPLINK Handler implemented by HostApp")}setVizbeeEventHandler(e){"function"==typeof e?this.vizbeeEventHandler=e:vizbee.logger.warn(this.constructor.name+"::setVizbeeEventHandler - NO Event Handler implemented by HostApp")}setVizbeeSigninEventHandler(e){"function"==typeof e?this.vizbeeSigninEventHandler=e:vizbee.logger.warn(this.constructor.name+"::setVizbeeSigninEventHandler - NO Event Handler implemented by HostApp")}}class ps{static get AD_POD_WAITING(){return"awaiting-ad-pod"}static get AD_POD_START(){return"ad-pod-start"}static get AD_PREPARING(){return"ad-preparing"}static get AD_START(){return"ad-start"}static get AD_PLAYING(){return"ad-playing"}static get AD_PAUSED(){return"ad-paused"}static get AD_END(){return"ad-end"}static get AD_POD_END(){return"ad-pod-end"}static get AD_ERROR(){return"ad-error"}}class hs{constructor(e,t){this._eventType=e,this._eventData=t}set eventType(e){this._eventType=e}get eventType(){return this._eventType}set eventData(e){this._eventData=e}get eventData(){return this._eventData}}class gs{constructor(e,t){this.type=e,this.data=t}}class fs{constructor(e,t){this.adType=e,this.playerElement=t,this.vtvPlayerEvent=new gs}updateAdStatus(e){this._isValidAdStatus(e)?this._handleAdStatus(e):vizbee.logger.verbose("AdAdapter::updateAdStatus - invalid ad status")}_isValidAdStatus(e){return e instanceof hs?-1!=[ps.AD_POD_WAITING,ps.AD_PREPARING,ps.AD_POD_START,ps.AD_POD_END,ps.AD_START,ps.AD_PLAYING,ps.AD_PAUSED,ps.AD_END,ps.AD_ERROR].indexOf(e.eventType)||(vizbee.logger.warn(`AdAdapter::_isValidAdStatus - adStatus event type is invalid: ${e.eventType}`),!1):(vizbee.logger.warn("AdAdapter::_isValidAdStatus - adStatus is not an instance of vizbee.continuity.messages.AdStatus"),!1)}_handleAdStatus(e){e?(vizbee.logger.verbose(`AdAdapter::_handleAdStatus - eventType: ${e.eventType}`),this.vtvPlayerEvent.type=e.eventType,this.vtvPlayerEvent.data=e.eventData||{},VizbeeTV.tv.player.dispatchOnEvent(this.vtvPlayerEvent)):vizbee.logger.warn("AdAdapter::_handleAdStatus - invalid ad status")}}class vs{constructor(e,t){this.playerType=e,this.playerElement=t,this.playHandler=void 0,this.pauseHandler=void 0,this.seekHandler=void 0,this.stopHandler=void 0,this.videoInfoGetter=void 0,this.tracksGetHandler=void 0,this.enabledTracksGetHandler=void 0,this.enableTracksHandler=void 0,this.disableTracksHandler=void 0,this.vizbeeEventHandler=void 0}setPlayerType(e){e&&(this.playerType=e)}setPlayerElement(e){e&&(this.playerElement=e)}updateVideoInfo(e){window.vizbee&&vizbee.continuity.ContinuityContext.getInstance().setVideoInfo(e)}setVideoInfoGetter(e){"function"==typeof e&&(this.videoInfoGetter=e)}getVideoInfo(){if(this.videoInfoGetter)return this.videoInfoGetter()}setPlayHandler(e){"function"==typeof e&&(this.playHandler=e)}setPauseHandler(e){"function"==typeof e&&(this.pauseHandler=e)}setSeekHandler(e){"function"==typeof e&&(this.seekHandler=e)}setStopHandler(e){"function"==typeof e&&(this.stopHandler=e)}getTracksHandler(e){"function"==typeof e&&(this.tracksGetHandler=e)}getEnabledTracksHandler(e){"function"==typeof e&&(this.enabledTracksGetHandler=e)}setAvailableTracksGetter(e){"function"==typeof e&&(this.tracksGetHandler=e)}setEnabledTracksGetter(e){"function"==typeof e&&(this.enabledTracksGetHandler=e)}setEnableTracksHandler(e){"function"==typeof e&&(this.enableTracksHandler=e)}setDisableTracksHandler(e){"function"==typeof e&&(this.disableTracksHandler=e)}setVizbeeEventHandler(e){"function"==typeof e&&(this.vizbeeEventHandler=e)}}class ys{static get UNKNOWN(){return"unknown"}static get HTML(){return"html"}static get AVPLAYER(){return"avplayer"}static get BITMOVIN(){return"bitmovin"}static get VIDEOJS(){return"videojs"}static get THEO(){return"theo"}static get SHAKA(){return"shaka"}}class ms{static get UNKNOWN(){return"unknown"}static get SSAI(){return"ssai"}static get CSAI(){return"csai"}}class bs{constructor(){this._guid="",this._isLive=!1,this._startTime=0,this._videoUrl="",this._deeplink="",this._imgUrl="",this._title="",this._subtitle="",this._desc="",this._tracks=[],this._cuepoints=[],this._customStreamInfo=void 0,this._customMetadata=void 0}toJson(){let e={};return e.id=this._guid,e.islive=this._isLive,e.starttime=this._startTime,e.videourl=this._videoUrl,e.deeplink=this._deeplink,e.imgurl=this._imgUrl,e.title=this._title,e.subtitle=this._subtitle,e.desc=this._desc,e.tracks=this._tracks,e.cuepoints=this._cuepoints,e.customstreaminfo=this._customStreamInfo,e.custommetadata=this._customMetadata,e}fromJson(e){e?(this._guid=e.id,this._isLive=e.islive,this._startTime=e.starttime,this._videoUrl=e.videourl,this._deeplink=void 0!==e.deeplink&&null!==e.deeplink?e.deeplink:"",this._imgUrl=e.imgurl,this._title=e.title,this._subtitle=e.subtitle,this._desc=e.desc,this._tracks=e.tracks,this._cuepoints=e.cuepoints,this._customStreamInfo=e.customstreaminfo,this._customMetadata=e.custommetadata):vizbee.logger.debug(this.constructor.name+"::toJson - invalid syncVideoInfo")}set isLive(e){this._isLive=e}get isLive(){return this._isLive}set guid(e){this._guid=e}get guid(){return this._guid}set videoUrl(e){this._videoUrl=e}get videoUrl(){return this._videoUrl}set deeplink(e){this._deeplink=e}get deeplink(){return this._deeplink}set imgUrl(e){this._imgUrl=e}get imgUrl(){return this._imgUrl}set title(e){this._title=e}get title(){return this._title}set subtitle(e){this._subtitle=e}get subtitle(){return this._subtitle}set desc(e){this._desc=e}get desc(){return this._desc}set startTime(e){this._startTime=e}get startTime(){return this._startTime}set tracks(e){this._tracks=e}get tracks(){return this._tracks}set cuepoints(e){this._cuepoints=e}get cuepoints(){return this._cuepoints}set customStreamInfo(e){this._customStreamInfo=e}get customStreamInfo(){return this._customStreamInfo}set customMetadata(e){this._customMetadata=e}get customMetadata(){return this._customMetadata}}class Ss{static get IDLE(){return"idle"}static get PREPARING(){return"preparing"}static get LOADING(){return"loading"}static get STARTED(){return"started"}static get PLAYING(){return"playing"}static get PAUSED(){return"paused"}static get BUFFERING(){return"buffering"}static get INTERRUPTED(){return"interrupted"}static get ENDED(){return"ended"}static get ERROR(){return"error"}}class _s{constructor(){this._guid="",this._state=Ss.IDLE,this._currentPosition=-1,this._duration=-1,this._isLive=!1,this._isDvrSupported=!1,this._title="",this._subtitle="",this._videoUrl="",this._imgUrl=""}set guid(e){this._guid=e}get guid(){return this._guid}set state(e){this._state=e}get state(){return this._state}set currentPosition(e){this._currentPosition=e}get currentPosition(){return this._currentPosition}set duration(e){this._duration=e}get duration(){return this._duration}set isLive(e){this._isLive=e}get isLive(){return this._isLive}set isDvrSupported(e){this._isDvrSupported=e}get isDvrSupported(){return this._isDvrSupported}set title(e){this._title=e}get title(){return this._title}set subtitle(e){this._subtitle=e}get subtitle(){return this._subtitle}set videoUrl(e){this._videoUrl=e}get videoUrl(){return this._videoUrl}set imgUrl(e){this._imgUrl=e}get imgUrl(){return this._imgUrl}}class Es{constructor(){this._type="",this._data=void 0}set type(e){this._type=e}get type(){return this._type}set data(e){this._data=e}get data(){return this._data}}class Is extends ds{constructor(){super(),this.appAdapter=new us,this.playerAdapter=void 0,this.adAdapter=void 0,this.adType=void 0}static getInstance(){return null==os&&(os=new Is,vizbee.logger.d(this.constructor.name,"getInstance","created")),os}getAppAdapter(){return this.appAdapter}setAppAdapter(e){e instanceof us&&(this.appAdapter=e)}getPlayerAdapter(){return this.playerAdapter}setPlayerAdapter(e){if(!this._isPlatformPlayerInitialized())return vizbee.logger.w("DefaultContinuityContext::setPlayerAdapter - Vizbee platform player not initialized"),!1;if(!this._isValidPlayerAdapter(e))return vizbee.logger.w("DefaultContinuityContext::setPlayerAdapter - playerAdapter should be valid and of type vizbee.continuity.adapters.PlayerAdapter"),!1;this.playerAdapter=e;let t=this._buildPlatformConfig(e);return VizbeeTV.tv.player.reconstruct(t),this._setAdAdapter(),!0}removePlayerAdapter(e){return this._isPlatformPlayerInitialized()?(this.stopVideo(),this.playerAdapter=void 0,!0):(vizbee.logger.w(this.constructor.name,"resetPlayerAdapter","Vizbee platform player not initialized"),!1)}setPlayerAdapterWithVideoInfo(e,t){return!!this.setPlayerAdapter(e)&&this.setVideoInfo(t)}setVideoInfo(e){return!!this._isValidVideoInfo(e)&&this.virtualAPIWrapper.setVideoInfo(e.toJson())}getVideoInfo(){if(this.playerAdapter&&this.playerAdapter.getVideoInfo){let e=this.playerAdapter.getVideoInfo();if(e instanceof _s)return e}}getAdAdapter(e){return this.adAdapter}setAdAdapter(e){return e instanceof fs?this._isValidAdType(e.adType)?(this.adAdapter=e,this.setAdType(ms.CSAI),void this._setAdAdapter()):(vizbee.logger.w("DefaultContinuityContext::setAdAdapter - adAdapter.adType is INVALID"),!1):(vizbee.logger.w("DefaultContinuityContext::setAdAdapter - AdAdapter should be of type vizbee.continuity.adapters.AdAdapter"),!1)}removeAdAdapter(e){this.adAdapter=void 0}setAdType(e){this._isValidAdType(e)&&(this.adType=e,this._setAdAdapter())}start(e){if(!this.isValidAppId(e))return;let t={};t.appAdapter={startVideo:e=>{if(this.appAdapter&&this.appAdapter.deeplinkHandler){let t=new bs;t.fromJson(e),this.appAdapter.deeplinkHandler(t)}else vizbee.logger.w(this.constructor.name,"startVideo","NO DEEPLINK HANDLER")},onEvent:e=>{if(this.appAdapter&&this.appAdapter.vizbeeSigninEventHandler&&e&&"tv.vizbee.homesign.signin"===e.type){let t=new Es;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeSigninEventHandler(t)}if(this.appAdapter&&this.appAdapter.vizbeeEventHandler&&e){let t=new Es;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeEventHandler(t)}if(this.playerAdapter&&this.playerAdapter.vizbeeEventHandler&&e){let t=new Es;t.type=e.type,t.data=e.data,this.playerAdapter.vizbeeEventHandler(t)}},playVideo:()=>!(!this.playerAdapter||!this.playerAdapter.playHandler||(this.playerAdapter.playHandler(),0)),pauseVideo:()=>!(!this.playerAdapter||!this.playerAdapter.pauseHandler||(this.playerAdapter.pauseHandler(),0)),seekVideo:e=>!(!this.playerAdapter||!this.playerAdapter.seekHandler||(this.playerAdapter.seekHandler(e),0)),stopVideo:e=>!(!this.playerAdapter||!this.playerAdapter.stopHandler||(this.playerAdapter.stopHandler(e),0)),getTracks:()=>!(!this.playerAdapter||!this.playerAdapter.tracksGetHandler)&&this.playerAdapter.tracksGetHandler(),getEnabledTracks:()=>!(!this.playerAdapter||!this.playerAdapter.enabledTracksGetHandler)&&this.playerAdapter.enabledTracksGetHandler(),enableTracks:e=>!(!this.playerAdapter||!this.playerAdapter.enableTracksHandler||(this.playerAdapter.enableTracksHandler(e),0)),disableTracks:e=>!(!this.playerAdapter||!this.playerAdapter.disableTracksHandler||(this.playerAdapter.disableTracksHandler(e),0)),getVideoInfo:()=>this._buildSyncVideoInfo()},this.virtualAPIWrapper.init(e,t,{},this.vzbOptions)}stopVideo(){vizbee.logger.d(this.constructor.name,"stopVideo"),this.virtualAPIWrapper&&this.virtualAPIWrapper.setVideoStop&&(vizbee.logger.d(this.constructor.name,"stopVideo","calling setVideoStop"),this.virtualAPIWrapper.setVideoStop())}_buildPlatformConfig(e){let t={standalone:!0,videoElement:e.playerElement,vtvPlayerListConfig:[{type:"native"}]};return e.playerType==ys.BITMOVIN&&(t.vtvPlayerListConfig=[{type:"bitmovin"}]),e.playerType==ys.VIDEOJS&&(t.vtvPlayerListConfig=[{type:"videojs"}]),e.playerType==ys.THEO&&(t.vtvPlayerListConfig=[{type:"theo"}]),e.playerType==ys.SHAKA&&(t.vtvPlayerListConfig=[{type:"shaka"}]),t}_isValidVideoInfo(e){return e instanceof bs||(vizbee.logger.w(this.constructor.name,"_isValidVideoInfo","videoInfo should be of type vizbee.continuity.messages.VideoInfo"),!1)}_isValidPlayerAdapter(e){return e instanceof vs?!(e&&!e.playerElement&&(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should contain playerElement"),1)):(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should be of type vizbee.continuity.adapters.PlayerAdapter"),!1)}_isPlatformInitialized(){return VizbeeTV&&VizbeeTV.tv}_isPlatformPlayerInitialized(){return this._isPlatformInitialized()&&VizbeeTV.tv.player}_isValidAdType(e){return e?e==ms.SSAI||e==ms.CSAI||(vizbee.logger.w(`DefaultContinuityContext::_isValidAdType - adType is invalid: ${e}`),!1):(vizbee.logger.w("DefaultContinuityContext::_isValidAdType - adType is undefined"),!1)}_mapPlayerStateToSyncState(e){return{idle:"UNKNOWN",preparing:"UNKNOWN",loading:"BUFFERING",started:"PLAYING",playing:"PLAYING",paused:"PAUSED_BY_USER",buffering:"BUFFERING",interrupted:"INTERRUPTED",ended:"FINISHED",error:"FAILED"}[e]||e}_getAdAdapterType(e){if(e&&e.playerType)return this.adType==ms.CSAI?"vzb_ad_default":this.adType==ms.SSAI?e.playerType==ys.AVPLAYER?"vzb_ad_ssai_avplay":"vzb_ad_default":void 0;vizbee.logger.w(this.constructor.name,"_getAdAdapterType","INVALID playerAdapter")}_buildSyncVideoInfo(){if(!this.playerAdapter||!this.playerAdapter.getVideoInfo)return;let e=this.playerAdapter.getVideoInfo();if(!(e instanceof _s))return;let t={};return e.guid&&(t.id=e.guid),e.videoUrl&&(t.videourl=e.videoUrl),null!=e.isLive&&(t.islive=!!e.isLive),!1!==e.isDvrSupported&&(t.isdvrsupported=e.isDvrSupported),e.title&&(t.title=e.title),e.subtitle&&(t.subtitle=e.subtitle),e.imgUrl&&(t.imgurl=e.imgUrl),e.currentPosition>=0&&(t.position=e.currentPosition),e.duration>=0&&(t.duration=e.duration),t}_setAdAdapter(){let e=this._getAdAdapterType(this.playerAdapter);e&&this.virtualAPIWrapper&&VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player&&(this.virtualAPIWrapper.setAdAdapterType(e),this.virtualAPIWrapper.setAdsVideo(VizbeeTV.tv.player))}}class Ts{constructor(e){e=e||{},this._getStatus=e.getStatus,this._getPlayer=e.getPlayer,this._isPlaybackActive=e.isPlaybackActive,this._setVideoGuid=e.setVideoGuid,this._intervalMs="number"==typeof e.intervalMs&&e.intervalMs>0?e.intervalMs:850,this._logger=e.logger||{debug:function(){},warn:function(){}},this._timer=void 0,this._lastGuid=void 0}start(){this._timer||(this._logger.debug("V2StatusPoller::start",this._intervalMs),this._timer=setInterval(()=>this._onTick(),this._intervalMs))}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._lastGuid=void 0,this._logger.debug("V2StatusPoller::stop")}_onTick(){let e;try{e=this._getStatus&&this._getStatus()}catch(e){return void this._logger.warn("V2StatusPoller::_onTick - getter threw",e)}if(!e)return;const t=this._getPlayer&&this._getPlayer();if(!t)return;const i=e.id;i&&i!==this._lastGuid&&("function"==typeof this._setVideoGuid&&this._setVideoGuid(i,!!e.islive),this._lastGuid=i),t.setPositionMs(e.position),t.setDurationMs(e.duration),this._isPlaybackActive&&!this._isPlaybackActive()||t.dispatchOnTimeUpdate(t.currentTime())}}class Vs extends Is{constructor(){super(),this._statusPoller=void 0,this._lastPushedEventType=void 0}static getInstance(){return null==as&&(as=new Vs,vizbee.logger.d("ElementlessContinuityContext","getInstance","created")),as}setPlayerAdapter(e){let t=super.setPlayerAdapter(e);return t&&this._updateStatusPoller(e),t}removePlayerAdapter(e){return this.notifyPlayerState(Ss.INTERRUPTED),this._stopStatusPoller(),super.removePlayerAdapter(e)}notifyPlayerState(e){const t=this._mapStateToEventType(e);if(!t)return;this._lastPushedEventType=t;const i=VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player?VizbeeTV.tv.player.currentPlayer:void 0;i&&this._fireOnPlayer(i,t)}_isPlaybackActive(){return void 0===this._lastPushedEventType||"playing"===this._lastPushedEventType}_mapStateToEventType(e){return{loading:"loading",buffering:"loading",started:"playing",playing:"playing",paused:"paused",paused_by_user:"paused",interrupted:"interrupted",ended:"ended",finished:"ended",error:"error",failed:"error"}[String(e).toLowerCase()]||null}_fireOnPlayer(e,t){switch(t){case"loading":e.dispatchOnLoading();break;case"playing":e.dispatchOnPlaying();break;case"paused":e.dispatchOnPaused();break;case"ended":e.dispatchOnEnded();break;case"interrupted":e.dispatchOnInterrupted({reason:"host"});break;case"error":e.dispatchOnError({reason:"host"})}}_isValidPlayerAdapter(e){return e instanceof vs?!(!e.playerElement&&!e.videoInfoGetter&&(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should contain a playerElement or a videoInfoGetter"),1)):(vizbee.logger.d(this.constructor.name,"_isValidPlayerAdapter","playerAdapter should be of type vizbee.continuity.adapters.PlayerAdapter"),!1)}_buildPlatformConfig(e){return e&&e.playerElement?super._buildPlatformConfig(e):{standalone:!0,vtvPlayerListConfig:[{type:"native"}],playerType:e&&e.playerType}}_updateStatusPoller(e){if(this._stopStatusPoller(),!e||!e.videoInfoGetter)return;this._lastPushedEventType=void 0;let t=this;this._statusPoller=new Ts({intervalMs:this.vzbOptions&&this.vzbOptions.statusPollIntervalMs,logger:vizbee&&vizbee.logger,getStatus:()=>t._buildSyncVideoInfo(),getPlayer:()=>VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player?VizbeeTV.tv.player.currentPlayer:void 0,isPlaybackActive:()=>t._isPlaybackActive(),setVideoGuid:(e,i)=>{t.virtualAPIWrapper&&t.virtualAPIWrapper.setVideoGuid&&t.virtualAPIWrapper.setVideoGuid(e,i)}}),this._statusPoller.start()}_stopStatusPoller(){this._statusPoller&&(this._statusPoller.stop(),this._statusPoller=void 0)}}class Ps extends vs{constructor(e){super(ys.HTML,e)}}class As{constructor(){this.playHandler=void 0,this.pauseHandler=void 0,this.seekHandler=void 0,this.stopHandler=void 0,this.videoInfoGetter=void 0,this.enableTracksHandler=void 0,this.disableTracksHandler=void 0,this.availableTracksGetter=void 0,this.enabledTracksGetter=void 0,this.vizbeeEventHandler=void 0}updateVideoInfo(e){window.vizbee&&vizbee.continuity.ContinuityContext.getInstance().setVideoInfo(e)}setVideoInfoGetter(e){"function"==typeof e&&(this.videoInfoGetter=e)}getVideoInfo(){if(this.videoInfoGetter)return this.videoInfoGetter()}updateVideoStatus(e){}setPlayHandler(e){"function"==typeof e&&(this.playHandler=e)}setPauseHandler(e){"function"==typeof e&&(this.pauseHandler=e)}setSeekHandler(e){"function"==typeof e&&(this.seekHandler=e)}setStopHandler(e){"function"==typeof e&&(this.stopHandler=e)}setAvailableTracksGetter(e){"function"==typeof e&&(this.availableTracksGetter=e)}setEnabledTracksGetter(e){"function"==typeof e&&(this.enabledTracksGetter=e)}setEnableTracksHandler(e){"function"==typeof e&&(this.enableTracksHandler=e)}setDisableTracksHandler(e){"function"==typeof e&&(this.disableTracksHandler=e)}setVizbeeEventHandler(e){"function"==typeof e&&(this.vizbeeEventHandler=e)}}class Ds extends J{constructor(e){if(!(e instanceof J))throw new TypeError("BasePlayerExtension::constructor() - playerToExtend must be instance of BasePlayerExtensible.");super(e.platform),this.extendedPlayer=e,this.parentExtension=null,this.isExtendedPlayerBasePlayer()||(this.extendedPlayer.parentExtension=this),this.registerEvents(this.extendedPlayer,this),VizbeeTV.logger.debug(this.constructor.name+"::constructed")}registerEvents(e,t){e&&t?(e.onLoading=e=>{this.onLoadingHandler.call(t,e)},e.onStarted=e=>{this.onStartedHandler.call(t,e)},e.onPlaying=e=>{this.onPlayingHandler.call(t,e)},e.onPaused=e=>{this.onPausedHandler.call(t,e)},e.onBuffering=e=>{this.onBufferingHandler.call(t,e)},e.onBufferingComplete=e=>{this.onBufferingCompleteHandler.call(t,e)},e.onTimeUpdate=e=>{this.onTimeUpdateHandler.call(t,e)},e.onInterrupted=e=>{this.onInterruptedHandler.call(t,e)},e.onEnded=e=>{this.onEndedHandler.call(t,e)},e.onError=e=>{this.onErrorHandler.call(t,e)},e.onEvent=e=>{this.onEventHandler.call(t,e)}):VizbeeTV.logger.error(this.constructor.name+"::registerEvents - MISSING playerToExtend/currentPlayer")}reconstruct(e){this.extendedPlayer.reconstruct(e)}beforeStart(e){super.start(e)}start(e){this.beforeStart(e),this.extendedPlayer.start(e)}play(){this.extendedPlayer.play()}pause(){this.extendedPlayer.pause()}togglePlayPause(){VizbeeTV.logger.debug("BasePlayerExtension::togglePlayPause() -- called"),this.extendedPlayer.togglePlayPause()}stop(e){this.extendedPlayer.stop(e)}seek(e){this.extendedPlayer.seek(e)}currentTime(){return this.extendedPlayer.currentTime()}getDuration(){return this.extendedPlayer.getDuration()}getStartTime(){return this.extendedPlayer.getStartTime()}getBufferLevel(){return this.extendedPlayer.getBufferLevel()}getAudioBufferLevel(){return this.extendedPlayer.getAudioBufferLevel()}getCurrentState(){return this.extendedPlayer.getCurrentState()}getCurrentVersion(){return this.extendedPlayer.getCurrentVersion()}getTracks(e){return this.extendedPlayer.getTracks(e)}getEnabledTracks(e){return this.extendedPlayer.getEnabledTracks(e)}setTracks(e){return this.extendedPlayer.setTracks(e)}enableTracks(e){this.extendedPlayer.enableTracks(e)}disableTracks(e){this.extendedPlayer.disableTracks(e)}changeAudioTrack(e){this.extendedPlayer.changeAudioTrack(e)}doAction(e){return this.extendedPlayer.doAction(e)}getName(){return this.extendedPlayer.getName()}destroy(){this.resetListeners(),this.extendedPlayer.destroy()}getStreamQualityInfo(){return this.extendedPlayer?this.extendedPlayer.getStreamQualityInfo():{}}setStreamQualityInfo(e){this.extendedPlayer&&this.extendedPlayer.setStreamQualityInfo(e)}resetStreamQualityInfo(){this.extendedPlayer&&this.extendedPlayer.resetStreamQualityInfo()}get basePlayer(){return this.isExtendedPlayerBasePlayer()?this.extendedPlayer.currentPlayer:this.extendedPlayer instanceof Ds?this.extendedPlayer.basePlayer:void 0}isExtendedPlayerBasePlayer(){return this.extendedPlayer instanceof J&&!(this.extendedPlayer instanceof Ds)}get parentPlayer(){return this.parentExtension}onLoadingHandler(e){this.dispatchOnLoading.call(this,e)}onStartedHandler(e){this.dispatchOnStarted.call(this,e)}onPlayingHandler(e){this.dispatchOnPlaying.call(this,e)}onPausedHandler(e){this.dispatchOnPaused.call(this,e)}onBufferingHandler(e){this.dispatchOnBuffering.call(this,e)}onBufferingCompleteHandler(e){this.dispatchOnBufferingComplete.call(this,e)}onTimeUpdateHandler(e){this.dispatchOnTimeUpdate.call(this,e)}onInterruptedHandler(e){this.dispatchOnInterrupted.call(this,e)}onEndedHandler(e){this.dispatchOnEnded.call(this,e)}onErrorHandler(e){this.dispatchOnError.call(this,e)}onEventHandler(e){this.dispatchOnEvent.call(this,e)}}class Cs extends vs{constructor(){super(ys.AVPLAYER,webapis.avplay)}setPlayerType(e){}setPlayerElement(e){}wrapListener(e){let t=this._getVTVAVPlayer();return null==t?(vizbee.logger.warn(this.constructor.name+"::wrapListener - can't get AVPlayer"),e):t.wrapAVPlayerListener(e)}getListener(){let e=this._getVTVAVPlayer();if(null!=e)return e.getListener();vizbee.logger.warn(this.constructor.name+"::getListener - can't get AVPlayer")}_getVTVAVPlayer(){if(!this.playerElement)return;let e,t;if(VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player)return e=VizbeeTV.tv.player,Object.getPrototypeOf(e.constructor).name===Ds.name?t=e.basePlayer:Object.getPrototypeOf(e.constructor).name===J.name&&(t=e.currentPlayer),t&&"avplayer"==t.getName().toLowerCase()?t:void vizbee.logger.warn(this.constructor.name+"::_getVTVAVPlayer - can't get AVPlayer");vizbee.logger.warn(this.constructor.name+"::_getVTVAVPlayer - can't get platform player")}}class ks{static get STOP_REASON_UNKNOWN(){return"stop_reason_unknown"}static get STOP_BY_USER(){return"stop_by_user"}static get STOP_IMPLICIT(){return"stop_implicit"}static get STOP_REASON_BEFORE_NEXT_VIDEO(){return"stop_reason_before_next_video"}}class ws{constructor(){}wasAppLaunchedByVizbee(){return!!VizbeeTV.tv.launchParamsDeferral&&VizbeeTV.tv.launchParamsDeferral.isLaunchedbyVizbee()}wasVideoStartedByVizbee(){return VZB.wasVideoStartedByVizbee()}addProvider(e,t){const i=VZB.getMetricsManager();i&&i.addProvider(e,t)}removeProvider(e){const t=VZB.getMetricsManager();t&&t.removeProvider(e)}logMetrics(e,t){const i=VZB.getMetricsManager();i&&i.trackEvent(e,t)}setCustomAttributes(e){const t=VZB.getMetricsManager();t&&t.setCustomProperties(e)}}class Ns{constructor(){this._type="",this._id=-1}toJSON(){return{type:this._type,id:this._id}}fromJSON(e){e&&e.type&&!isNaN(e.id)?(this._type=e.type,this._id=e.id):VizbeeSDK.logger.verbose("Track::fromJSON - invalid trackInfo")}set type(e){this._type=e}get type(){return this._type}set id(e){this._id=e}get id(){return this._id}}class Os extends Ns{constructor(){super(),this.type=n,this.subtype="",this._lang=""}toJSON(){let e=super.toJSON();return e.lang=this._lang,e.subtype=this._subtype,e}fromJSON(e){e?(e.type=e.type||this.type,super.fromJSON(e),this._lang=e.lang,this._subtype=e.subtype):VizbeeSDK.logger.verbose("SubtitleTrack::fromJSON - invalid trackInfo")}set lang(e){this._lang=e}get lang(){return this._lang}set subtype(e){this._subtype=e}get subtype(){return this._subtype}}class Rs{constructor(){this.state={message:"This is vizbee snackbar!",theme:{color:"#FFFFFF",bgColor:"#7F98DE"},layout:{position:""},border:{color:"#FFFFFF"},font:{uri:"",family:"",size:24,weight:""},icon:{uri:"https://static.claspws.tv/screen/icons/common/user_icon_white.png"}},this.uiContainer=document.getElementsByTagName("body")[0],this.uiContainer&&(this._setupCSS(),this.render(this.uiContainer),this.isCurrentAnimationShowingUI=void 0)}render(e){this.nodes||e&&(this.nodes={},this.nodes.popupMessageWithIconOverlay=document.createElement("div"),this.nodes.popupMessageWithIconOverlay.id="vizbeeSnackbarOverlay",this.nodes.popupMessageWithIconOverlay.className="opaqueBackground hidden",this.nodes.popupMessageWithIconContainer=document.createElement("div"),this.nodes.popupMessageWithIconContainer.id="popupTimedoutMessageWithIconUIContainer",this.nodes.popupMessageWithIconContainer.className="popupTimedoutMessageWithIconUIContainer",this.nodes.popupMessageWithIconContainer.style.color=this.state.theme.color,this.nodes.popupTimedoutIconEle=document.createElement("div"),this.nodes.popupTimedoutIconEle.id="popupTimedoutIconEle",this.nodes.popupTimedoutIconEle.className="popupTimedoutIconEle",this.nodes.popupTimedoutMessageEle=document.createElement("div"),this.nodes.popupTimedoutMessageEle.id="popupTimedoutMessageEle",this.nodes.popupTimedoutMessageEle.className="popupMessageEle",this.nodes.popupMessageWithIconContainer.appendChild(this.nodes.popupTimedoutIconEle),this.nodes.popupMessageWithIconContainer.appendChild(this.nodes.popupTimedoutMessageEle),this.nodes.popupMessageWithIconOverlay.appendChild(this.nodes.popupMessageWithIconContainer),e.appendChild(this.nodes.popupMessageWithIconOverlay),this._updateUI())}setOptions(e){e&&(this.state.message=e.message||this.state.message,this.state.theme.color=e.theme.color||this.state.theme.color,this.state.theme.bgColor=e.theme.bgColor||this.state.theme.bgColor,this.state.layout.position=e.layout.position||this.state.layout.position,this.state.border.color=e.border.color||this.state.border.color,this.state.font.uri=e.font.uri||this.state.font.uri,this.state.font.family=e.font.family||this.state.font.family,this.state.font.size=this.screenRatio*(e.font.size||this.state.font.size),this.state.font.weight=e.font.weight||this.state.font.weight,this.state.icon.uri=e.icon.uri||this.state.icon.uri,this._updateUI(),this.show())}show(){this.nodes&&this.nodes.popupMessageWithIconOverlay&&(this._showUIWithAnimation(),C.removeClass("hidden",this.nodes.popupMessageWithIconOverlay))}hide(){this.nodes&&this.nodes.popupMessageWithIconOverlay&&this.nodes.popupMessageWithIconContainer&&(C.addClass("hidden",this.nodes.popupMessageWithIconOverlay),this.uiContainer&&this.uiContainer.contains(this.nodes.popupMessageWithIconOverlay)&&this.nodes.popupMessageWithIconOverlay.parentNode.removeChild(this.nodes.popupMessageWithIconOverlay))}_updateUI(){if(!this.nodes)return;let e=this.nodes.popupMessageWithIconContainer;if(e){e.style.color=this.state.theme.color,e.style.backgroundColor=this.state.theme.bgColor,null!=this.state.border.color&&(e.style.borderColor=this.state.border.color);const t=this.state.layout.position;if(t){delete e.style.top,delete e.style.right,delete e.style.bottom,delete e.style.left,e.style.position=t;const i=30*this.screenRatio+"px";t.indexOf("top")>-1?(e.style.top=i,t.indexOf("left")>-1?e.style.left=i:e.style.right=i):(e.style.bottom=i,t.indexOf("left")>-1?e.style.left=i:e.style.right=i)}}let t=this.nodes.popupTimedoutMessageEle;t&&(null!=this.state.font.uri&&(t.style.fontFamily=this.state.font.family),null!=this.state.font.size&&(t.style.fontSize=this.state.font.size+"px"),null!=this.state.font.weight&&(t.style.fontWeight=this.state.font.weight),null!=this.state.font.color&&(t.style.color=this.state.font.color),t.innerHTML=this.state.message);let i=this.nodes.popupTimedoutIconEle;i&&(this.state.icon.uri?(i.style.minWidth=36*this.screenRatio+"px",i.style.minHeight=36*this.screenRatio+"px",i.style.backgroundImage="url('"+this.state.icon.uri+"')",t&&(t.style.paddingLeft=12*this.screenRatio+"px")):(i.style.minWidth="0px",i.style.width="0px",t&&(t.style.paddingLeft="0px")))}_showUIWithAnimation(){this.isCurrentAnimationShowingUI=!0,I.get(this.state,["layout","position"],"").indexOf("top")>-1?this._showSlidingFromTopToBottom():this._showSlidingFromBottomToTop()}_isAnimationSupported(e){return e&&"function"==typeof e.animate}_showSlidingFromBottomToTop(){if(!this.nodes||!this.nodes.popupMessageWithIconContainer)return;if(!this._isAnimationSupported(this.nodes.popupMessageWithIconContainer))return void VizbeeTV.logger.i("PopupMessageWithIconView","_showSlidingFromBottomToTop","animation NOT supported!");const e=this.nodes.popupMessageWithIconContainer.offsetHeight+50,t=[{transform:"translateY("+e+"px)"},{transform:"translateY("+e/2+"px)"},{transform:"translateY(0px)"}];this.nodes.popupMessageWithIconContainer.animate(t,{duration:300,iterations:1})}_showSlidingFromTopToBottom(){if(!this.nodes||!this.nodes.popupMessageWithIconContainer)return;if(!this._isAnimationSupported(this.nodes.popupMessageWithIconContainer))return void VizbeeTV.logger.i("PopupMessageWithIconView","_showSlidingFromTopToBottom","animation NOT supported!");const e=this.nodes.popupMessageWithIconContainer.offsetHeight+50,t=[{transform:"translateY(-"+e+"px)"},{transform:"translateY(-"+e/2+"px)"},{transform:"translateY(0px)"}];this.nodes.popupMessageWithIconContainer.animate(t,{duration:300,iterations:1})}_setupCSS(){this.screenRatio=this._getScreenRatio();let e=this._processCSS(this.screenRatio,"\n #vizbeeSnackbarOverlay {\n position: absolute;\n top: 0px;\n left: 0px;\n width: $1280px;\n height: $720px;\n background: transparent !important;\n z-index: 9999;\n }\n\n #popupTimedoutMessageWithIconUIContainer {\n position: absolute;\n display: inline-flex;\n align-items: center;\n max-width: $420px;\n max-height: $80px;\n background: white;\n border-color: #FFFFFF;\n border: solid;\n border-width: $1px;\n border-radius: $45px;\n padding: $10px $24px;\n text-align: left !important;\n }\n\n #popupTimedoutIconEle {\n width: $36px;\n height: $36px;\n min-width: $36px;\n min-height: $36px;\n background-size: contain;\n background-repeat: no-repeat;\n }\n\n #popupTimedoutMessageEle {\n padding-left: $12px;\n }\n");this._appendToHEAD("vizbeeSnackbarCSS",e)}_processCSS(e,t){if(t)return t.replace(/\$[0-9]+/gi,function(t){let i=t.split("$");return Math.ceil(e*i[1])})}_getScreenRatio(){return document.body.clientWidth/1280}_appendToHEAD(e,t){if(this._isEmpty(e))return;if(this._isEmpty(t))return;let i=document.getElementById(e);if(null!==i&&i instanceof HTMLStyleElement)return;let n=document.createElement("style");n.type="text/css",n.id=e,n.styleSheet?n.styleSheet.cssText=t:n.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(n)}_isEmpty(e){return void 0===e||0==e.length||null==e}}class Ms{constructor(e){this.uiConfig=e,this.popupMessageWithIconView=void 0}show(e=8){this.hide(),this.uiConfig&&"function"==typeof this.uiConfig.toJSON?(this.popupMessageWithIconView=new Rs,this.popupMessageWithIconView.setOptions(this.uiConfig.toJSON()),-1!==e&&setTimeout(()=>{this.popupMessageWithIconView.hide()},1e3*e)):VizbeeTV.logger.e("PopupMessageWithIconView","show","Invalid uiConfig")}hide(){this.popupMessageWithIconView&&this.popupMessageWithIconView.hide();let e=document.getElementById("vizbeeSnackbarOverlay");e&&(VizbeeTV.logger.i("PopupMessageWithIconView","hide","Removing vizbeeSnackbarEle"),e.parentNode.removeChild(e))}}const Ls={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"};class xs{constructor(){this._message="This is a vizbee snackbar message",this._theme={color:"#FFFFFF",bgColor:"#7F98DE"},this._layout={position:Ls.BOTTOM_RIGHT},this._border={color:"#FFFFFF"},this._font={uri:"",family:"",size:24,weight:""},this._icon={uri:"https://s3.amazonaws.com/vga-videos/images/vsa/loading.gif"}}get message(){return this._message}set message(e){this._message=e}get theme(){return this._theme}set theme(e){this._theme=e}get layout(){return this._layout}set layout(e){this._layout=e}get border(){return this._border}set border(e){this._border=e}get font(){return this._font}set font(e){this._font=e}get icon(){return this._icon}set icon(e){this._icon=e}fromJSON(e){e&&(this._message=e.message,e.theme&&(this._theme.color=e.theme.color||this._theme.color,this._theme.bgColor=e.theme.bgColor||this._theme.bgColor),e.layout&&(this._layout=e.layout||this._layout),e.border&&(this._border=e.border||this._border),e.font&&(this._font.uri=e.font.uri||this._font.uri,this._font.family=e.font.family||this._font.family,this._font.size=e.font.size||this._font.size,this._font.weight=e.font.weight||this._font.weight),e.icon&&e.icon.uri&&(this._icon.uri=e.icon.uri||this._icon.uri))}toJSON(){return{message:this._message,theme:this._theme,layout:this._layout,border:this._border,font:this._font,icon:this._icon}}}class zs{constructor(){ke(this,"namespaceAndReceiverMap",new Map)}async send(e,t){return VizbeeSDK.logger.debug(this.constructor.name,"send",`namespace: ${t}, payload: ${JSON.stringify(e)}`),new Promise((i,n)=>{window.VZB.sendXMessage(e,t,{onSuccess:e=>{i()},onFailure:e=>{n(e)}})})}addReceiver(e,t){VizbeeSDK.logger.debug(this.constructor.name,"addReceiver",`with namespace: ${e}`),this.namespaceAndReceiverMap.set(e,t)}removeReceiver(e,t){VizbeeSDK.logger.debug(this.constructor.name,"removeReceiver",`with namespace: ${e}`),this.namespaceAndReceiverMap.delete(e)}onReceive(e,t,i){VizbeeSDK.logger.debug(this.constructor.name,"onReceive",`namespace: ${e}, payload: ${JSON.stringify(t)}, device: ${i}`);const n=this.namespaceAndReceiverMap.get(e);n&&n(t,e,i)}}let Ks=function(e){return e.ANDROID_MOBILE="Android",e.IOS="iOS",e.UNKNOWN="Unknown",e}({}),Us=function(e){return e.ANDROID_MOBILE="ANDROID_MOBILE",e.IOS="IOS",e.UNKNOWN="UNKNOWN",e}({});function Fs(e){switch(e){case Ks.ANDROID_MOBILE:return Us.ANDROID_MOBILE;case Ks.IOS:return Us.IOS;case Ks.UNKNOWN:default:return Us.UNKNOWN}}let Bs=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({}),Gs=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({});class Hs{constructor(){ke(this,"presenceCallbacks",[]),ke(this,"syncController",null),this.init()}init(){var e,t,i;this.syncController=null===(e=window.VZB)||void 0===e||null===(t=e.getSyncController)||void 0===t?void 0:t.call(e),this.syncController?this.listenForSyncControllerSessionState():(null===(i=window.VizbeeSDK)||void 0===i||null===(i=i.logger)||void 0===i||i.warn("VizbeeBicastMemberPresenceClientImpl","init","syncController is not available"),this.listenForSyncControllerAvailability())}listenForSyncControllerAvailability(){var e,t;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerAvailability","waiting for syncController to be available"),null===(t=window.VZB)||void 0===t||t.addSyncReadyListener(()=>{var e,t,i;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerAvailability","syncController is now available"),this.syncController=null===(t=window.VZB)||void 0===t||null===(i=t.getSyncController)||void 0===i?void 0:i.call(t),this.listenForSyncControllerSessionState()})}listenForSyncControllerSessionState(){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerSessionState","subscribing to presence events"),this.syncController.subscribeToPresence(e=>{if(VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerSessionState",`presence event received: ${JSON.stringify(e)}`),null!==e){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","listenForSyncControllerSessionState",`processing presence event: ${JSON.stringify(e)}`);const t=this.toVizbeeDevice(e.member),i={event:e.event===Gs.JOIN?Bs.JOIN:Bs.LEAVE,device:t};this.presenceCallbacks.forEach(e=>e(i))}})}subscribe(e){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","subscribe",e),this.presenceCallbacks.push(e)}unsubscribe(e){VizbeeSDK.logger.debug("VizbeeBicastMemberPresenceClientImpl","unsubscribe","");const t=this.presenceCallbacks.indexOf(e);t>-1&&this.presenceCallbacks.splice(t,1)}getMembers(){var e,t;const i=(null===(e=this.syncController)||void 0===e||null===(t=e.getActiveSenders)||void 0===t?void 0:t.call(e))||{};return Object.values(i).map(e=>this.toVizbeeDevice(e))}toVizbeeDevice(e){var t,i,n,r,s,o,a,d,l,c,u;return{deviceId:null!==(t=null==e||null===(i=e.ssinfo)||void 0===i?void 0:i.REMOTE_DEVICE_ID)&&void 0!==t?t:"UNKNOWN",friendlyName:null!==(n=null==e||null===(r=e.ssinfo)||void 0===r?void 0:r.REMOTE_FRIENDLY_NAME)&&void 0!==n?n:"UNKNOWN",modelName:null!==(s=null==e||null===(o=e.ssinfo)||void 0===o?void 0:o.modelName)&&void 0!==s?s:"UNKNOWN",modelNumber:null!==(a=null==e||null===(d=e.ssinfo)||void 0===d?void 0:d.modelNumber)&&void 0!==a?a:"UNKNOWN",manufacturer:null!==(l=null==e||null===(c=e.ssinfo)||void 0===c?void 0:c.manufacturer)&&void 0!==l?l:"UNKNOWN",deviceType:Fs(null==e||null===(u=e.ssinfo)||void 0===u?void 0:u.REMOTE_DEVICE_TYPE)}}}ke(Hs,"LOG_TAG","VizbeeBicastMemberPresenceClientImpl");class Ws{constructor(){ke(this,"_messagingClient",null),ke(this,"_presenceClient",null)}getMessagingClient(){return this._messagingClient||(this._messagingClient=new zs),this._messagingClient}getPresenceClient(){return this._presenceClient||(this._presenceClient=new Hs),this._presenceClient}}class js{constructor(){if(ke(this,"session",null),ke(this,"sessionState",rr.NOT_CONNECTED),ke(this,"sessionStateListeners",[]),ke(this,"syncController",null),ke(this,"onSessionStateChanged",e=>{var t,i;switch(this.sessionState=e,e){case rr.CONNECTED:null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.info("VizbeeBicastSessionManager","onSessionStateChanged","CONNECTED"),this.session=new Ws,this.sessionStateListeners.forEach(e=>e.onSessionStateChanged(rr.CONNECTED));break;case rr.NOT_CONNECTED:null===(i=window.VizbeeSDK)||void 0===i||null===(i=i.logger)||void 0===i||i.info("VizbeeBicastSessionManager","onSessionStateChanged","NOT_CONNECTED"),this.session=null,this.sessionStateListeners.forEach(e=>e.onSessionStateChanged(rr.NOT_CONNECTED))}}),js.instance)return js.instance;this.init(),js.instance=this}init(){var e,t,i,n;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastSessionManager","init","initialize session manager"),this.syncController=null===(t=window.VZB)||void 0===t||null===(i=t.getSyncController)||void 0===i?void 0:i.call(t),this.syncController?this.listenForSyncControllerSessionState():(null===(n=window.VizbeeSDK)||void 0===n||null===(n=n.logger)||void 0===n||n.warn("VizbeeBicastSessionManager","init","syncController is not available"),this.listenForSyncControllerAvailability())}listenForSyncControllerAvailability(){var e,t;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastSessionManager","listenForSyncControllerAvailability","waiting for syncController to be available"),null===(t=window.VZB)||void 0===t||t.addSyncReadyListener(()=>{var e,t,i;null===(e=window.VizbeeSDK)||void 0===e||null===(e=e.logger)||void 0===e||e.debug("VizbeeBicastSessionManager","listenForSyncControllerAvailability","syncController is now available"),this.syncController=null===(t=window.VZB)||void 0===t||null===(i=t.getSyncController)||void 0===i?void 0:i.call(t),this.listenForSyncControllerSessionState()})}listenForSyncControllerSessionState(){var e,t,i,n;this.sessionState=null!==(e=null===(t=this.syncController)||void 0===t||null===(i=t.sessionState)||void 0===i?void 0:i.call(t))&&void 0!==e?e:rr.NOT_CONNECTED,this.sessionState===rr.CONNECTED&&(this.session=new Ws),null===(n=this.syncController)||void 0===n||n.addSessionStateListener(this.onSessionStateChanged)}addSessionStateListener(e){var t;null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.debug("VizbeeBicastSessionManager","addSessionStateListener","add session state listener"),"function"==typeof e?this.sessionStateListeners.push({onSessionStateChanged:e}):this.sessionStateListeners.push(e)}removeSessionStateListener(e){var t;null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.debug("VizbeeBicastSessionManager","removeSessionStateListener","remove session state listener");const i=this.sessionStateListeners.indexOf(e);i>-1&&this.sessionStateListeners.splice(i,1)}getSession(){return this.session}isConnecting(){return this.sessionState===rr.CONNECTING}isConnected(){return this.sessionState===rr.CONNECTED}}class qs{constructor(){if(ke(this,"presenceCallbacks",[]),ke(this,"vizbeeSession",null),qs.instance)return qs.instance;this.init(),qs.instance=this}init(){try{var e;if(VizbeeSDK.logger.info("VizbeePresenceManager::init - Initializing Vizbee Presence Manager"),null===(e=window.vizbee)||void 0===e||null===(e=e.continuity)||void 0===e||!e.xmessages)throw new Error("Vizbee continuity or xmessages not initialized");const t=new window.vizbee.continuity.xmessages.VizbeeBicastSessionManager;if(!t)throw new Error("Session manager initialization failed");t.addSessionStateListener({onSessionStateChanged:e=>{if(VizbeeSDK.logger.info("VizbeePresenceManager::init - Session state changed:",e),e===rr.CONNECTED){if(VizbeeSDK.logger.debug("VizbeePresenceManager::init - Session connected"),this.vizbeeSession=t.getSession(),!this.vizbeeSession)throw new Error("Failed to retrieve Vizbee session");if(this.vizbeePresenceClient=this.vizbeeSession.getPresenceClient(),!this.vizbeePresenceClient)throw new Error("Failed to retrieve Vizbee presence client");if(this.presenceCallbacks.length>0)for(let e=0;e<this.presenceCallbacks.length;e++){const t=this.presenceCallbacks[e];this.vizbeePresenceClient.subscribe(t)}}else{if(this.vizbeePresenceClient)for(let e=0;e<this.presenceCallbacks.length;e++){const t=this.presenceCallbacks[e];this.vizbeePresenceClient.unsubscribe(t)}this.vizbeeSession=null}}})}catch(e){throw VizbeeSDK.logger.warn("VizbeePresenceManager::init - Error initializing Vizbee session:",e),e}}subscribe(e){"function"==typeof e?(this.presenceCallbacks.push(e),this.vizbeePresenceClient?this.vizbeePresenceClient.subscribe(e):VizbeeSDK.logger.warn("VizbeePresenceManager::subscribe - Presence client not initialized yet")):VizbeeSDK.logger.warn("VizbeePresenceManager::subscribe - Provided callback is not a function")}unsubscribe(e){VizbeeSDK.logger.debug("VizbeePresenceManager::unsubscribe"),this.vizbeePresenceClient&&this.vizbeePresenceClient.unsubscribe(e);const t=this.presenceCallbacks.indexOf(e);t>-1&&this.presenceCallbacks.splice(t,1)}getMembers(){return this.vizbeePresenceClient?this.vizbeePresenceClient.getMembers():[]}}class Ys extends cs{constructor(){super()}get ContinuityContext(){return Vs}get adapters(){return{AppAdapter:us,PlayerAdapter:vs,HTMLPlayerAdapter:Ps,BasePlayerAdapter:As,AVPlayerAdapter:Cs,PlayerType:ys,AdAdapter:fs,AdType:ms,VideoStopReason:ks}}get messages(){return{VizbeeEvent:Es,VideoInfo:bs,VideoStatus:_s,AdEventType:ps,AdStatus:hs,PlayerState:Ss,SubtitleTrack:Os}}get analytics(){return{AnalyticsProvider:ws}}get ui(){return{LayoutPosition:Ls,Snackbar:Ms,SnackbarUIConfig:xs}}get analytics(){return{AnalyticsProvider:ws}}get ui(){return{LayoutPosition:Ls,Snackbar:Ms,SnackbarUIConfig:xs}}get xmessages(){return{VizbeeBicastSessionManager:js,VizbeeBicastSession:Ws,VizbeeMessagingClient:void 0,VizbeePresenceManager:qs}}}var Js=new class extends Ys{constructor(){super()}},Qs=new class extends rs{constructor(){super()}get continuity(){return Js}get framework(){return Js}};if(Qs.logger=new Pe,Qs.logger.setPrefix("[Vizbee]"),"undefined"!=typeof window){if(window.VizbeeSDK=Qs,window.vizbee){let e=window.vizbee;window.vizbee=window.VizbeeSDK,Object.keys(e).forEach(t=>{window.vizbee[t]=e[t]})}else window.vizbee=window.VizbeeSDK;"function"==typeof window.dispatchEvent&&window.dispatchEvent(new Event("VIZBEE_SDK_READY"))}export{ps as AdEventType,ms as AdType,Ss as PlayerState,ys as PlayerType,ks as VideoStopReason,Qs as default};