@vizbeetv/sdk-qa 7.8.40 → 7.8.41

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.
@@ -0,0 +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,i)=>e.then(()=>D.loadScript(t)).catch(e=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - FAILED to load library",e)}),Promise.resolve()).then(()=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - SUCCESS to load library")})}}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={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="videoadapter_video",qe="videoadapter_ad";function Ye(e){var t,i,n=!Ue.contains(["timeupdate"],e.type);He.isInProgress||(Ge&&"app"!==Ge.app.state?(t=new $e,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(je,t,n)):VizbeeSDK.logger.verbose('VideoAdapter::videoEventHandler - app.state = "app"'))}function Je(e,t){var i=e.playing||e.preparing;(i||!i&&He.isInProgress)&&Be.emit(qe,e,t),He.isInProgress=i||!1,He.isInProgress||(We=!1),"FINISHED"==e.state||e.state}function $e(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)}function Qe(){He.isInProgress&&Re.reset()}var Ze,Xe,et,tt,it,nt,rt,st,ot,at,dt,lt,ct,ut,pt={setVideo:function(e){var t;(t=e).onLoading=function(e){He.isInProgress||(Ye({type:"loading"}),We=!1)},t.onPlaying=function(e){He.isInProgress||(Ye({type:"playing"}),We=!0)},t.onPaused=function(e){He.isInProgress||(Ye({type:"paused"}),We=!1)},t.onBuffering=function(e){He.isInProgress||(Ye({type:"loading"}),We=!1)},t.onError=function(e){He.isInProgress||(Ye({type:"error",data:e}),We=!1)},t.onInterrupted=function(e){He.isInProgress||(Ye({type:"interrupted",data:e}),We=!1)},t.onEnded=function(){He.isInProgress||(Ye({type:"ended"}),We=!1)},t.onTimeUpdate=function(e){He.isInProgress||(We?Ye({type:"timeupdate"}):(We=!0,Ye({type:"playing"})))},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 $e({id:Ge.video.id,state:"INTERRUPTED"});Be.emit(je,i,!0)}var n=new $e({id:e});n.position=n.duration=-1,n.state="UNKNOWN",Be.emit(je,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()),Ye({type:"error"})},willStart:function(e,t){Fe.willStartVideo(e,t)},start:function(e){Ye({type:"loadedmetadata"}),Qe(),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)){VizbeeTV.tv.inputDevice.sendStop(),VizbeeSDK.logger.debug("VideoAdapter::stop - sending INTERRUPTED state");var t=new $e({state:"INTERRUPTED"});Be.emit(je,t,!0),Qe()}},exit:function(){var e=new $e({state:"INTERRUPTED"});Be.emit(je,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(je,new $e,!0)},volumeDown:function(){Be.emit(je,new $e,!0)},onEvent:function(e){Fe.onEvent(e)},setAdAdapter:function(e){Re&&Re.removeListener(Je),(Re=e)&&Re.addListener(Je)},setAppStateManager:function(e){Ge=e},reset:function(){Ke=void 0,He={playing:!1}},addListener:function(e){Be.addListener(je,e),Be.addListener(qe,e)},removeListener:function(e){Be.removeListener(je,e),Be.removeListener(qe,e)}};function ht(){if(Xe)return Ze;Xe=1;var e,t=I();return Ze={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 gt(){if(tt)return et;tt=1;var e=new(0,Le().EventEmitter),t=pt,i=ht(),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 et={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(nt)return it;nt=1;var e=I(),t=new(0,Le().EventEmitter),i=gt(),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"),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(),it={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 vt(){return at?ot:(at=1,ot={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 yt(){if(lt)return dt;lt=1;var e=new(0,Le().EventEmitter),t="sync_proxy_video_cmds";return dt={send:function(i){e.emit(t,i)},reset:function(){e.removeAllListeners(t)},addListener:function(i){e.addListener(t,i)}}}class mt{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 bt{constructor(e,t){this.type=e,this.data=t}}class St{static get SYNC_CONNECT(){return"sync-connect"}static get SYNC_MESSAGE(){return"sync-message"}static get SYNC_PRESENCE(){return"sync-presence"}}var _t,It,Tt,Et,Vt=_(function(){if(ut)return ct;ut=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 ct={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}}}()),Pt={exports:{}},At={exports:{}};function Ct(){return _t||(_t=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}},At.exports=t),At.exports;var e,t}function Dt(){if(Tt)return It;Tt=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 It=e}var kt,wt,Nt,Mt=(Et||(Et=1,function(){var e=Ct(),t=Dt().utf8,i=Dt().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,Pt.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)}}}()),Pt.exports),Ot=_(Mt),xt={exports:{}},Lt={exports:{}},zt={exports:{}},Rt={exports:{}},Kt={exports:{}};function Ut(){return wt||(wt=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){return kt||(kt=1,e=Kt,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=Kt.exports),null!==e&&(e.exports=t.uuid)),Kt.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}(Rt,Rt.exports)),Rt.exports}function Bt(){return Nt||(Nt=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=Ut())&&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}(zt,zt.exports)),zt.exports}var Ft,Gt={exports:{}};function Ht(){return Ft||(Ft=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(Bt());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}(Gt,Gt.exports)),Gt.exports}var Wt,jt,qt={exports:{}},Yt={exports:{}},Jt={exports:{}};function $t(){return Wt||(Wt=1,e=Jt,t=Jt.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),Jt.exports;var e,t}function Qt(){return jt||(jt=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=$t())&&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}(Yt,Yt.exports)),Yt.exports}var Zt,Xt,ei,ti={exports:{}},ii={},ni={exports:{}};function ri(){return Zt||(Zt=1,e=ni,t=ni.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),ni.exports;var e,t}function si(){if(Xt)return ii;Xt=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.getOperation=function(){return t.default.PNTimeOperation},ii.getURL=function(){return"/time/0"},ii.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},ii.prepareParams=function(){return{}},ii.isAuthSupported=function(){return!1},ii.handleResponse=function(e,t){return{timetoken:t[0]}},ii.validateParams=function(){};var e,t=(e=ri())&&e.__esModule?e:{default:e};return ii}var oi,ai,di,li,ci={exports:{}};function ui(){if(di)return ai;function e(e){return encodeURIComponent(e).replace(/[!~*'()]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}return di=1,ai={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 pi(){return li||(li=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(Ht()),a(Bt()),a(Qt());var n=a((ei||(ei=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=si())||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}(ti,ti.exports)),ti.exports)),r=a((oi||(oi=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=Bt())||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}(ci,ci.exports)),ci.exports)),s=a(ui()),o=a($t());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}(qt,qt.exports)),qt.exports}var hi,gi={exports:{}};var fi,vi,yi,mi,bi,Si={},_i={},Ii={},Ti={};function Ei(){return bi||(bi=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(Bt()),r=K(Ht()),s=K(pi()),o=K(Qt()),a=K((hi||(hi=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(Ut()),n=s(ui());s(Bt());var r=s(ri());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}(gi,gi.exports)),gi.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(fi)return Si;fi=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.getOperation=function(){return e.default.PNUnsubscribeOperation},Si.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Si.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"},Si.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Si.isAuthSupported=function(){return!0},Si.prepareParams=function(e,t){var i=t.channelGroups,n=void 0===i?[]:i,r={};return n.length>0&&(r["channel-group"]=n.join(",")),r},Si.handleResponse=function(){return{}};var e=i(ri()),t=i(ui());function i(e){return e&&e.__esModule?e:{default:e}}return Si}(),m=R(y),b=R(null),S=function(){if(vi)return _i;vi=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.getOperation=function(){return e.default.PNHeartbeatOperation},_i.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},_i.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"},_i.isAuthSupported=function(){return!0},_i.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},_i.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},_i.handleResponse=function(){return{}};var e=i(ri()),t=i(ui());function i(e){return e&&e.__esModule?e:{default:e}}return _i}(),_=R(S),I=R(null),T=R(null),E=R(null),V=R(null),P=R(null),A=function(){if(yi)return Ii;yi=1,Object.defineProperty(Ii,"__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};Ii.getOperation=function(){return t.default.PNPublishOperation},Ii.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"},Ii.usePost=function(e,t){var i=t.sendByPost;return void 0!==i&&i},Ii.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)},Ii.postURL=function(e,t){var n=e.config,r=t.channel;return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+i.default.encodeString(r)+"/0"},Ii.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Ii.isAuthSupported=function(){return!0},Ii.postPayload=function(e,t){return r(e,t.message)},Ii.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},Ii.handleResponse=function(e,t){return{timetoken:t[2]}};var t=n(ri()),i=n(ui());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 Ii}(),C=R(A),D=R(null),k=R(null),w=R(null),N=R(si()),M=function(){if(mi)return Ti;mi=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.getOperation=function(){return e.default.PNSubscribeOperation},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/subscribe/"+n.subscribeKey+"/"+t.default.encodeString(o)+"/0"},Ti.getRequestTimeout=function(e){return e.config.getSubscribeTimeout()},Ti.isAuthSupported=function(){return!0},Ti.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},Ti.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(ri()),t=i(ui());function i(e){return e&&e.__esModule?e:{default:e}}return Ti}(),O=R(M),x=K(ri()),L=K($t()),z=K(Ut());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}(Lt,Lt.exports)),Lt.exports}var Vi,Pi={exports:{}};var Ai,Ci,Di,ki={exports:{}},wi={},Ni=(Di||(Di=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=a(Ei()),n=a((Vi||(Vi=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(Bt());var n=r($t());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}(Pi,Pi.exports)),Pi.exports)),r=function(){return Ai||(Ai=1,e=ki,t=ki.exports,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),ki.exports;var e,t}(),s=a(r),o=function(){if(Ci)return wi;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 Ci=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.get=function(i,n,r){return t.call(this,"GET",this.getStandardOrigin()+n.url,e(i),null,n,r)},wi.post=function(i,n,r,s){return t.call(this,"POST",this.getStandardOrigin()+r.url,e(i),n,r,s)},wi.del=function(i,n,r){return t.call(this,"DELETE",this.getStandardOrigin()+n.url,e(i),null,n,r)},wi}();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}(xt,xt.exports)),xt.exports),Mi=_(Ni);const Oi=["PNAccessDeniedCategory","PNTimeoutCategory","PNNetworkIssuesCategory","PNBadRequestCategory","PNMalformedResponseCategory","PNDecryptionErrorCategory","PNTLSConnectionFailedCategory","PNTLSUntrustedCertificateCategory","PNUnexpectedDisconnectCategory","PNNetworkDownCategory","PNNetworkUpCategory"];class xi extends mt{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 Mi({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 bt(St.SYNC_CONNECT,{})),e(!0)):Oi.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=(""+Ot(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:{};Vt.verifyDeviceId(),this.dispatchReceive(new bt(St.SYNC_MESSAGE,n))}}class Li extends mt{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 zi extends mt{constructor(e,t){if(!(e instanceof mt))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 zi?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===St.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 Ri extends zi{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 Ki extends zi{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 Ui extends zi{constructor(e,t){super(e,t)}getActiveSenders(){throw new TypeError("BaseSyncWithPresence::getSenders() - Abstract method.")}getActiveSendersCount(){throw new TypeError("BaseSyncWithPresence::getActiveSendersCount() - Abstract method.")}}class Bi extends Ui{constructor(e,t){if(!(e instanceof Ui))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 Fi{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:St.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:St.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,Fi.encodeVideoInfo(e)),t}}class Gi extends Bi{constructor(e,t){super(e,t)}handleSyncReceiveEvent(e){if("start_video"==e.data.b.cmd.name){let t=Fi.decodeVideoInfo(e.data.b);t&&(t=Fi.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=Fi.decodeVideoInfo(e.b);return i&&(i=Fi.addInfoFromHeader(i,e.h)),t.items.push(i),t}}class Hi extends Ui{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 bt(St.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 bt(St.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 bt(St.SYNC_PRESENCE,this._senderMap)))}}class Wi extends Bi{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 ji=["BUFFERING","PLAYING","PAUSED_BY_USER","INTERRUPTED","FINISHED","FAILED"];class qi extends Bi{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 ji.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 Yi{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 Ji{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 $i extends Ji{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 Qi extends Ji{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 Zi{constructor(e){this.senders=[],e&&e.vizbee_url&&this.senders.push(new Qi(e)),e&&e.mixpanel_url&&e.mixpanel_token&&this.senders.push(new $i(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 Xi="UNKNOWN",en="NOT_FOUND";var tn=new class{constructor(){this.config={},this.commonProperties={},this.attributesProvidersList=[],this.isInitialized=!1,this.needToSetDistinctIdForVideoEvents=!0}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 Zi(e.metricsParams),this.appSessionId=Math.floor(1e10*Math.random()).toString()+"_"+Date.now(),this.screenSdkId=Yi.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(),Yi.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":en}}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!=Xi&&(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"],Xi),r.osNativeVersion=T.get(VizbeeTV.tv.deviceInfo,["os","sdkVersion"],Xi)),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=Xi,this.commonProperties.SCREEN_IDFV=Xi,this.commonProperties.SCREEN_HOMESSO_USER_INFO={user_login:Xi,user_login_type:Xi,user_name:Xi,user_subscription_renewal_type:Xi,user_subscription_type:Xi,user_subscription_value:Xi},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=en,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(){this.shouldTrack("SCREEN_LAUNCHED",this.commonProperties)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenLaunched");let e=T.extend({},this.commonProperties,this.buildPlayerProperties());this.track("SCREEN_LAUNCHED",e)})}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!=Xi||(t.adId=VizbeeTV.tv.adId||Xi),this.commonProperties.isAdTrackingDisabled&&this.commonProperties.isAdTrackingDisabled!=Xi||(t.isAdTrackingDisabled=VizbeeTV.tv.isAdTrackingDisabled||Xi),VizbeeTV.tv.deviceInfo&&(VizbeeTV.tv.deviceInfo.deviceId&&VizbeeTV.tv.deviceInfo.deviceId!=Xi&&(t.deviceId=VizbeeTV.tv.deviceInfo.deviceId),VizbeeTV.tv.deviceInfo.model&&VizbeeTV.tv.deviceInfo.model!=Xi&&(t.deviceModel=VizbeeTV.tv.deviceInfo.model)),this.setAttributesProviderProperties(t,t=>{this.setCommonProperties(t),e()})}};const nn="receiver_with_applets";class rn extends Bi{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){tn.init(this.appConfig);const t=VizbeeTV.tv.launchParamsDeferral;t&&"function"==typeof t.waitUntilReady?t.waitUntilReady().then(()=>{tn.refreshLaunchParamProperties(),tn.trackScreenLaunched()}):tn.trackScreenLaunched(),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"),tn.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||{};tn.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,tn.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&&tn.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&&tn.trackScreenTVSignin(e)}return e}handleNonSyncReceiveEvent(e){if(e&&e.type==St.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===nn||(VizbeeSDK.logger.d("MetricsExtension","handleNonSyncReceiveEvent","new sender connected, id = "+e),tn.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 sn extends Bi{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){tn.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"),tn.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"),tn.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 on=_(gt());class an extends Bi{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?on.enableTracks(i):on.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=on.getTracks(n),i=on.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 dn extends Bi{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}`),on.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=on.getAudioTracks(r),i=on.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 ln=[Ri,Ki,Hi,Gi,class extends Bi{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())}},Wi,class extends Bi{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")}},qi,sn,rn,class extends Bi{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 bt(St.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)}},an,dn],cn=[Ri,Ki,Hi,Gi,Wi,qi,sn,rn,an,dn,null];let un;class pn{createSync(e){let t=T.get(e,["syncInfo","syncMethod"],"pubnub").toLowerCase();return"googlecustom"==t?(un=this.getGoogleCustomSyncInstanceWitExtensions(e),un):"googledual"==t?(un=this.getGoogleDualSyncInstanceWitExtensions(e),un):(un=this.getDefaultSyncInstanceWitExtensions(e),un)}static getSync(){return un}getGoogleCustomSyncInstanceWitExtensions(e){return this.addExtensions(e,this.getGoogleCastSync(e),cn)}getGoogleDualSyncInstanceWitExtensions(e){let t=this.addExtensions(e,new xi(e),ln),i=this.addExtensions(e,this.getGoogleCastSync(e),cn),n=new Li(e);return n.addSyncInstance(t),n.addSyncInstance(i),n}getDefaultSyncInstanceWitExtensions(e){return this.addExtensions(e,new xi(e),ln)}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 hn=function(e){return e[e.NOT_CONNECTED=1]="NOT_CONNECTED",e[e.CONNECTING=2]="CONNECTING",e[e.CONNECTED=3]="CONNECTED",e}({});var gn,fn,vn,yn,mn,bn,Sn,_n,In=I(),Tn=ft(),En=function(){if(st)return rt;st=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(),rt={type:"VGAStateManager",app:{state:"app"},video:e,ad:t,reset:i,addListener:function(e){},removeListener:function(){}}}(),Vn=ze(),Pn=vt(),An=gt(),Cn=yt(),Dn=750;let kn;class wn{static getInstance(){return null==kn&&(kn=new wn),kn}getQueueManager(){return null==this.queueManager&&(this.queueManager=new null(null.getInstance())),VizbeeSDK.logger.debug("ContinuityContext::getQueueManager - returning queue manager",this.queueManager),this.queueManager}}var Nn,Mn,On,xn=I(),Ln=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}(),zn=xe,Rn=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)||(Dn=c);var u=[],p=[],h={};return t?(o=!0,i=En):(o=!1,i=Tn,An.setAppStateManager(Tn),Cn.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 pn;(r=t.createSync(n)).onReceive=function(t){if(t)switch(t.type){case St.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 St.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 St.SYNC_PRESENCE:o||function(e){VizbeeSDK.logger.debug("SyncController::presenceHandler() - connected users count",e);var t=In.extend({},h);h=In.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),Vn.updatePresence(e)}(t.data)}var r,s,l},r.connect(e),i.addListener(S),Vn.isAppSet()&&(VizbeeSDK.logger.debug("SyncController::connect appIsSet"),d=!0,g()),u.forEach(e=>{e(hn.CONNECTED)}),s=window.setInterval(_,Dn)},disconnect:function(){VizbeeSDK.logger.debug("SyncController::disconnect() called"),clearInterval(s),i.removeListener(S),u.forEach(e=>{e(hn.NOT_CONNECTED)}),f(),r.disconnect(),a=!1},isConnected:function(){return a},addSessionStateListener:function(e){u.push(e)},sessionState:function(){return a?hn.CONNECTED:hn.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,Pn.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(In.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,An.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()"),An.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);An.pause();break;case"play":if("video"!==i.app.state)return void VizbeeSDK.logger.warn("play requested when not in 'video' state",i.app.state);An.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";An.stop(u);break;case"exit":s={cmd:{ns:"video",name:"olleh",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}},r.send(s),An.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(In.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);An.seek(o);break;case"vol_up":"function"==typeof An.volumeUp&&An.volumeUp();break;case"vol_down":"function"==typeof An.volumeDown&&An.volumeDown();break;case"mute":"function"==typeof An.mute&&An.mute(!0);break;case"unmute":"function"==typeof An.mute&&An.mute(!1);break;case"set_tracks":"function"==typeof An.setTracks&&An.setTracks(e.cmd.param||[]);break;case"event":"function"==typeof An.onEvent&&e.einfo&&e.einfo.data&&(An.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),An.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=Vn.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}}},Kn=ft(),Un=ze(),Bn=vt(),Fn=gt(),Gn=ht(),Hn=function(){if(fn)return gn;fn=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 gn={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)}}}(),Wn=function(){if(bn)return mn;bn=1,I();var e=function(){if(yn)return vn;yn=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 vn={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 mn={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)}}}(),jn=yt(),qn=(_n||(_n=1,Sn={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)}}}),Sn),Yn=void 0,Jn=void 0,$n=!1,Qn=[],Zn="vzb0000000";function Xn(){if(On&&On.features&&On.features.shouldSyncDisconnectOnBackground){if($n)return;Yn?Yn.isConnected()||(VizbeeSDK.logger.i("SDK","onForeground","connecting VGA"),$n=!0,ir(Zn,function(){$n=!1,Jn&&!Jn.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET after VGA ",Mn.id),$n=!0,ir(Mn.id,function(){$n=!1}))})):Jn&&!Jn.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET ",Mn.id),$n=!0,ir(Mn.id,function(){$n=!1}))}}function er(){return VizbeeSDK.logger.i("SDK","onBackground"),On&&On.features&&On.features.shouldExitOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","exiting the app"),void VizbeeTV.tv.exit()):On&&On.features&&On.features.shouldSyncDisconnectOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","disconnecting from sync"),Yn&&Yn.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting VGA"),Yn.disconnect()),Jn&&Jn.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting APPLET"),Jn.disconnect()),void($n=!1)):void ar()}function tr(e){VizbeeSDK.logger.i("SDK","onEnd","sending olleh"),e&&e.isTeardown&&(Yn&&Yn.enableSynchronousPublish(),Jn&&Jn.enableSynchronousPublish()),ar()}function ir(e,t){Ln.getConfig({appId:e||Mn.id,deviceId:"",platform:VizbeeTV.tv.cloudPlatformName,platformModel:VizbeeTV.tv.platformModel,hostProxy:Mn.configServiceProxyHost},function(e){On=e,VizbeeSDK.logger.d("SDK","getConfig","got config=",On),On.customAttributesForMetrics=Mn.customAttributesForMetrics,On.features&&On.features.enableIpv6Lookup?zn.getIpv6Address(function(e){VizbeeSDK.logger.d("SDK","getIpv6Address","got response=",e),On.ipv6Address=e,nr(On,t)}):(VizbeeSDK.logger.d("SDK","getIpv6Address","skipped - enableIpv6Lookup not set in screen config"),nr(On,t))})}function nr(e,t){qn.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),$n=!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==Zn||e.features&&e.features.targetAppType==nn?(Zn=e.appId,Yn||(Yn=new Rn(e,!0)),Yn.connect(function(e){e?VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connected VGA"):VizbeeSDK.logger.e("SDK","onConfigAndDeviceIDReady","failed to connect VGA")})):(Jn||(VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","creating appletSyncController"),Jn=new Rn(e,!1),xn.each(Qn,e=>{e()})),VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connecting appletSyncController"),Jn.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),$n=!1,t&&t(void 0)})}function rr(e){VizbeeSDK.logger.d("SDK","setApp"),Un.setApp(e)}function sr(e){VizbeeSDK.logger.d("SDK","setVideo","video=",e),Fn.setVideo(e)}function or(e){Nn={vzb_ad_ima:null,vzb_ad_ssai:Wn,vzb_ad_ssai_avplay:null,vzb_ad_default:Hn}[e.toLowerCase()],Fn.setAdAdapter(Nn)}function ar(){jn.send({type:"sync_proxy_video_cmds",cmd:{ns:"video",name:"olleh",type:"int"}})}var dr={ContinuityContext:wn,QueueBase:null,QueueManager:null,QueueDelegate:null,QueueDelegateFactory:null},lr={VERSION:"7.8.41",wasVideoStartedByVizbee:function(){return Kn&&Kn.wasVideoStartedByVizbee()},init:function(e){VizbeeSDK.logger.i("SDK","init"),VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.addHandler("onForeground",Xn),VizbeeTV.tv.appLifeCycleManager.addHandler("onBackground",er),VizbeeTV.tv.appLifeCycleManager.addHandler("onEnd",tr)),Mn=e,VizbeeSDK.logger.i("SDK","onStart"),Mn&&Mn.id&&(function(e){var t;VizbeeSDK.logger.d("SDK","handleInitOptions"),e.video&&sr(e.video),e.app&&rr(e.app),e.videoAdapter&&(t=e.videoAdapter,VizbeeSDK.logger.d("SDK","setHostVideoAdapter","video=",t),Gn.setVideoAdapter(t)),e.adType&&or(e.adType),e.VGA&&e.isVGA&&Bn.setVGA(e.VGA)}(Mn),Fn.init(),ir())},setApp:rr,setVideo:sr,setVideoGuid:function(e,t){Fn.setId(e,t)},setVideoInfo:function(e){VizbeeSDK.logger.d("SDK","setVideoInfo","videoInfo=",e),Fn.setVideoInfo(e)},setVideoStop:function(){Fn.setVideoStop()},setAdsVideo:function(e){VizbeeSDK.logger.d("SDK","setAdsVideo","video=",e),Nn?Nn.setAdVideo(e):VizbeeSDK.logger.d("SDK","setAdsVideo","AdAdapter not configured; skipping")},getAdsAdapter:function(){return Nn},setAdType:or,sendXMessage:function(e,t,i){if(!Jn)return void VizbeeSDK.logger.e("XMessages",this.constructor.name,"sendXMessage","appletSyncController not initialized");if(xn.get(On,["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 jn.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`),jn.send(n)},syncProxy:jn,addSyncReadyListener:function(e){Qn.push(e)},removeSyncReadyListener:function(e){Qn=xn.without(Qn,e)},getSyncController:function(){return Jn},getMetricsManager:function(){return tn},wrapVideoCallbacks:Fn.wrapCallbacks,addVideoEventListener:Fn.addEventListener,removeVideoEventListener:Fn.removeEventListener,reset:function(){VizbeeSDK.logger.d("SDK","reset");try{Jn&&(Jn.disconnect(),Jn=void 0)}catch(e){VizbeeSDK.logger.e("SDK","reset","error disconnecting appletSyncController.",e)}try{Kn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppStateManager",e)}try{Un.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppAdapter",e)}try{Nn&&Nn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AdAdapter",e)}try{Fn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset"," error resetting VideoAdapter",e)}try{Gn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting HostVideoAdapter",e)}try{jn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting SyncProxy",e)}try{VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.removeHandler("onForeground",Xn),VizbeeTV.tv.appLifeCycleManager.removeHandler("onBackground",er),VizbeeTV.tv.appLifeCycleManager.removeHandler("onEnd",tr))}catch(e){VizbeeSDK.logger.e("SDK","reset","error removing app lifecycle handlers",e)}},framework:dr};window.VizbeeSDK||(window.VizbeeSDK={},VizbeeSDK.logger||(VizbeeSDK.logger=new Ve,VizbeeSDK.logger.setPrefix("[Vizbee]")));var cr=window.VZB;cr=lr,window.VZB=cr;class ur{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 pr={};class hr extends ur{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(),pr[i]&&!t.vgaAdapter?(this._apiWrapper=new pr[i],this._apiWrapper.setOptions(s),this._apiWrapper.initAppOnPlatform(e,t,i,n,r)):(this._apiWrapper=new ur,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 gr,fr,vr;class yr{constructor(){this.virtualAPIWrapper=ss,this.vzbOptions={}}static getInstance(){return null==gr&&(gr=new yr),gr}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 mr{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 br{get ContinuityContext(){return yr}get ContinuityOptions(){return mr}}class Sr{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 _r{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 Ir{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 Tr{constructor(e,t){this.type=e,this.data=t}}class Er{constructor(e,t){this.adType=e,this.playerElement=t,this.vtvPlayerEvent=new Tr}updateAdStatus(e){this._isValidAdStatus(e)?this._handleAdStatus(e):vizbee.logger.verbose("AdAdapter::updateAdStatus - invalid ad status")}_isValidAdStatus(e){return e instanceof Ir?-1!=[_r.AD_POD_WAITING,_r.AD_PREPARING,_r.AD_POD_START,_r.AD_POD_END,_r.AD_START,_r.AD_PLAYING,_r.AD_PAUSED,_r.AD_END,_r.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 Vr{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 Pr{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 Ar{static get UNKNOWN(){return"unknown"}static get SSAI(){return"ssai"}static get CSAI(){return"csai"}}class Cr{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 Dr{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 kr{constructor(){this._guid="",this._state=Dr.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 wr{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 Nr extends yr{constructor(){super(),this.appAdapter=new Sr,this.playerAdapter=void 0,this.adAdapter=void 0,this.adType=void 0}static getInstance(){return null==fr&&(fr=new Nr,vizbee.logger.d(this.constructor.name,"getInstance","created")),fr}getAppAdapter(){return this.appAdapter}setAppAdapter(e){e instanceof Sr&&(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 kr)return e}}getAdAdapter(e){return this.adAdapter}setAdAdapter(e){return e instanceof Er?this._isValidAdType(e.adType)?(this.adAdapter=e,this.setAdType(Ar.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 Cr;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 wr;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeSigninEventHandler(t)}if(this.appAdapter&&this.appAdapter.vizbeeEventHandler&&e){let t=new wr;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeEventHandler(t)}if(this.playerAdapter&&this.playerAdapter.vizbeeEventHandler&&e){let t=new wr;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==Pr.BITMOVIN&&(t.vtvPlayerListConfig=[{type:"bitmovin"}]),e.playerType==Pr.VIDEOJS&&(t.vtvPlayerListConfig=[{type:"videojs"}]),e.playerType==Pr.THEO&&(t.vtvPlayerListConfig=[{type:"theo"}]),e.playerType==Pr.SHAKA&&(t.vtvPlayerListConfig=[{type:"shaka"}]),t}_isValidVideoInfo(e){return e instanceof Cr||(vizbee.logger.w(this.constructor.name,"_isValidVideoInfo","videoInfo should be of type vizbee.continuity.messages.VideoInfo"),!1)}_isValidPlayerAdapter(e){return e instanceof Vr?!(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==Ar.SSAI||e==Ar.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==Ar.CSAI?"vzb_ad_default":this.adType==Ar.SSAI?e.playerType==Pr.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 kr))return;let t={};return e.guid&&(t.id=e.guid),e.videoUrl&&(t.videourl=e.videoUrl),!1!==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 Mr{constructor(e){e=e||{},this._getStatus=e.getStatus,this._getPlayer=e.getPlayer,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),t.dispatchOnTimeUpdate(t.currentTime())}}class Or extends Nr{constructor(){super(),this._statusPoller=void 0}static getInstance(){return null==vr&&(vr=new Or,vizbee.logger.d("ElementlessContinuityContext","getInstance","created")),vr}setPlayerAdapter(e){let t=super.setPlayerAdapter(e);return t&&this._updateStatusPoller(e),t}removePlayerAdapter(e){return this.notifyPlayerState(Dr.INTERRUPTED),this._stopStatusPoller(),super.removePlayerAdapter(e)}notifyPlayerState(e){const t=VizbeeTV&&VizbeeTV.tv&&VizbeeTV.tv.player?VizbeeTV.tv.player.currentPlayer:void 0;if(!t||!e)return;const i=this._mapStateToEventType(e);i&&this._fireOnPlayer(t,i)}_mapStateToEventType(e){return{loading:"loading",buffering:"loading",started:"playing",playing:"playing",paused:"paused",interrupted:"interrupted",ended:"ended",error:"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 Vr?!(!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;let t=this;this._statusPoller=new Mr({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,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 xr{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 Lr 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 Lr?this.extendedPlayer.basePlayer:void 0}isExtendedPlayerBasePlayer(){return this.extendedPlayer instanceof Y&&!(this.extendedPlayer instanceof Lr)}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 zr extends Vr{constructor(){super(Pr.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===Lr.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 Rr{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 Kr{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 Ur{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 Br extends Ur{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 Fr{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 Gr{constructor(e){this.uiConfig=e,this.popupMessageWithIconView=void 0}show(e=8){this.hide(),this.uiConfig&&"function"==typeof this.uiConfig.toJSON?(this.popupMessageWithIconView=new Fr,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 Hr={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"};class Wr{constructor(){this._message="This is a vizbee snackbar message",this._theme={color:"#FFFFFF",bgColor:"#7F98DE"},this._layout={position:Hr.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 qr{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 Yr=function(e){return e.ANDROID_MOBILE="Android",e.IOS="iOS",e.UNKNOWN="Unknown",e}({}),Jr=function(e){return e.ANDROID_MOBILE="ANDROID_MOBILE",e.IOS="IOS",e.UNKNOWN="UNKNOWN",e}({});function $r(e){switch(e){case Yr.ANDROID_MOBILE:return Jr.ANDROID_MOBILE;case Yr.IOS:return Jr.IOS;case Yr.UNKNOWN:default:return Jr.UNKNOWN}}let Qr=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({}),Zr=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({});class Xr{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===Zr.JOIN?Qr.JOIN:Qr.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:$r(null==e||null===(u=e.ssinfo)||void 0===u?void 0:u.REMOTE_DEVICE_TYPE)}}}jr(Xr,"LOG_TAG","VizbeeBicastMemberPresenceClientImpl");class es{constructor(){jr(this,"_messagingClient",null),jr(this,"_presenceClient",null)}getMessagingClient(){return this._messagingClient||(this._messagingClient=new qr),this._messagingClient}getPresenceClient(){return this._presenceClient||(this._presenceClient=new Xr),this._presenceClient}}class ts{constructor(){if(jr(this,"session",null),jr(this,"sessionState",hn.NOT_CONNECTED),jr(this,"sessionStateListeners",[]),jr(this,"syncController",null),jr(this,"onSessionStateChanged",e=>{var t,i;switch(this.sessionState=e,e){case hn.CONNECTED:null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.info("VizbeeBicastSessionManager","onSessionStateChanged","CONNECTED"),this.session=new es,this.sessionStateListeners.forEach(e=>e.onSessionStateChanged(hn.CONNECTED));break;case hn.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(hn.NOT_CONNECTED))}}),ts.instance)return ts.instance;this.init(),ts.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:hn.NOT_CONNECTED,this.sessionState===hn.CONNECTED&&(this.session=new es),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===hn.CONNECTING}isConnected(){return this.sessionState===hn.CONNECTED}}class is{constructor(){if(jr(this,"presenceCallbacks",[]),jr(this,"vizbeeSession",null),is.instance)return is.instance;this.init(),is.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===hn.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 ns extends br{constructor(){super()}get ContinuityContext(){return Or}get adapters(){return{AppAdapter:Sr,PlayerAdapter:Vr,BasePlayerAdapter:xr,AVPlayerAdapter:zr,PlayerType:Pr,AdAdapter:Er,AdType:Ar,VideoStopReason:Rr}}get messages(){return{VizbeeEvent:wr,VideoInfo:Cr,VideoStatus:kr,AdEventType:_r,AdStatus:Ir,PlayerState:Dr,SubtitleTrack:Br}}get analytics(){return{AnalyticsProvider:Kr}}get ui(){return{LayoutPosition:Hr,Snackbar:Gr,SnackbarUIConfig:Wr}}get analytics(){return{AnalyticsProvider:Kr}}get ui(){return{LayoutPosition:Hr,Snackbar:Gr,SnackbarUIConfig:Wr}}get xmessages(){return{VizbeeBicastSessionManager:ts,VizbeeBicastSession:es,VizbeeMessagingClient:void 0,VizbeePresenceManager:is}}}var rs=new class extends ns{constructor(){super()}},ss=new class extends hr{constructor(){super()}get continuity(){return rs}get framework(){return rs}};if(ss.logger=new Ve,ss.logger.setPrefix("[Vizbee]"),"undefined"!=typeof window){if(window.VizbeeSDK=ss,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"))}