vizbee-qa-sdk-lgwebos-es6 1.0.0

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.
Files changed (2) hide show
  1. package/index.js +1 -0
  2. package/package.json +10 -0
package/index.js ADDED
@@ -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="onForeground",n="onBackground",r="subtitle",s="audio",a="bitmovin",o="videojs",d="theo",l="shaka",c="msf-lib-loaded";class u{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("onEnd")}set isAppExiting(e){this.isAppExitInProgress=e}get isAppExiting(){return this.isAppExitInProgress}createPlayer(){throw new TypeError("Platform::createPlayer() - Abstract method.")}}class p{constructor(e,t){if("BaseEvent"===this.constructor.name)throw new TypeError("BaseEvent::constructor() - Abstract class.");this.nativeEvent=e,this.source=t}}class h extends p{constructor(e,t){super(e,t)}}class g extends h{constructor(e,t){if(!(t instanceof M))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 f{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 p))throw new TypeError("BaseEventDispatcher::dispatchEvent() - event must be instance of BaseEvent.");this._eventHandlers.forEach(t=>{t instanceof Function&&t(e)})}reset(){this._eventHandlers=[]}}class v extends f{constructor(){if(super(),"BaseInputDevice"===this.constructor.name)throw new TypeError("BaseInputDevice::constructor() - Abstract class.")}}var y,m,b,S={exports:{}},_=S.exports;function I(){return y||(y=1,e=S,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},a=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(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 o)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)}}o.prototype.catch=function(e){return this.then(null,e)},o.prototype.then=function(e,t){var i=new o(n);return d(this,new p(e,t,i)),i},o.all=function(){var e=Array.prototype.slice.call(1===arguments.length&&a(arguments[0])?arguments[0]:arguments);return new o(function(t,i){if(0===e.length)return t([]);var n=e.length;function r(s,a){try{if(a&&("object"==typeof a||"function"==typeof a)){var o=a.then;if("function"==typeof o)return void o.call(a,function(e){r(s,e)},i)}e[s]=a,0===--n&&t(e)}catch(e){i(e)}}for(var s=0;s<e.length;s++)r(s,e[s])})},o.resolve=function(e){return e&&"object"==typeof e&&e.constructor===o?e:new o(function(t){t(e)})},o.reject=function(e){return new o(function(t,i){i(e)})},o.race=function(e){return new o(function(t,i){for(var n=0,r=e.length;n<r;n++)e[n].then(t,i)})},o._setImmediateFn=function(e){r=e},o._setUnhandledRejectionFn=function(e){s=e},e.exports?e.exports=o:t.Promise||(t.Promise=o)}(_)),S.exports;var e}function E(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function T(){if(b)return m;b=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 m=e}var V=E(T());let P=[],A=[],C=[],w=document.getElementsByTagName("HEAD")[0],D=document.getElementsByTagName("BODY")[0];class k{static xchangeHLSUrl(e,t,i,n,r,s){var a="unknown",o="unknown";t&&(a=t),i&&(o=i);var d="https://hlsxchange.claspws.tv/"+a+"/"+o;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"),w.appendChild(t),C.push(t),t.setAttribute("href",e)}static loadSynchronousScripts(e){var t=t||void 0;if(t||(t=I()),void 0===k.loadSynchronousScripts.scripts&&(k.loadSynchronousScripts.scripts=[],k.loadSynchronousScripts.index=-1,k.loadSynchronousScripts.loading=!1,k.loadSynchronousScripts.next=function(){if(!k.loadSynchronousScripts.loading){k.loadSynchronousScripts.loading=!0;var e=k.loadSynchronousScripts.scripts[++k.loadSynchronousScripts.index],t=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.src=e.src,i.onload=()=>{k.loadSynchronousScripts.loading=!1,k.loadSynchronousScripts.index<k.loadSynchronousScripts.scripts.length-1&&k.loadSynchronousScripts.next(),e.resolve()},t.appendChild(i)}}),e){for(var i=0;i<k.loadSynchronousScripts.scripts.length;i++)if(k.loadSynchronousScripts.scripts[i].src==e)return k.loadSynchronousScripts.scripts[i].promise;var n={src:e};n.promise=new t(e=>{n.resolve=e}),k.loadSynchronousScripts.scripts.push(n),k.loadSynchronousScripts.next()}return k.loadSynchronousScripts.scripts[k.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||(()=>{}),w.appendChild(n),P.push(n),n.setAttribute("src",e)}static loadScriptToBody(e,t,i){if(!e||!(e instanceof String||"string"==typeof e))throw new TypeError("Util::loadScript - Url must be a string.");t=!(!t&&void 0!==t);var n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("async",t),n.onload=i||(()=>{}),D.appendChild(n),A.push(n),n.setAttribute("src",e)}static clearLoadedScripts(){for(let e=0;e<P.length;e++)P[e]&&P[e]instanceof Node&&(w.removeChild(P[e]),delete P[e])}static clearBodyLoadedScripts(){for(let e=0;e<A.length;e++)A[e]&&A[e]instanceof Node&&(D.removeChild(A[e]),delete A[e])}static clearLoadedStyleSheets(){for(let e=0;e<C.length;e++)C[e]&&C[e]instanceof Node&&(C[e].disabled=!0,w.removeChild(C[e]),delete C[e])}static clearAllLoadedScriptsAndStyleSheets(){k.clearLoadedScripts(),k.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,a=n.left,o=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)&&a>=0&&a<=(u||l)||s>=0&&s<=(c||d)&&o>=0&&o<=(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);k.myscroll(n,t,i,i.scrollTop,r-t,0)}static myscroll(e,t,i,n,r,s){++s>10||e.children.length>0&&k.elementInViewport(e.children.item(0),!0,t)||(i.scrollTop=n+(r-n)/10*s,setTimeout(function(){k.myscroll(e,t,i,n,r,s)},20))}static xhr(e){var t=t||void 0;return t||(t=I()),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 a=void 0;s.onreadystatechange=function(o){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}),a=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=o.target;e.format=e.format||"json","json"===e.format?(c=c.response?JSON.parse(c.response):{}).headers?Object.assign(c.headers,a):c.headers=a:"xml"===e.format&&(c=c.responseXML),e.isFullResponse?t({xhr:o.target,data:c,headers:a}):t(c)}catch(o){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(V.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 a="";if(i)switch(i.constructor){case Number:a=i===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+i;break;case String:a="; expires="+i;break;case Date:a="; expires="+i.toUTCString()}return document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+a+(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]=k.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]=k.deepMerge(e[i],t[i]):n[i]=t[i]})),n}static isEqual(e,t){return V.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 a=!0;for(var o in i)a=!1,e(i[o],n?n+"."+o:o);a&&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,a="";r=t.exec(n);)s=s[a]||(s[a]=r[2]?[]:{}),a=r[2]||r[1];s[a]=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)k.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]=k.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+=k.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+=k.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(!V.isString(t))return e;if(!V.isString(e))return e;if(-1!=e.indexOf(t)){let i=e.trim().split(t);return V.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&&k.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 V.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=I()),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(V.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 N=!1;class M extends v{constructor(e){if(super(),VizbeeTV.logger.debug("constructing BaseTVRemote"),this.eventType=g,!(e&&e instanceof u))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{N=!0;let e="keydown";document.addEventListener(e,e=>{this.dispatchEvent(new g(e,this))})}catch(e){VizbeeTV.logger.error("registerListener error - ",e.message,e)}}sendKeyEvent(e){try{var t=k.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(M.keys.play)}sendPause(){this.sendKeyEvent(M.keys.pause)}sendStop(){this.sendKeyEvent(M.keys.stop)}}class x extends M{get keyCodeMap(){return{38:M.keys.up,40:M.keys.down,37:M.keys.left,39:M.keys.right,13:M.keys.select,415:M.keys.play,19:M.keys.pause,413:M.keys.stop,417:M.keys.ffw,412:M.keys.rw,461:M.keys.back,1e3:M.keys.exit}}}class O{init(){this.player=void 0}setPlayer(e){this.player=e}getPlayer(){return this.player}getTracks(e){return[]}getEnabledTracks(e){return[]}enableTracks(e=[]){}disableTracks(e){}}class L{static getInstance(e,t){}}class z extends O{constructor(){super(),this.init()}init(){this.subtitleInstance=void 0,this.playerType=void 0,this.subtitleType=void 0,this.videoPlayer=void 0}setPlayerWithType(e,t){e?t?(this.playerType=e,this.playerType==a?this.videoPlayer=t.bitmovinPlayer:this.playerType==o?this.videoPlayer=t.playerElement:this.playerType==d?this.videoPlayer=t.playerInstance:this.playerType==l?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=L.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 R={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 K{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);V.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]=R[e]||e,VizbeeTV.logger.verbose("BaseAudio::_setTrackLanguageCodeToNameMap - updated _setTrackLanguageCodeToNameMap = ",this.trackLanguageCodeToNameMap))}_reset(){this.trackIdStringToNumberMap={},this.trackLanguageCodeToNameMap={}}}class H{static getInstance(e){}}class U extends K{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==a?this.videoPlayer=t.bitmovinPlayer:this.playerType==o?this.videoPlayer=t.playerElement:this.playerType==l?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=H.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 F{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 u))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 z,this.audioDelegate=new U,this.streamQualityInfo=new F}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=a:-1!=t.indexOf("videojs")?e=o:-1!=t.indexOf("theo")?e=d:-1!=t.indexOf("shaka")?e=l:-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)?k.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=k.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==r?this.subtitlesDelegate&&this.subtitlesDelegate.isReady()?this.subtitlesDelegate.getTracks(e):[]:e==s&&this.audioDelegate&&this.audioDelegate.isReady()?this.audioDelegate.getTracks(e):[]}getEnabledTracks(e){return e==r?this.subtitlesDelegate&&this.subtitlesDelegate.isReady()?this.subtitlesDelegate.getEnabledTracks(e):[]:e==s&&this.audioDelegate&&this.audioDelegate.isReady()?this.audioDelegate.getEnabledTracks(e):[]}getSubtitleTypeFromVideoInfo(e){return"any"}enableTracks(e){this.subtitlesDelegate.isReady()&&this.subtitlesDelegate.enableTracks(e)}disableTracks(e){this.subtitlesDelegate.isReady()&&this.subtitlesDelegate.disableTracks(e)}changeAudioTrack(e){this.audioDelegate.isReady()?this.audioDelegate.setActiveTrack(e):VizbeeTV.logger.warn(this.constructor.name+"::changeAudioTrack - audio delegate is not ready")}getStreamQualityInfo(){return this.streamQualityInfo&&this.streamQualityInfo.toJSON()}setStreamQualityInfo(e){this.streamQualityInfo&&this.streamQualityInfo.fromJSON(e)}resetStreamQualityInfo(){this.streamQualityInfo&&this.streamQualityInfo.reset()}setTracks(e){}getCurrentTrack(){var e;return this.videoInfo.tracks&&this.videoInfo.tracks.length>0&&isFinite(this.videoInfo.activeTrackId)&&(e=this.videoInfo.tracks.find(e=>this.videoInfo.activeTrackId==e.trackId)),e}}class G extends B{extend(){throw new TypeError("BasePlayerExtensible::extend() - Abstract method.")}beforeStart(){throw new TypeError("BasePlayerExtensible::beforeStart() - Abstract method.")}}class W extends G{constructor(e){super(e),this.playerElement=this.platformConfig.videoElement,this.currentSrc="",this.eventListenersSet=!1,this.bypassCanPlay=!1,this.hlsxchange=!1,this.invokedWithStartVideo=!1,this.startedPlaying=!1,this.finishedStartSeek=!1,this.isVideoStopped=!1,this.isVideoEnded=!1,this.logEvents=["abort","error","canplay","canplaythrough","durationchange","emptied","ended","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","volumechange","waiting"],this.playbackEvents=["canplay","canplaythrough","durationchange","loadeddata","loadedmetadata","pause","play","playing","seeked","seeking"],this.loadingEvents=["loadeddata","loadedmetadata"],this.startedEvents=["loadedmetadata"],this.platformConfig.standalone?this.registerEventHandlers():this.configurePlayerElement()}configurePlayerElement(){let e=this.playerElement;e.removeAttribute("style"),e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.top="0px",e.style.left="0px",e.style.backgroundColor="black",e.style.display="block"}baseStart(e){super.start(e)}start(e){this.baseStart(e),this.platformConfig.standalone||this.configurePlayerElement(),this.invokedWithStartVideo=!0,VizbeeTV.logger.debug("HtmlPlayer::Start() -- ",this.currentSrc,this.videoInfo.src),this.startedPlaying=!1,this.finishedStartSeek=!1,VizbeeTV.logger.debug("HtmlPlayer::start() -- Playing video"),this.videoInfo.src=this.getHlsxchangeUrl(),VizbeeTV.logger.info("HtmlPlayer::start() - video url ",this.videoInfo.src),""!=this.playerElement.src&&(VizbeeTV.logger.debug("HtmlPlayer::start - setting src to empty"),this.playerElement.src=""),this.playerElement.removeAttribute("src"),this.playerElement.removeAttribute("type"),this.playerElement.setAttribute("src",this.videoInfo.src),this.videoInfo.src.lastIndexOf(".m3u8")>=0||this.videoInfo.src.lastIndexOf("m3u")>=0?this.playerElement.setAttribute("type","application/vnd.apple.mpegurl"):this.videoInfo.src.lastIndexOf(".ism")>=0?this.playerElement.setAttribute("type","application/vnd.ms-sstr+xml"):this.videoInfo.src.lastIndexOf(".mpd")>=0?this.playerElement.setAttribute("type","application/dash+xml"):this.playerElement.setAttribute("type","video/mp4"),this.registerEventHandlers(),this.bypassCanPlay=!1,this.playerElement.load(),this.currentSrc=this.videoInfo.src}play(){VizbeeTV.logger.debug("HtmlPlayer::play() called."),this.playerElement.play(),this.bypassCanPlay=!1}pause(){VizbeeTV.logger.debug("HtmlPlayer::pause() called."),this.playerElement.pause(),void 0===this.playerElement.paused&&(this.bypassCanPlay=!0)}seek(e){VizbeeTV.logger.debug("HtmlPlayer::seek() called with time ",e);var t=e/1e3;0==t&&(t=1),this.playerElement.currentTime=t}togglePlayPause(){this.playerElement.paused?this.playerElement.play():this.playerElement.pause()}stop(e){this.isVideoStopped=!0,this.playerElement.src&&this.playerElement.src!=location.origin+location.pathname&&(this.playerElement.src=""),this.videoInfo&&(this.videoInfo.src=""),this.currentSrc=""}currentTime(){return this.playerElement.currentTime}getDuration(){return this.playerElement.duration}destroy(){return new Promise((e,t)=>{this.unregisterEventHandlers(),super.destroy(),e()})}registerEventHandlers(){VizbeeTV.logger.debug("HtmlPlayer::registerEventHandlers called",this,this.playerElement),this.playerElement&&(this.eventListenersSet||(this._eventCallbackHandles={logEvent:e=>this.defaultLogHandler(e),loadingEvent:e=>this.loadingHandler(e),startedEvent:e=>this.startedEventHandler(e),canplayEvent:e=>this.videoCanPlayHandler(e),playEvent:e=>this.videoPlayHandler(e),playingEvent:e=>this.videoPlayingHandler(e),seekedEvent:e=>this.videoSeekedHandler(e),pauseEvent:e=>this.videoPausedHandler(e),bufferingEvent:e=>this.bufferingHandler(e),timeupdateEvent:e=>this.timeUpdateHandler(e),endedEvent:()=>this.endedHandler(),errorEvent:e=>this.errorHandler(e),abortEvent:e=>this.abortHandler(e)},this.logEvents.forEach(e=>{this.playerElement.addEventListener(e,this._eventCallbackHandles.logEvent,!1)}),this.playbackEvents.forEach(e=>{this.playerElement.addEventListener(e,this._eventCallbackHandles.playbackEvent,!1)}),this.loadingEvents.forEach(e=>{this.playerElement.addEventListener(e,this._eventCallbackHandles.loadingEvent,!1)}),this.startedEvents.forEach(e=>{this.playerElement.addEventListener(e,this._eventCallbackHandles.startedEvent,!1)}),this.playerElement.addEventListener("canplay",this._eventCallbackHandles.canplayEvent,!1),this.playerElement.addEventListener("play",this._eventCallbackHandles.playEvent,!1),this.playerElement.addEventListener("playing",this._eventCallbackHandles.playingEvent,!1),this.playerElement.addEventListener("seeked",this._eventCallbackHandles.seekedEvent,!1),this.playerElement.addEventListener("pause",this._eventCallbackHandles.pauseEvent,!1),this.playerElement.addEventListener("seeking",this._eventCallbackHandles.bufferingEvent,!1),this.playerElement.addEventListener("timeupdate",this._eventCallbackHandles.timeupdateEvent,!1),this.playerElement.addEventListener("ended",this._eventCallbackHandles.endedEvent,!1),this.playerElement.addEventListener("error",this._eventCallbackHandles.errorEvent,!1),this.playerElement.addEventListener("abort",this._eventCallbackHandles.abortEvent,!1),this.eventListenersSet=!0))}unregisterEventHandlers(){VizbeeTV.logger.debug("HtmlPlayer::unregisterEventHandlers called"),this.playerElement&&this.eventListenersSet&&this._eventCallbackHandles&&(this.logEvents.forEach(e=>{this.playerElement.removeEventListener(e,this._eventCallbackHandles.logEvent)}),this.playbackEvents.forEach(e=>{this.playerElement.removeEventListener(e,this._eventCallbackHandles.playbackEvent)}),this.loadingEvents.forEach(e=>{this.playerElement.removeEventListener(e,this._eventCallbackHandles.loadingEvent)}),this.startedEvents.forEach(e=>{this.playerElement.removeEventListener(e,this._eventCallbackHandles.startedEvent)}),this.playerElement.removeEventListener("canplay",this._eventCallbackHandles.canplayEvent),this.playerElement.removeEventListener("play",this._eventCallbackHandles.playEvent),this.playerElement.removeEventListener("playing",this._eventCallbackHandles.playingEvent),this.playerElement.removeEventListener("seeked",this._eventCallbackHandles.seekedEvent),this.playerElement.removeEventListener("pause",this._eventCallbackHandles.pauseEvent),this.playerElement.removeEventListener("seeking",this._eventCallbackHandles.bufferingEvent),this.playerElement.removeEventListener("timeupdate",this._eventCallbackHandles.timeupdateEvent),this.playerElement.removeEventListener("ended",this._eventCallbackHandles.endedEvent),this.playerElement.removeEventListener("error",this._eventCallbackHandles.errorEvent),this.playerElement.removeEventListener("abort",this._eventCallbackHandles.abortEvent),this.eventListenersSet=!1)}defaultLogHandler(e){VizbeeTV.logger.debug("HtmlPlayer::defaultLogHandler ["+this.getCurrentState()+"] "+e.type+" -- ",e,this.currentSrc,this.getDuration(),this.currentTime(),this),VizbeeTV.logger.debug("---------------------"),VizbeeTV.logger.debug("readyState",this.playerElement.readyState),VizbeeTV.logger.debug("---------------------")}loadingHandler(e){this.isVideoEnded=!1,this.dispatchOnLoading()}startedEventHandler(e){this.dispatchOnStarted()}videoCanPlayHandler(e){if(this.invokedWithStartVideo&&(VizbeeTV.logger.debug("HtmlPlayer::videoCanPlayHandler::canplay - checking and playing video",this,this.playerElement.duration,this.startedPlaying),this.isVideoEnded=!1,!this.startedPlaying)){this.videoInfo&&this.videoInfo.startTime||(this.videoInfo=this.videoInfo||{},this.videoInfo.startTime=0);var t=this.videoInfo.startTime/1e3;if(VizbeeTV.logger.debug("HtmlPlayer::videoCanPlayHandler::canplay - starttime = "+t),!this.finishedStartSeek&&0!=t)try{VizbeeTV.logger.debug("HtmlPlayer::videoCanPlayHandler::canplay - seeking to start time = ",t),this.finishedStartSeek=!0,this.playerElement.currentTime=t||0}catch(e){VizbeeTV.logger.error("HtmlPlayer::videoCanPlayHandler::canplay - Error setting start time for video",e)}this.bypassCanPlay||(VizbeeTV.tv.player.play(!0),this.startedPlaying=!0)}}videoPlayHandler(e){this.isVideoEnded=!1,this.dispatchOnPlaying()}videoPlayingHandler(e){this.isVideoEnded=!1,this.dispatchOnPlaying()}videoPausedHandler(e){this.dispatchOnPaused()}videoSeekedHandler(e){this.dispatchOnBufferingComplete(),this.playerElement.paused?this.dispatchOnPaused():this.dispatchOnPlaying()}bufferingHandler(e){this.isVideoEnded=!1,this.dispatchOnBuffering()}timeUpdateHandler(e){this.playerElement.paused||this.dispatchOnTimeUpdate(e)}endedHandler(){this.isVideoEnded=!0,this.dispatchOnEnded()}abortHandler(e){let t,i=this.buildErrorEvent(0,"UNKNOWN",{});i.data=e,e&&e.currentTarget&&e.currentTarget.error?t=e.currentTarget.error:e&&e.target&&e.target.error&&(t=e.target.error),t&&void 0!==t.code&&null!=t.code&&(i.code=t.code),i.reason="STOP_BY_USER",this.dispatchOnInterrupted(i)||this.errorHandler(e),this.isVideoStopped=!1}errorHandler(e){let t,i=this.buildErrorEvent(0,"UNKNOWN",{});if(i.data=e,e&&e.currentTarget&&e.currentTarget.error?t=e.currentTarget.error:e&&e.target&&e.target.error&&(t=e.target.error),this.isVideoStopped)return this.isVideoStopped=!1,i.reason="STOP_BY_USER",void this.dispatchOnError(i);if(t&&void 0!==t.code&&null!=t.code)switch(i.code=t.code,t.code){case t.MEDIA_ERR_ABORTED:i.reason="MEDIA_ERR_ABORTED",VizbeeTV.logger.error("HtmlPlayer::ERROR ** You aborted the video playback.");break;case t.MEDIA_ERR_NETWORK:i.reason="MEDIA_ERR_NETWORK",VizbeeTV.logger.error("HtmlPlayer::ERROR ** A network error caused the video download to fail part-way.");break;case t.MEDIA_ERR_DECODE:i.reason="MEDIA_ERR_DECODE",VizbeeTV.logger.error("HtmlPlayer::ERROR ** The video playback was aborted due to a corruption problem or because the video used features your browser did not support.");break;case t.MEDIA_ERR_SRC_NOT_SUPPORTED:i.reason="MEDIA_ERR_SRC_NOT_SUPPORTED",VizbeeTV.logger.error("HtmlPlayer::ERROR ** The video could not be loaded, either because the server or network failed or because the format is not supported.");break;default:VizbeeTV.logger.error("HtmlPlayer::ERROR ** An unknown error occurred.",t)}let n=this.getAppVideoStartErrorInfo(i.code,i.reason);i.code=n.errorCode,i.reason=n.errorReason,VizbeeTV.logger.error("HtmlPlayer::ErrorHandler ["+this.currentState+"]",i.reason,i.code),this.dispatchOnError(i)}}class j extends W{constructor(e){super(e),VizbeeTV.logger.debug("Inside LGWebOSHtmlPlayer constructor")}loadingHandler(e){this.videoInfo.isLive||super.loadingHandler(e)}videoCanPlayHandler(e){VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler::canplay : duration="+this.duration+" startedPlaying="+this.startedPlaying+" finishedStartSeek="+this.finishedStartSeek),this.startedPlaying||(VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler::canplay - issuing play command"),this.bypassCanPlay||(VizbeeTV.tv.player.play(!0),this.startedPlaying=!0))}videoPlayHandler(e){super.videoPlayHandler(e),VizbeeTV.logger.debug("LGWebOSHtmlPlayer::videoPlayHandler",VizbeeTV.tv.player.videoInfo.startTime,this.finishedStartSeek,this),null==this.videoInfo.startTime&&(this.videoInfo.startTime=0);var t=this.videoInfo.startTime/1e3;if(!this.finishedStartSeek&&0!=t)try{var i=this;setTimeout(function(){VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler - seeking to start time"),i.finishedStartSeek=!0,i.playerElement.currentTime=t},1e3)}catch(e){VizbeeTV.logger.error("LGHtmlPlayer::start::canplay - Error setting start time for video",e)}}}class q extends W{constructor(e){super(e),VizbeeTV.logger.debug("LGWebOS2015HtmlPlayer::constructor")}start(e){if(VizbeeTV.logger.debug("LGWebOS2015HtmlPlayer::Start() -- ",this.currentSrc,e.src),this._emptyVideoSource(),this.baseStart(e),this.configurePlayerElement(),this.invokedWithStartVideo=!0,this.startedPlaying=!1,this.finishedStartSeek=!1,this.videoInfo.maxStartBitrateInBps=7e6,this.videoInfo.maxStartBitrateInBps){var t={option:{adaptiveStreaming:{bps:{start:this.videoInfo.maxStartBitrateInBps}}}},i=encodeURI(JSON.stringify(t));this.videoInfo.videoMimeTypeSuffix=";mediaOption="+i,VizbeeTV.logger.debug("LGWebOS2015HtmlPlayer::start - setting videoMimeTypeSuffix to "+this.videoInfo.videoMimeTypeSuffix+" for src= "+this.videoInfo.src)}this.videoInfo.src=this.getHlsxchangeUrl(),VizbeeTV.logger.info("LGWebOS2015HtmlPlayer::start() - video url ",this.videoInfo.src);var n="";n=this.videoInfo.src.lastIndexOf(".m3u8")>=0||this.videoInfo.src.lastIndexOf("m3u")>=0?"application/vnd.apple.mpegurl":this.videoInfo.src.lastIndexOf(".ism")>=0?"application/vnd.ms-sstr+xml":this.videoInfo.src.lastIndexOf(".mpd")>=0?"application/dash+xml":"video/mp4",this.videoInfo.videoMimeTypeSuffix&&(n+=this.videoInfo.videoMimeTypeSuffix),VizbeeTV.logger.debug("LGWebOS2015HtmlPlayer::start - setting type to "+n+" for src= "+this.videoInfo.src),this._addVideoSource(n),this.eventListenersSet||(this.registerEventHandlers(),this.eventListenersSet=!0),this.bypassCanPlay=!1,this.playerElement.load(),this.currentSrc=this.videoInfo.src}stop(){this.isVideoStopped=!0,this._emptyVideoSource(),this.currentSrc=""}_addVideoSource(e){var t=this.playerElement.getElementsByTagName("source");if(t.length>0)t[0].setAttribute("src",this.videoInfo.src),t[0].setAttribute("type",e);else{var i=document.createElement("source");i.setAttribute("src",this.videoInfo.src),i.setAttribute("type",e),i.addEventListener("error",e=>{VizbeeTV.logger.debug("LGWebOS2015HtmlPlayer::sourceErrorHandler ["+this.getCurrentState()+"] ",e),-1!=[this.playerState.PREPARING,this.playerState.LOADING,this.playerState.BUFFERING,this.playerState.STARTED,this.playerState.PLAYING,this.playerState.PAUSED].indexOf(this.getCurrentState())&&this.errorHandler(e)}),this.playerElement.appendChild(i)}}_emptyVideoSource(){VizbeeTV.logger.debug("LGWebOS2015HtmlPlayer::_emptyVideoSource",this.playerElement.src);var e=this.playerElement.getElementsByTagName("source");if(e.length){for(let t=0;t<e.length;t++)e[t].src="";this.playerElement.load()}}getName(){return"LGWebOSHtmlPlayer"}}var Y=null,J=null,$=null,X=null,Q=null;class Z extends G{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 ee{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 te extends ee{constructor(){super(),this.deviceIdAlgorithm="VTV_URL_PARAMS",this.storageDeviceIdKey="VTV_"+this.deviceIdKey}uniqueDeviceID(e,t){var i=(k.getUrlVars()||{})[this.deviceIdKey];if(i)k.docCookies.setItem(this.storageDeviceIdKey,i,1/0,"/");else{var n=k.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 ie{constructor(){}isLaunchedbyVizbee(){throw new TypeError("BaseLaunchParams::isLaunchedbyVizbee() - Abstract method. This method must be implemented by derived classes.")}getLaunchParams(e){}setLaunchParams(e){}}class ne extends ie{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 re{constructor(){var e,t,i,n,r;this._uaParser=(e=navigator.userAgent,i={name:"",version:""},n={name:"",version:""},r={name:"",version:""},(t=/Tizen\s*([\d.]+)?/i.exec(e))?(i.name="Tizen",i.version=t[1]||""):(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=/SamsungBrowser\/([\d.]+)/i.exec(e))?(n.name="Samsung Internet",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 se={6:"webOS TV 6.0",7:"webOS TV 22",8:"webOS TV 23",9:"webOS TV 24"};class ae extends re{constructor(){super(),this._deviceInfo={};try{setTimeout(()=>{window.webOS&&webOS.deviceInfo(e=>{e&&(setTimeout(()=>{},1e4),this._deviceInfo=V.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:se[(this._deviceInfo.sdkVersion||t).split(".")[0]]||t}}}class oe{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 de extends oe{constructor(){super()}}class le{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 ce extends le{constructor(){super(),this._didBackgroundOnce=!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)}})}_emitOnBackground(){this._didBackgroundOnce=!0,this.eventMap[n].forEach(e=>{VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnBackground"),e.apply({})})}_emitOnForeground(){this._didBackgroundOnce&&this.eventMap[i].forEach(e=>{VizbeeTV.logger.info("LGWebOSAppLifeCycleManager::_emitOnForeground"),e.apply({})})}}class ue extends u{constructor(e){super(e),this.deviceId=new te,this.launchParams=new ne,this._deviceInfo=new ae,this._networkInfo=new de,this.lgWebOSAppLifeCycleManager=new ce,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=j,e.htmlPlayer=j):(VizbeeTV.logger.d("LGWebOS","createPlayer","WebOS 2014 detected - using html player"),e={nativePlayer:q,htmlPlayer:q,bitmovinPlayer:J,modularBitmovinPlayer:J,videoJSPlayer:$,theoPlayer:X,shakaPlayer:Q,topPlayer:Y}),this.player=new Z(this,e),this.player}createInputDevice(){let e=new x(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 pe extends ee{constructor(){super(),this.deviceIdAlgorithm="VTV_INTERNAL_IP"}}class he extends pe{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)}),a=new Promise((e,t)=>{i=this._getInternalIPWithWebRTC(i=>{if(i&&i.length>0){for(var n="",r=0;r<i.length;r++)if(k.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([a,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 ge extends ie{constructor(){super()}isLaunchedbyVizbee(){let e=this.getLaunchParams();return!(!e||void 0===e.vzb)}getLaunchParams(){return window.webOSDev?webOSDev.launchParams():void 0}}const fe={6:"webOS TV 6.0",7:"webOS TV 22",8:"webOS TV 23",9:"webOS TV 24"};class ve extends re{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=V.extend({},this._deviceInfo,e):VizbeeTV.logger.warn('LGWebOSNativeDeviceInfo::constructor - "getSystemInfo" failed to fetch deviceInfo')}}),webOS.deviceInfo(e=>{e&&(this._deviceInfo=V.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:fe[(this._deviceInfo.sdkVersion||t).split(".")[0]]||t}}}class ye extends oe{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"===V.get(this._networkInfo,["wifi","state"])?e="WIFI":"connected"===V.get(this._networkInfo,["wired","state"])&&(e="WIRED"),e}get isWifiConnected(){return"connected"===V.get(this._networkInfo,["wifi","state"])}get internalIP(){return V.get(this._networkInfo,["wifi","ipAddress"],t)}get ssid(){return V.get(this._networkInfo,["wifi","ssid"],t)}}class me extends u{constructor(e){super(e),this.deviceId=new he,this.launchParams=new ge,this._deviceInfo=new ve,this._networkInfo=new ye}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=j,e.htmlPlayer=j):(VizbeeTV.logger.debug("LGWebOSNative::Factory::createPlayer() > WebOS 2014 detected - using html player"),e={nativePlayer:q,htmlPlayer:q,bitmovinPlayer:J,modularBitmovinPlayer:J,videoJSPlayer:$,theoPlayer:X,shakaPlayer:Q,topPlayer:Y}),this.player=new Z(this,e),this.player}createInputDevice(){let e=new x(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}}class be extends u{constructor(e){super(e),this._loadWebOSLibrary();let t=be.getPlatformType().toLowerCase();this.__platform="lgwebosnative"==t?new me(e):new ue(e)}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=[];if(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){var t=e.reduce((e,t,i)=>e.then(()=>k.loadScript(t)).catch(e=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - FAILED to load library",e)}),Promise.resolve());t.then(()=>{VizbeeTV.logger.debug("LGWebOSVirtualPlatform::_loadWebOSLibrary() - SUCCESS to load library")})}}}class Se extends W{constructor(e){super(e),VizbeeTV.logger.debug("Inside LGHtmlPlayer constructor")}videoCanPlayHandler(e){VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler::canplay : duration="+this.playerElement.duration+" startedPlaying="+this.startedPlaying+" finishedStartSeek="+this.finishedStartSeek),this.startedPlaying||(VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler::canplay - issuing play command"),this.bypassCanPlay||(VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler::canplay - in bypassCanPlay"),this.play(!0),this.startedPlaying=!0)),null==this.videoInfo.startTime&&(this.videoInfo.startTime=0);var t=this.videoInfo.startTime/1e3;if(VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler - start time = "+t),!this.finishedStartSeek&&0!=t)try{this.playerElement.duration>0&&(VizbeeTV.logger.debug("LGHtmlPlayer::videoCanPlayHandler - seeking to start time"),this.finishedStartSeek=!0,this.playerElement.currentTime=t)}catch(e){VizbeeTV.logger.error("LGHtmlPlayer::start::canplay - Error setting start time for video",e)}}}class _e extends pe{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 Ie extends re{constructor(){super()}}class Ee extends oe{constructor(){super()}}class Te extends M{get keyCodeMap(){return{203:M.keys.up,204:M.keys.down,205:M.keys.left,206:M.keys.right,195:M.keys.select,197:M.keys.play_pause,196:M.keys.back,202:M.keys.ffw,201:M.keys.rw,211:M.keys.alt_up,212:M.keys.alt_down,213:M.keys.alt_right,214:M.keys.alt_left}}sendPlay(){this.sendKeyEvent(M.keys.play_pause)}sendPause(){this.sendKeyEvent(M.keys.play_pause)}sendStop(){this.sendKeyEvent(M.keys.back)}}class Ve extends pe{constructor(){super()}uniqueDeviceID(e,t){let i="UNKNOWN_DEVICE_ID";try{let t=window.vizbeeXboxHost;t&&t.deviceId?i=t.deviceId:VizbeeTV.logger.w("XboxWebView2DeviceID","uniqueDeviceID","vizbeeXboxHost.deviceId missing, using fallback"),e(i)}catch(t){VizbeeTV.logger.e("XboxWebView2DeviceID","uniqueDeviceID","error reading host bridge",t),e(i)}}}class Pe extends ie{constructor(){super(),this._params=void 0,this.asyncFunction=void 0;let e="undefined"!=typeof window&&window.vizbeeXboxHost||{};this._parseAndSet(e.launchParams),this._listenForLaunchParamsChanges()}_listenForLaunchParamsChanges(){"undefined"!=typeof window&&window.chrome&&window.chrome.webview&&"function"==typeof window.chrome.webview.addEventListener&&window.chrome.webview.addEventListener("message",e=>{let t=e&&e.data;t&&"vizbeeXboxHost"===t.source&&"launchParamsChanged"===t.event&&(VizbeeTV.logger.i("XboxWebView2LaunchParams","_listenForLaunchParamsChanges","received launchParamsChanged",t.launchParams),this.setLaunchParams(t.launchParams))})}isLaunchedbyVizbee(){let e=this.getLaunchParams();return e?(VizbeeTV.logger.d("XboxWebView2LaunchParams","isLaunchedbyVizbee","params present",e),!0):(VizbeeTV.logger.d("XboxWebView2LaunchParams","isLaunchedbyVizbee","params not present"),!1)}getLaunchParams(){return this._params}getLaunchParamsAsync(e){if("function"!=typeof e)throw new TypeError("XboxWebView2LaunchParams::getLaunchParamsAsync : Argument supplied is not of type function");this.asyncFunction=e,this._params&&this.asyncFunction(this._params)}setLaunchParams(e){VizbeeTV.logger.i("XboxWebView2LaunchParams","setLaunchParams","rawParamData = ",e),this._params=void 0,this._parseAndSet(e),this.asyncFunction&&this._params&&this.asyncFunction(this._params)}_parseAndSet(e){if(!e||"string"!=typeof e)return;let t=e,i=e.indexOf("?");if(i>=0&&(t=e.substring(i+1)),!t)return;let n=t.split("&").reduce((e,t)=>{let[i,n]=t.split("=");return i&&(e[i]=null!=n?decodeURIComponent(n):""),e},{});Object.keys(n).length>0&&(this._params=n)}}class Ae{constructor(){if("BaseAdID"===this.constructor.name)throw new TypeError("BaseAdID::constructor() - Abstract class.")}adId(){return"UNKNOWN"}isAdTrackingDisabled(){return!0}}class Ce extends Ae{constructor(){super()}adId(){return("undefined"!=typeof window&&window.vizbeeXboxHost||{}).advertisingId||""}isAdTrackingDisabled(){let e="undefined"!=typeof window&&window.vizbeeXboxHost||{};return"boolean"==typeof e.isAdTrackingDisabled?e.isAdTrackingDisabled:this.adId().length<=0}}class we extends re{constructor(){super(),this._host="undefined"!=typeof window&&window.vizbeeXboxHost||{}}get deviceId(){return this._host.internalDeviceId||t}get make(){return this._host.make||t}get model(){return this._host.model||t}get friendlyName(){return this._host.friendlyName||t}}class De extends oe{constructor(){super()}get internalIP(){return("undefined"!=typeof window&&window.vizbeeXboxHost||{}).internalIP||t}}class ke extends le{constructor(){super(),this._eventVsHandlerMap={activated:"onStart",suspending:n,resuming:i}}init(){"undefined"!=typeof window&&window.chrome&&window.chrome.webview&&"function"==typeof window.chrome.webview.addEventListener?this._listen():VizbeeTV.logger.w("XboxWebView2AppLifeCycleManager","init","window.chrome.webview not available, lifecycle events will not fire")}_listen(){window.chrome.webview.addEventListener("message",e=>{let t=e&&e.data;if(!t||"vizbeeXboxHost"!==t.source||!t.event)return;let i=t.event,n=this._eventVsHandlerMap[i];VizbeeTV.logger.d("XboxWebView2AppLifeCycleManager","_listen","got event = "+i),n&&this.eventMap[n]&&this.eventMap[n].length&&this.eventMap[n].forEach(e=>{e.apply({},[t])})})}}class Ne extends u{constructor(e){super(e),this.deviceId=new Ve,this.launchParams=new Pe,this.xboxAdId=new Ce,this._xboxInfo=new we,this._xboxNetworkInfo=new De,this.xboxAppLifeCycleManager=new ke,this.xboxAppLifeCycleManager.init()}createPlayer(){let e={nativePlayer:null,htmlPlayer:null,bitmovinPlayer:J,modularBitmovinPlayer:J,videoJSPlayer:$,theoPlayer:X,shakaPlayer:Q,topPlayer:Y};return this.player=new Z(this,e),VizbeeTV.logger.d("XboxWebView2","createPlayer","created html player instance"),this.player}createInputDevice(){return this.inputDevice=new Te(this),this.inputDevice}exit(){super.exit(),setTimeout(()=>{VizbeeTV.logger.i("XboxWebView2","exit","exiting the app");try{if(window.chrome&&window.chrome.webview&&"function"==typeof window.chrome.webview.postMessage)return void window.chrome.webview.postMessage("EXIT_APP")}catch(e){VizbeeTV.logger.e("XboxWebView2","exit","error posting EXIT_APP",e)}window.close()},1e3)}get defaultAppletAppId(){return"vzb0000000"}get cloudPlatformName(){return"xbox_one"}get adId(){return this.xboxAdId.adId()}get isAdTrackingDisabled(){return this.xboxAdId.isAdTrackingDisabled()}get appLifeCycleManager(){return this.xboxAppLifeCycleManager}get deviceInfo(){return this._xboxInfo}get networkInfo(){return this._xboxNetworkInfo}}class Me extends u{constructor(e){super(e);let t=Me.getPlatformType().toLowerCase();this.__platform="xboxwebview2"==t?new Ne(e):new null(e),VizbeeTV.logger.i("XboxVirtualPlatform","constructor","selected variant = "+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("XboxVirtualPlatform","screenSaverEnabled","enabled = "+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("XboxVirtualPlatform","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&&this.__platform.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()}set enableHLSExchange(e){this.__platform.enableHLSExchange=e}static getPlatformType(){return"undefined"!=typeof window&&window.vizbeeXboxHost&&window.chrome&&window.chrome.webview?"XboxWebView2":"Xbox"}}let xe,Oe,Le={chromecast:null,desktop:null,lgnetcast:class extends u{constructor(e){super(e),this.deviceId=new _e,this.deviceId.deviceAPIID=e.deviceAPIID,this.launchParams=new ne,this._deviceInfo=new Ie,this._networkInfo=new Ee}createPlayer(){VizbeeTV.logger.debug("LGNetCast::Factory::createPlayer() - creating LG HTML Player");let e={nativePlayer:Se,htmlPlayer:Se,bitmovinPlayer:J,modularBitmovinPlayer:J,videoJSPlayer:$,theoPlayer:X,shakaPlayer:Q,topPlayer:Y};return this.player=new Z(this,e),this.player}createInputDevice(){let e=new x(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}},lgwebos:be,samsung:null,tizen:null,operabdp:null,opera:null,vizio:null,viziosmartcast:null,panasonic:null,sony:null,sonybdp:null,xbox:Me};class ze extends u{constructor(e,t){if(super(t),e=e.toLowerCase(),!Le[e])throw new TypeError("VirtualPlatform::constructor() - platform "+e+" doesnot exist.");this.__platform=new Le[e](t),this.player,this.inputDevice}reset(){xe&&(xe.stop(),VizbeeTV.logger.debug("player reset",xe)),Oe&&(Oe.reset(),Oe=void 0)}uniqueDeviceID(e,t){this.__platform.uniqueDeviceID(e,t)}set enableHLSExchange(e){xe.enableHLSExchange=e}set deviceIDAlgorithm(e){return this.__platform.deviceIDAlgorithm=e}get deviceIDAlgorithm(){return this.__platform.deviceIDAlgorithm}get player(){return void 0===xe&&(xe=this.__platform.createPlayer()),xe}set player(e){e&&(xe=e)}destroyPlayer(){xe.destroy().then(()=>{xe=void 0})}get inputDevice(){return void 0===Oe&&(Oe=this.__platform.createInputDevice()),Oe}set screenSaverEnabled(e){e=e||!1,void 0!==this.__platform&&this.__platform.enableScreenSaver&&(VizbeeTV.logger.debug("VirtualPlatform::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}static getPlatformType(){return window.cast?"Chromecast":"undefined"!=typeof Windows&&Windows.System&&Windows.System.Profile&&Windows.System.Profile.AnalyticsInfo&&Windows.System.Profile.AnalyticsInfo.versionInfo&&Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily&&-1!=Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily.toLowerCase().indexOf("xbox")||"undefined"!=typeof window&&window.vizbeeXboxHost&&window.chrome&&window.chrome.webview?"Xbox":window.webapis?"Tizen":window.VIZIO?"VizioSmartCast":window.navigator.userAgent.toLowerCase().indexOf("webos.tv")>-1||window.PalmServiceBridge?"LGWebOS":void 0}static detectPlatformWhenReady(e){let t=ze.getPlatformType();t?e(t):(window.navigator&&window.navigator.userAgent||"").toLowerCase().indexOf("vizio smartcast")>-1?ze._awaitVizioSmartCast(e):e(void 0)}static _awaitVizioSmartCast(e){let t,i=!1;const n=n=>{i||(i=!0,clearTimeout(t),document.removeEventListener("VIZIO_LIBRARY_DID_LOAD",r),n||VizbeeTV.logger.error("VirtualPlatform::_awaitVizioSmartCast - Vizio companion library is mandatory for Vizbee initialization; not available within 5s"),e(n))},r=()=>n(ze.getPlatformType());VizbeeTV.logger.info("VirtualPlatform::_awaitVizioSmartCast - waiting up to 5s for VIZIO_LIBRARY_DID_LOAD"),document.addEventListener("VIZIO_LIBRARY_DID_LOAD",r),t=setTimeout(()=>n(void 0),5e3)}}class Re extends ze{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 Ke{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=k.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=k.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=k.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=k.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=k.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=k.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=k.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?k.padEnd(e+"::",40," ")+k.padEnd(t,30," ")+" - ":""}getCurrentTimeString(){return"["+(new Date).toISOString()+"]"}}class He extends Ke{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&&(V.isObject(t)||V.isString(t))&&i.captureException(t)}}catch(e){}}_shouldLogException(){return!0}}var Ue,Fe,Be,Ge;function We(){if(Fe)return Ue;Fe=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 a="";if(i)switch(i.constructor){case Number:a=i===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+i;break;case String:a="; expires="+i;break;case Date:a="; expires="+i.toUTCString()}return document.cookie=encodeURIComponent(e)+"="+encodeURIComponent(t)+a+(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 Ue={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(a){if(4===s.readyState)if(-1===[200,304].indexOf(s.status))VizbeeSDK.logger.error("xhr error",a),n>0?(n--,r()):i(new Error("Server responded with a status of "+s.status));else try{e.format=e.format||"json";var o=a.target;"json"===e.format?o=JSON.parse(o.response):"xml"===e.format&&(o=o.responseXML),VizbeeSDK.logger.debug("Util::xhr() -- response object --",o),t(o)}catch(a){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},Ue}window.VizbeeTV={init:function(e,t,i){this.logger=new He,this.logger.setPrefix("[VTVLIB]"),this.Util=k,i?this.tv instanceof Re?this.tv.config=V.extend(this.tv.config,t):this.tv=new Re(e,t):this.tv instanceof ze?this.tv.config=V.extend(this.tv.config,t):this.tv=new ze(e,t)}};var je,qe,Ye,Je,$e={getIpv6Address:function(e){k.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 Xe(){if(qe)return je;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 qe=1,je=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,a,o,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:o=Array.prototype.slice.call(arguments,1),s.apply(this,o)}else if(i(s))for(o=Array.prototype.slice.call(arguments,1),a=(l=s.slice()).length,d=0;d<a;d++)l[d].apply(this,o);return!0},e.prototype.addListener=function(r,s){var a;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&&(a=n(this._maxListeners)?e.defaultMaxListeners:this._maxListeners)&&a>0&&this._events[r].length>a&&(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,a,o;if(!t(n))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(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(o=a;o-- >0;)if(r[o]===n||r[o].listener&&r[o].listener===n){s=o;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)},je}function Qe(){if(Je)return Ye;Je=1;var e,t=new(0,Xe().EventEmitter);return Ye={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)}},Ye}var Ze,et,tt=T(),it=new(0,Xe().EventEmitter),nt=Qe(),rt=void 0,st={isInProgress:!1},at=!1,ot="videoadapter_video",dt="videoadapter_ad";function lt(e){var t,i,n=!tt.contains(["timeupdate"],e.type);st.isInProgress||(rt&&"app"!==rt.app.state?(t=new ut,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),it.emit(ot,t,n)):VizbeeSDK.logger.verbose('VideoAdapter::videoEventHandler - app.state = "app"'))}function ct(e,t){var i=e.playing||e.preparing;(i||!i&&st.isInProgress)&&it.emit(dt,e,t),st.isInProgress=i||!1,st.isInProgress||(at=!1),"FINISHED"==e.state||e.state}function ut(e){var t={type:"video",position:-1,duration:-1,cc:{},tr:{}};return et?(t.position=1e3*et.currentTime(),t.duration=1e3*et.getDuration(),t.startTime=et.getStartTime(),t.videoBufferLevel=et.getBufferLevel(),t.audioBufferLevel=et.getAudioBufferLevel(),t.qos=et.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}),tt.extend(t,e)}function pt(){st.isInProgress&&Ze.reset()}var ht,gt,ft,vt,yt,mt,bt,St,_t,It,Et,Tt,Vt,Pt,At={setVideo:function(e){var t;(t=e).onLoading=function(e){st.isInProgress||(lt({type:"loading"}),at=!1)},t.onPlaying=function(e){st.isInProgress||(lt({type:"playing"}),at=!0)},t.onPaused=function(e){st.isInProgress||(lt({type:"paused"}),at=!1)},t.onBuffering=function(e){st.isInProgress||(lt({type:"loading"}),at=!1)},t.onError=function(e){st.isInProgress||(lt({type:"error",data:e}),at=!1)},t.onInterrupted=function(e){st.isInProgress||(lt({type:"interrupted",data:e}),at=!1)},t.onEnded=function(){st.isInProgress||(lt({type:"ended"}),at=!1)},t.onTimeUpdate=function(e){st.isInProgress||(at?lt({type:"timeupdate"}):(at=!0,lt({type:"playing"})))},et=e},setVideoInfo:function(e){e&&rt&&rt.setCurrentVideoInfo(e)},setId:function(e,t){if(rt){if(rt.video&&rt.video.id&&e&&rt.video.id!=e){VizbeeSDK.logger.debug("VideoAdapter::setId - SENDING INTERRUPTED");var i=new ut({id:rt.video.id,state:"INTERRUPTED"});it.emit(ot,i,!0)}var n=new ut({id:e});n.position=n.duration=-1,n.state="UNKNOWN",it.emit(ot,n,!0),VizbeeSDK.logger.debug("VideoAdapter::setId - setting currentGUID = "+e),rt.setCurrentVideoInfo(tt.extend(rt.getCurrentVideoInfo()||{},{id:e,islive:t}))}},setVideoStop:function(){st&&st.isInProgress&&Ze&&(st.isInProgress=!1,Ze.reset()),lt({type:"error"})},willStart:function(e,t){nt.willStartVideo(e,t)},start:function(e){lt({type:"loadedmetadata"}),pt(),nt.startVideo(e)},play:function(){nt.playVideo()||VizbeeTV.tv.inputDevice.sendPlay()},pause:function(){nt.pauseVideo()||VizbeeTV.tv.inputDevice.sendPause()},seek:function(e){nt.seekVideo(e)||tt.isNumber(e)&&et.seek(e)},stop:function(e){if(!nt.stopVideo(e)){VizbeeTV.tv.inputDevice.sendStop(),VizbeeSDK.logger.debug("VideoAdapter::stop - sending INTERRUPTED state");var t=new ut({state:"INTERRUPTED"});it.emit(ot,t,!0),pt()}},exit:function(){var e=new ut({state:"INTERRUPTED"});it.emit(ot,e,!0)},setTracks:function(e){et.setTracks(e)},getTracks:function(e){e=e||r;var t=nt.getTracks();return!1!==t?t:et.getTracks(e)},getEnabledTracks:function(e){e=e||r;var t=nt.getEnabledTracks();return!1!==t?t:et.getEnabledTracks(e)},enableTracks:function(e){nt.enableTracks(e)||et.enableTracks(e)},disableTracks:function(e){nt.disableTracks(e)||et.disableTracks(e)},getAudioTracks:function(e){e=e||s;var t=nt.getAudioTracks();return!1!==t?t:et.getTracks(e)},getActiveAudioTrack:function(e){e=e||s;var t=nt.getActiveAudioTrack();return!1!==t?t:(et.getEnabledTracks(e)||[])[0]},changeAudioTrack:function(e){nt.changeAudioTrack(e)||et.changeAudioTrack(e)},mute:function(e){},volumeUp:function(){it.emit(ot,new ut,!0)},volumeDown:function(){it.emit(ot,new ut,!0)},onEvent:function(e){nt.onEvent(e)},setAdAdapter:function(e){Ze&&Ze.removeListener(ct),(Ze=e)&&Ze.addListener(ct)},setAppStateManager:function(e){rt=e},reset:function(){et=void 0,st={playing:!1}},addListener:function(e){it.addListener(ot,e),it.addListener(dt,e)},removeListener:function(e){it.removeListener(ot,e),it.removeListener(dt,e)}};function Ct(){if(gt)return ht;gt=1;var e,t=T();return ht={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 wt(){if(vt)return ft;vt=1;var e=new(0,Xe().EventEmitter),t=At,i=Ct(),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 ft={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 Dt(){if(mt)return yt;mt=1;var e=T(),t=new(0,Xe().EventEmitter),i=wt(),n=Qe(),r={state:"app"},s={},a={},o="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(a,t)):(a.preparing=!1,a.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,a,d),s.id="",s.state="UNKNOWN",s.position=-1,s.duration=-1,s.elapsedTime=0,s.tr={},s.error={},a.id="",a.state="UNKNOWN",a.position=-1,a.duration=-1,o={},VizbeeSDK.logger.debug("AppStateManager:reset() complete : current video and ad objects = ",s,a,d)}return g(),i.addListener(u),n.addListener(u),n.isAppSet()&&p(),yt={type:"AppStateManager",app:r,video:s,ad:a,reset:g,syncStartVideoSource:o,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 kt(){return It?_t:(It=1,_t={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 Nt(){if(Tt)return Et;Tt=1;var e=new(0,Xe().EventEmitter),t="sync_proxy_video_cmds";return Et={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 xt{constructor(e,t){this.type=e,this.data=t}}class Ot{static get SYNC_CONNECT(){return"sync-connect"}static get SYNC_MESSAGE(){return"sync-message"}static get SYNC_PRESENCE(){return"sync-presence"}}var Lt,zt,Rt,Kt,Ht=E(function(){if(Pt)return Vt;Pt=1;var e=We().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),a=e.getItem(t);return Vt={getDeviceId:function(){return a},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||(a!==r&&this.isIntermediateVerifcationCookieSet()&&e.eraseCookieFromAllPaths(n),a=r,e.setItem(t,a,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 o=[t,r,i,n],d=0;d<o.length;d++)e.eraseCookieFromAllPaths(o[d]);s=null,a=null}}}()),Ut={exports:{}},Ft={exports:{}};function Bt(){return Lt||(Lt=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}},Ft.exports=t),Ft.exports;var e,t}function Gt(){if(Rt)return zt;Rt=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 zt=e}var Wt,jt,qt,Yt=(Kt||(Kt=1,function(){var e=Bt(),t=Gt().utf8,i=Gt().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 a=e.bytesToWords(r),o=8*r.length,d=1732584193,l=-271733879,c=-1732584194,u=271733878,p=0;p<a.length;p++)a[p]=16711935&(a[p]<<8|a[p]>>>24)|4278255360&(a[p]<<24|a[p]>>>8);a[o>>>5]|=128<<o%32,a[14+(o+64>>>9<<4)]=o;var h=n._ff,g=n._gg,f=n._hh,v=n._ii;for(p=0;p<a.length;p+=16){var y=d,m=l,b=c,S=u;d=h(d,l,c,u,a[p+0],7,-680876936),u=h(u,d,l,c,a[p+1],12,-389564586),c=h(c,u,d,l,a[p+2],17,606105819),l=h(l,c,u,d,a[p+3],22,-1044525330),d=h(d,l,c,u,a[p+4],7,-176418897),u=h(u,d,l,c,a[p+5],12,1200080426),c=h(c,u,d,l,a[p+6],17,-1473231341),l=h(l,c,u,d,a[p+7],22,-45705983),d=h(d,l,c,u,a[p+8],7,1770035416),u=h(u,d,l,c,a[p+9],12,-1958414417),c=h(c,u,d,l,a[p+10],17,-42063),l=h(l,c,u,d,a[p+11],22,-1990404162),d=h(d,l,c,u,a[p+12],7,1804603682),u=h(u,d,l,c,a[p+13],12,-40341101),c=h(c,u,d,l,a[p+14],17,-1502002290),d=g(d,l=h(l,c,u,d,a[p+15],22,1236535329),c,u,a[p+1],5,-165796510),u=g(u,d,l,c,a[p+6],9,-1069501632),c=g(c,u,d,l,a[p+11],14,643717713),l=g(l,c,u,d,a[p+0],20,-373897302),d=g(d,l,c,u,a[p+5],5,-701558691),u=g(u,d,l,c,a[p+10],9,38016083),c=g(c,u,d,l,a[p+15],14,-660478335),l=g(l,c,u,d,a[p+4],20,-405537848),d=g(d,l,c,u,a[p+9],5,568446438),u=g(u,d,l,c,a[p+14],9,-1019803690),c=g(c,u,d,l,a[p+3],14,-187363961),l=g(l,c,u,d,a[p+8],20,1163531501),d=g(d,l,c,u,a[p+13],5,-1444681467),u=g(u,d,l,c,a[p+2],9,-51403784),c=g(c,u,d,l,a[p+7],14,1735328473),d=f(d,l=g(l,c,u,d,a[p+12],20,-1926607734),c,u,a[p+5],4,-378558),u=f(u,d,l,c,a[p+8],11,-2022574463),c=f(c,u,d,l,a[p+11],16,1839030562),l=f(l,c,u,d,a[p+14],23,-35309556),d=f(d,l,c,u,a[p+1],4,-1530992060),u=f(u,d,l,c,a[p+4],11,1272893353),c=f(c,u,d,l,a[p+7],16,-155497632),l=f(l,c,u,d,a[p+10],23,-1094730640),d=f(d,l,c,u,a[p+13],4,681279174),u=f(u,d,l,c,a[p+0],11,-358537222),c=f(c,u,d,l,a[p+3],16,-722521979),l=f(l,c,u,d,a[p+6],23,76029189),d=f(d,l,c,u,a[p+9],4,-640364487),u=f(u,d,l,c,a[p+12],11,-421815835),c=f(c,u,d,l,a[p+15],16,530742520),d=v(d,l=f(l,c,u,d,a[p+2],23,-995338651),c,u,a[p+0],6,-198630844),u=v(u,d,l,c,a[p+7],10,1126891415),c=v(c,u,d,l,a[p+14],15,-1416354905),l=v(l,c,u,d,a[p+5],21,-57434055),d=v(d,l,c,u,a[p+12],6,1700485571),u=v(u,d,l,c,a[p+3],10,-1894986606),c=v(c,u,d,l,a[p+10],15,-1051523),l=v(l,c,u,d,a[p+1],21,-2054922799),d=v(d,l,c,u,a[p+8],6,1873313359),u=v(u,d,l,c,a[p+15],10,-30611744),c=v(c,u,d,l,a[p+6],15,-1560198380),l=v(l,c,u,d,a[p+13],21,1309151649),d=v(d,l,c,u,a[p+4],6,-145523070),u=v(u,d,l,c,a[p+11],10,-1120210379),c=v(c,u,d,l,a[p+2],15,718787259),l=v(l,c,u,d,a[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,a){var o=e+(t&i|~t&n)+(r>>>0)+a;return(o<<s|o>>>32-s)+t},n._gg=function(e,t,i,n,r,s,a){var o=e+(t&n|i&~n)+(r>>>0)+a;return(o<<s|o>>>32-s)+t},n._hh=function(e,t,i,n,r,s,a){var o=e+(t^i^n)+(r>>>0)+a;return(o<<s|o>>>32-s)+t},n._ii=function(e,t,i,n,r,s,a){var o=e+(i^(t|~n))+(r>>>0)+a;return(o<<s|o>>>32-s)+t},n._blocksize=16,n._digestsize=16,Ut.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)}}}()),Ut.exports),Jt=E(Yt),$t={exports:{}},Xt={exports:{}},Qt={exports:{}},Zt={exports:{}},ei={exports:{}};function ti(){return jt||(jt=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i,n=function(){return Wt||(Wt=1,e=ei,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=ei.exports),null!==e&&(e.exports=t.uuid)),ei.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}(Zt,Zt.exports)),Zt.exports}function ii(){return qt||(qt=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=ti())&&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}(Qt,Qt.exports)),Qt.exports}var ni,ri={exports:{}};function si(){return ni||(ni=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(ii());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),a=this._getPaddedKey(t||this._config.cipherKey,i);return n.default.AES.encrypt(e,a,{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),a=this._getPaddedKey(t||this._config.cipherKey,i);try{var o=n.default.enc.Base64.parse(e),d=n.default.AES.decrypt({ciphertext:o},a,{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}(ri,ri.exports)),ri.exports}var ai,oi,di={exports:{}},li={exports:{}},ci={exports:{}};function ui(){return ai||(ai=1,e=ci,t=ci.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),ci.exports;var e,t}function pi(){return 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}}(),r=(i=ui())&&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}(li,li.exports)),li.exports}var hi,gi,fi,vi={exports:{}},yi={},mi={exports:{}};function bi(){return hi||(hi=1,e=mi,t=mi.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),mi.exports;var e,t}function Si(){if(gi)return yi;gi=1,Object.defineProperty(yi,"__esModule",{value:!0}),yi.getOperation=function(){return t.default.PNTimeOperation},yi.getURL=function(){return"/time/0"},yi.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},yi.prepareParams=function(){return{}},yi.isAuthSupported=function(){return!1},yi.handleResponse=function(e,t){return{timetoken:t[0]}},yi.validateParams=function(){};var e,t=(e=bi())&&e.__esModule?e:{default:e};return yi}var _i,Ii,Ei,Ti,Vi={exports:{}};function Pi(){if(Ei)return Ii;function e(e){return encodeURIComponent(e).replace(/[!~*'()]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}return Ei=1,Ii={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 Ai(){return Ti||(Ti=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}}();o(si()),o(ii()),o(pi());var n=o((fi||(fi=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}(vi,vi.exports)),vi.exports)),r=o((_i||(_i=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=ii())||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}(Vi,Vi.exports)),Vi.exports)),s=o(Pi()),a=o(ui());function o(e){return e&&e.__esModule?e:{default:e}}var d=function(){function e(t){var i=t.subscribeEndpoint,s=t.leaveEndpoint,a=t.heartbeatEndpoint,o=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=a,this._setStateEndpoint=o,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,a=e.channelGroups,o=void 0===a?[]:a;return s.forEach(function(e){e in i._channels&&(i._channels[e].state=n)}),o.forEach(function(e){e in i._channelGroups&&(i._channelGroups[e].state=n)}),this._setStateEndpoint({state:n,channels:s,channelGroups:o},t)}},{key:"adaptPresenceChange",value:function(e){var t=this,i=e.connected,n=e.channels,r=void 0===n?[]:n,s=e.channelGroups,a=void 0===s?[]:s;i?(r.forEach(function(e){t._heartbeatChannels[e]={state:{}}}),a.forEach(function(e){t._heartbeatChannelGroups[e]={state:{}}})):(r.forEach(function(e){e in t._heartbeatChannels&&delete t._heartbeatChannels[e]}),a.forEach(function(e){e in t._heartbeatChannelGroups&&delete t._heartbeatChannelGroups[e]}),!1===this._config.suppressLeaveEvents&&this._leaveEndpoint({channels:r,channelGroups:a},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,a=void 0===s?[]:s,o=e.withPresence,d=void 0!==o&&o;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)}),a.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,a=void 0===s?[]:s,o=[],d=[];r.forEach(function(e){e in i._channels&&(delete i._channels[e],o.push(e)),e in i._presenceChannels&&(delete i._presenceChannels[e],o.push(e))}),a.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===o.length&&0===d.length||(!1!==this._config.suppressLeaveEvents||t||this._leaveEndpoint({channels:o,channelGroups:d},function(e){e.affectedChannels=o,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===a.default.PNTimeoutCategory?this._startSubscribeLoop():e.category===a.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:a.default.PNReconnectedCategory,operation:e.operation,lastTimetoken:i._lastTimetoken,currentTimetoken:i._currentTimetoken};i._listenerManager.announceStatus(t)}),this._reconnectionManager.startPolling(),this._listenerManager.announceStatus(e)):e.category===a.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=a.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||[],o=this._config,d=o.requestMessageCountThreshold,l=o.dedupeOnSubscribe;if(d&&r.length>=d){var c={};c.category=a.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 a={channel:null,subscription:null};a.actualChannel=null!=n?t:null,a.subscribedChannel=null!=n?n:t,t&&(a.channel=t.substring(0,t.lastIndexOf("-pnpres"))),n&&(a.subscription=n.substring(0,n.lastIndexOf("-pnpres"))),a.action=e.payload.action,a.state=e.payload.data,a.timetoken=r.publishTimetoken,a.occupancy=e.payload.occupancy,a.uuid=e.payload.uuid,a.timestamp=e.payload.timestamp,e.payload.join&&(a.join=e.payload.join),e.payload.leave&&(a.leave=e.payload.leave),e.payload.timeout&&(a.timeout=e.payload.timeout),i._listenerManager.announcePresence(a)}else{var o={channel:null,subscription:null};o.actualChannel=null!=n?t:null,o.subscribedChannel=null!=n?n:t,o.channel=t,o.subscription=n,o.timetoken=r.publishTimetoken,o.publisher=e.issuingClientId,e.userMetadata&&(o.userMetadata=e.userMetadata),i._config.cipherKey?o.message=i._crypto.decrypt(e.payload):o.message=e.payload,i._listenerManager.announceMessage(o)}}),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}(di,di.exports)),di.exports}var Ci,wi={exports:{}};var Di,ki,Ni,Mi,xi,Oi={},Li={},zi={},Ri={};function Ki(){return xi||(xi=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(ii()),r=K(si()),s=K(Ai()),a=K(pi()),o=K((Ci||(Ci=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(o(p)):c?(c.reject(new a("Validation failed, check status for details",o(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 a=r.subscribeKey+"\n"+r.publishKey+"\n"+t+"\n";a+=n.default.signPamFromParams(i);var o=s.HMACSHA256(a);o=(o=o.replace(/\+/g,"-")).replace(/\//g,"_"),i.signature=o}(e,g,h);var y=function(i,n){if(i.error)l?l(i):c&&c.reject(new a("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(ti()),n=s(Pi());s(ii());var r=s(bi());function s(e){return e&&e.__esModule?e:{default:e}}var a=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 o(e){return(t={message:e}).type="validationError",t.error=!0,t;var t}e.exports=t.default}(wi,wi.exports)),wi.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(Di)return Oi;Di=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.getOperation=function(){return e.default.PNUnsubscribeOperation},Oi.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Oi.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,a=s.length>0?s.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+t.default.encodeString(a)+"/leave"},Oi.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Oi.isAuthSupported=function(){return!0},Oi.prepareParams=function(e,t){var i=t.channelGroups,n=void 0===i?[]:i,r={};return n.length>0&&(r["channel-group"]=n.join(",")),r},Oi.handleResponse=function(){return{}};var e=i(bi()),t=i(Pi());function i(e){return e&&e.__esModule?e:{default:e}}return Oi}(),m=R(y),b=R(null),S=function(){if(ki)return Li;ki=1,Object.defineProperty(Li,"__esModule",{value:!0}),Li.getOperation=function(){return e.default.PNHeartbeatOperation},Li.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Li.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,a=s.length>0?s.join(","):",";return"/v2/presence/sub-key/"+n.subscribeKey+"/channel/"+t.default.encodeString(a)+"/heartbeat"},Li.isAuthSupported=function(){return!0},Li.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},Li.prepareParams=function(e,t){var i=t.channelGroups,n=void 0===i?[]:i,r=t.state,s=void 0===r?{}:r,a=e.config,o={};return n.length>0&&(o["channel-group"]=n.join(",")),o.state=JSON.stringify(s),o.heartbeat=a.getPresenceTimeout(),o},Li.handleResponse=function(){return{}};var e=i(bi()),t=i(Pi());function i(e){return e&&e.__esModule?e:{default:e}}return Li}(),_=R(S),I=R(null),E=R(null),T=R(null),V=R(null),P=R(null),A=function(){if(Ni)return zi;Ni=1,Object.defineProperty(zi,"__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};zi.getOperation=function(){return t.default.PNPublishOperation},zi.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"},zi.usePost=function(e,t){var i=t.sendByPost;return void 0!==i&&i},zi.getURL=function(e,t){var n=e.config,s=t.channel,a=r(e,t.message);return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+i.default.encodeString(s)+"/0/"+i.default.encodeString(a)},zi.postURL=function(e,t){var n=e.config,r=t.channel;return"/publish/"+n.publishKey+"/"+n.subscribeKey+"/0/"+i.default.encodeString(r)+"/0"},zi.getRequestTimeout=function(e){return e.config.getTransactionTimeout()},zi.isAuthSupported=function(){return!0},zi.postPayload=function(e,t){return r(e,t.message)},zi.prepareParams=function(t,i){var n=i.meta,r=i.replicate,s=void 0===r||r,a=i.storeInHistory,o=i.ttl,d={};return null!=a&&(d.store=a?"1":"0"),o&&(d.ttl=o),!1===s&&(d.norep="true"),n&&"object"===(void 0===n?"undefined":e(n))&&(d.meta=JSON.stringify(n)),d},zi.handleResponse=function(e,t){return{timetoken:t[2]}};var t=n(bi()),i=n(Pi());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 zi}(),C=R(A),w=R(null),D=R(null),k=R(null),N=R(Si()),M=function(){if(Mi)return Ri;Mi=1,Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.getOperation=function(){return e.default.PNSubscribeOperation},Ri.validateParams=function(e){if(!e.config.subscribeKey)return"Missing Subscribe Key"},Ri.getURL=function(e,i){var n=e.config,r=i.channels,s=void 0===r?[]:r,a=s.length>0?s.join(","):",";return"/v2/subscribe/"+n.subscribeKey+"/"+t.default.encodeString(a)+"/0"},Ri.getRequestTimeout=function(e){return e.config.getSubscribeTimeout()},Ri.isAuthSupported=function(){return!0},Ri.prepareParams=function(e,t){var i=e.config,n=t.channelGroups,r=void 0===n?[]:n,s=t.timetoken,a=t.filterExpression,o=t.region,d={heartbeat:i.getPresenceTimeout()};return r.length>0&&(d["channel-group"]=r.join(",")),a&&a.length>0&&(d["filter-expr"]=a),s&&(d.tt=s),o&&(d.tr=o),d},Ri.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(bi()),t=i(Pi());function i(e){return e&&e.__esModule?e:{default:e}}return Ri}(),x=R(M),O=K(bi()),L=K(ui()),z=K(ti());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 H=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 O={config:A,networking:S,crypto:M},L=o.default.bind(this,O,N),z=o.default.bind(this,O,m),R=o.default.bind(this,O,_),K=o.default.bind(this,O,E),H=o.default.bind(this,O,x),U=this._listenerManager=new a.default,F=new s.default({timeEndpoint:L,leaveEndpoint:z,heartbeatEndpoint:R,setStateEndpoint:K,subscribeEndpoint:H,crypto:O.crypto,config:O.config,listenerManager:U});this.addListener=U.addListener.bind(U),this.removeListener=U.removeListener.bind(U),this.removeAllListeners=U.removeAllListeners.bind(U),this.channelGroups={listGroups:o.default.bind(this,O,u),listChannels:o.default.bind(this,O,p),addChannels:o.default.bind(this,O,d),removeChannels:o.default.bind(this,O,l),deleteGroup:o.default.bind(this,O,c)},this.push={addChannels:o.default.bind(this,O,h),removeChannels:o.default.bind(this,O,g),deleteDevice:o.default.bind(this,O,v),listChannels:o.default.bind(this,O,f)},this.hereNow=o.default.bind(this,O,T),this.whereNow=o.default.bind(this,O,b),this.getState=o.default.bind(this,O,I),this.setState=F.adaptStateChange.bind(F),this.grant=o.default.bind(this,O,P),this.audit=o.default.bind(this,O,V),this.publish=o.default.bind(this,O,C),this.fire=function(e,t){return e.replicate=!1,e.storeInHistory=!1,i.publish(e,t)},this.history=o.default.bind(this,O,w),this.deleteMessages=o.default.bind(this,O,D),this.fetchMessages=o.default.bind(this,O,k),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=O.config.getAuthKey.bind(O.config),this.setAuthKey=O.config.setAuthKey.bind(O.config),this.setCipherKey=O.config.setCipherKey.bind(O.config),this.getUUID=O.config.getUUID.bind(O.config),this.setUUID=O.config.setUUID.bind(O.config),this.getFilterExpression=O.config.getFilterExpression.bind(O.config),this.setFilterExpression=O.config.setFilterExpression.bind(O.config),this.setHeartbeatInterval=O.config.setHeartbeatInterval.bind(O.config),S.hasModule("proxy")&&(this.setProxy=function(e){O.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}();H.OPERATIONS=O.default,H.CATEGORIES=L.default,t.default=H,e.exports=t.default}(Xt,Xt.exports)),Xt.exports}var Hi,Ui={exports:{}};var Fi,Bi,Gi,Wi={exports:{}},ji={},qi=(Gi||(Gi=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=o(Ki()),n=o((Hi||(Hi=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(ii());var n=r(ui());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}(Ui,Ui.exports)),Ui.exports)),r=function(){return Fi||(Fi=1,e=Wi,t=Wi.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),Wi.exports;var e,t}(),s=o(r),a=function(){if(Bi)return ji;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 a=this,o=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,o.status&&(i.statusCode=o.status),e?(i.errorData=e,i.category=a._detectErrorCategory(e),s(i,null)):s(i,t)}}o.open(e,d,!0),o.timeout=r.timeout,o.onreadystatechange=function(){if(4===o.readyState){var e=o.status;if(e>=200&&e<300){var t;try{t=JSON.parse(o.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)}},o.ontimeout=function(){u({timeout:!0},null)},o.onerror=function(){u({status:0},null)};var p=null;null!=n&&(p="string"==typeof n?n:JSON.stringify(n),o.setRequestHeader("Content-Type","application/json"));try{o.send(p)}catch(e){u({status:0},null)}return{abort:function(){l=!0;try{o.abort()}catch(e){}}}}return Bi=1,Object.defineProperty(ji,"__esModule",{value:!0}),ji.get=function(i,n,r){return t.call(this,"GET",this.getStandardOrigin()+n.url,e(i),null,n,r)},ji.post=function(i,n,r,s){return t.call(this,"POST",this.getStandardOrigin()+r.url,e(i),n,r,s)},ji.del=function(i,n,r){return t.call(this,"DELETE",this.getStandardOrigin()+n.url,e(i),null,n,r)},ji}();function o(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:a.del,get:a.get,post:a.post,sendBeacon:d});var o=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(){o.networkDownDetected()}),window.addEventListener("online",function(){o.networkUpDetected()})),o}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}($t,$t.exports)),$t.exports),Yi=E(qi);const Ji=["PNAccessDeniedCategory","PNTimeoutCategory","PNNetworkIssuesCategory","PNBadRequestCategory","PNMalformedResponseCategory","PNDecryptionErrorCategory","PNTLSConnectionFailedCategory","PNTLSUntrustedCertificateCategory","PNUnexpectedDisconnectCategory","PNNetworkDownCategory","PNNetworkUpCategory"];class $i extends Mt{constructor(e){super(e),this.pubnub=void 0,this.channelId=void 0,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 Yi({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 xt(Ot.SYNC_CONNECT,{})),e(!0)):Ji.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){this.pubnub&&this.channelId&&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")})}generateChannel(){this.appConfig&&(this.channelId=(""+Jt(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:{};Ht.verifyDeviceId(),this.dispatchReceive(new xt(Ot.SYNC_MESSAGE,n))}}const Xi="MSF_LIBRARY_NOT_LOADED",Qi="MSF_LOCAL_SERVICE_ERROR";class Zi extends Mt{constructor(e){super(e),this.isMSFLibraryLoaded=!1,window.addEventListener(c,()=>{window.msf&&(this.isMSFLibraryLoaded=!0)}),window.msf&&(this.isMSFLibraryLoaded=!0),this.msfLocalChannel=void 0,this.channelConnectionRetryCount=15,this.channelId=void 0,this._generateChannelId()}connect(){VizbeeSDK.logger.debug("SamsungMSFSync::connect - appId= "+this.appConfig.appId+", deviceId= "+this.appConfig.deviceId),void 0===this.msfLocalChannel?void 0!==this.channelId?(VizbeeSDK.logger.debug("SamsungMSFSync::connect - creating channel"),this._createChannel(()=>{this.channelConnectionRetryCount=15},e=>{if(VizbeeSDK.logger.warn("SamsungMSFSync::connect - failed to create channel with error= ",e),this.channelConnectionRetryCount>0){VizbeeSDK.logger.info("SamsungMSFSync::connect - retrying to connect, attempts left= ",this.channelConnectionRetryCount),this.channelConnectionRetryCount--;let t=0;t=e.message===Xi?1500:0,VizbeeSDK.logger.info("SamsungMSFSync::connect - retrying to connect after timeout= ",t),setTimeout(()=>{this.connect()},t)}else VizbeeSDK.logger.critical("SamsungMSFSync::connect - failed to connect after all 15 retries with error: ",e)})):VizbeeSDK.logger.error("SamsungMSFSync::connect - channelId is invalid"):VizbeeSDK.logger.debug("SamsungMSFSync::connect - msfLocalChannel is already connected")}disconnect(){if(this.msfLocalChannel){VizbeeSDK.logger.debug("SamsungMSFSync::disconnect - invoking disconnect"),this.msfLocalChannel.off("say",this._messageHandler.bind(this)),this.msfLocalChannel.off("connect",this._connectHandler.bind(this)),this.msfLocalChannel.off("disconnect",this._disconnectHandler.bind(this));try{this.msfLocalChannel.isConnected?this.msfLocalChannel.disconnect((e,t)=>{e?VizbeeSDK.logger.warn("SamsungMSFSync::disconnect - failed to disconnect with error - ",e.code,e.message):VizbeeSDK.logger.info("SamsungMSFSync::disconnect - disconnected client - ",t)}):VizbeeSDK.logger.info("SamsungMSFSync::disconnect - already disconnected")}catch(e){VizbeeSDK.logger.warn("SamsungMSFSync::disconnect - failed to disconnect with exception - ",e)}this.msfLocalChannel=void 0,super.disconnect()}}send(e){this.msfLocalChannel&&this.msfLocalChannel.publish("say",e)}_generateChannelId(){this.appConfig&&(this.channelId=(""+Jt(this.appConfig.appId+":"+this.appConfig.deviceId)).toLowerCase()),VizbeeSDK.logger.info("SamsungMSFSync::_generateChannelId",this.channelId)}_createChannel(e,t){if(!this.isMSFLibraryLoaded)return VizbeeSDK.logger.warn("SamsungMSFSync::_createChannel - msf library is not loaded"),void t({message:Xi});window.msf.local((i,n)=>i?(VizbeeSDK.logger.error("SamsungMSFSync::_createChannel - msf.local service error= ",i),void t({message:Qi,cause:i})):n?(this.msfLocalChannel=n.channel(this.channelId),this.msfLocalChannel.on("connect",this._connectHandler.bind(this)),this.msfLocalChannel.on("disconnect",this._disconnectHandler.bind(this)),this.msfLocalChannel.on("say",this._messageHandler.bind(this)),this.msfLocalChannel.on("clientConnect",e=>{VizbeeSDK.logger.debug("SamsungMSFSync::clientConnect - client= ",e)}),this.msfLocalChannel.on("clientDisconnect",e=>{VizbeeSDK.logger.debug("SamsungMSFSync::clientDisconnect - client= ",e)}),void this.msfLocalChannel.connect({name:"Samsung TV"},(i,n)=>{i?(VizbeeSDK.logger.error("SamsungMSFSync::_createChannel - msfLocalChannel.connect error= ",i),t({message:"MSF_CHANNEL_CONNECTION_ERROR",cause:i})):(VizbeeSDK.logger.debug("SamsungMSFSync::_createChannel - msfLocalChannel.connect success"),e())})):(VizbeeSDK.logger.error("SamsungMSFSync::_createChannel - msf.local returned invalid service"),void t({message:Qi,cause:"msf.local returned invalid service"})))}_connectHandler(e){VizbeeSDK.logger.debug("SamsungMSFSync::_connectHandler - client= ",e),this.dispatchReceive(new xt(Ot.SYNC_CONNECT,{}))}_disconnectHandler(e){VizbeeSDK.logger.debug("SamsungMSFSync::_disconnectHandler - client= ",e),this.msfLocalChannel=void 0,super.disconnect()}_messageHandler(e,t){VizbeeSDK.logger.debug("SamsungMSFSync::_messageHandler",e),this.dispatchReceive(new xt(Ot.SYNC_MESSAGE,e))}}class en 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 tn 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 tn?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===Ot.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 nn extends tn{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(!V.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,!V.isString(t))return VizbeeSDK.logger.error("SanitizeHeaderRecvExtension:isValidMessage - invalid message id",t,e),s;if(!V.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 rn extends tn{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(!V.isObject(i))return t;if(!V.isObject(i.cmd))return t;if(!V.isString(i.cmd.name)||!V.isString(i.cmd.ns))return t;if("start_video"==i.cmd.name){let e=i.vinfo;if(!V.isObject(e))return t;if(!V.isString(e.id)&&!V.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 sn extends tn{constructor(e,t){super(e,t)}getActiveSenders(){throw new TypeError("BaseSyncWithPresence::getSenders() - Abstract method.")}getActiveSendersCount(){throw new TypeError("BaseSyncWithPresence::getActiveSendersCount() - Abstract method.")}}class an extends sn{constructor(e,t){if(!(e instanceof sn))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 on{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),!V.isUndefined(e.cmd)){var i=0;V.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=V.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=V.clone(t);return e.senderInfo=V.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:Ot.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:Ot.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=V.extend(t,on.encodeVideoInfo(e)),t}}class dn extends an{constructor(e,t){super(e,t)}handleSyncReceiveEvent(e){if("start_video"==e.data.b.cmd.name){let t=on.decodeVideoInfo(e.data.b);t&&(t=on.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=on.decodeVideoInfo(e.b);return i&&(i=on.addInfoFromHeader(i,e.h)),t.items.push(i),t}}class ln extends sn{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=V.omit(this._senderMap,V.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=V.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 xt(Ot.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=V.omit(this._senderMap,V.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 xt(Ot.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 xt(Ot.SYNC_PRESENCE,this._senderMap)))}}class cn extends an{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=V.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 un=["BUFFERING","PLAYING","PAUSED_BY_USER","INTERRUPTED","FINISHED","FAILED"];class pn extends an{constructor(e,t){super(e,t),this.appConfig=t,this.shouldSupportLiveDVR=V.get(t,["features","shouldSupportLiveDVR"],!1),this.liveDVRMinBufferInMs=V.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 un.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 hn{static setItem(e,t,i,n,r,s,a){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!"),k.docCookies.setItem(e,t,n,r,s,a)}}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!"),k.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;k.docCookies.removeItem(e,i,n)}}}class gn{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),a=this._getURIEncodedString(s),o="GET";this._needPostRequest(a)?(i=this.senderConfig.url,o="POST",n=JSON.stringify({data:a})):(i=this.senderConfig.url+"?data="+a,o="GET",n=void 0),VizbeeSDK.logger.d(`${this.constructor.name}`,`track() - sending metrics request: URL ${i}, Method ${o}, Data ${n}`),k.xhr({url:i,method:o,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 fn extends gn{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 vn extends gn{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 yn{constructor(e){this.senders=[],e&&e.vizbee_url&&this.senders.push(new vn(e)),e&&e.mixpanel_url&&e.mixpanel_token&&this.senders.push(new fn(e))}track(e,t){VizbeeSDK.logger.d(`${this.constructor.name}`,"track",e,t),V.each(this.senders,i=>{i.track(e,V.clone(t))})}}const mn="UNKNOWN";var bn=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 yn(e.metricsParams),this.appSessionId=Math.floor(1e10*Math.random()).toString()+"_"+Date.now(),this.screenSdkId=hn.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(),hn.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!")}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!=mn&&(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=V.get(VizbeeTV.tv.deviceInfo,["os","version"],mn),r.osNativeVersion=V.get(VizbeeTV.tv.deviceInfo,["os","sdkVersion"],mn)),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=mn,this.commonProperties.SCREEN_IDFV=mn,this.commonProperties.SCREEN_HOMESSO_USER_INFO={user_login:mn,user_login_type:mn,user_name:mn,user_subscription_renewal_type:mn,user_subscription_type:mn,user_subscription_value:mn},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="NOT_FOUND",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=V.extend(e,t))}),t(e)}).catch(i=>{console.error("Error getting attributes:",i),t(e)})}setCustomProperties(e){VizbeeSDK.logger.d("MetricsManager","setCustomProperties"),V.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=V.reject(this.attributesProvidersList,t=>t.provider==e)}trackEvent(e,t){this.shouldTrack(e,t)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackEvent",e);let i=V.extend({},this.commonProperties,t);this.track(e,i)})}trackScreenLaunched(){this.shouldTrack("SCREEN_LAUNCHED",this.commonProperties)&&this._setUpdatedCommonProperties(()=>{VizbeeSDK.logger.d("MetricsManager","trackScreenLaunched");let e=V.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+":"+k.uuidv4()+":"+Date.now(),this.needToSetDistinctIdForVideoEvents=!1;let t=V.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,k.uuidv4(),Date.now()),this.needToSetDistinctIdForVideoEvents=!0);let t=V.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=V.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=V.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=V.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=V.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=V.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=V.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=V.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 V.extend({VIDEO_PAUSED_TIME_MS:Math.round(e.videoPausedTimeInMs)},this.buildScreenTVViewDurationProperties(e))}buildScreenTVViewDurationProperties(e){return V.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=V.extend({},k.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),a=2*Math.ceil(i/2),o=2*Math.ceil(n/2);return V.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:a||0,AUDIO_BUFFER_2SEC_BIN:o||0},this.buildVideoProperties(e))}buildScreenTVViewStartTimeQualityProperties(e){return e&&V.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 V.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!=mn||(t.adId=VizbeeTV.tv.adId||mn),this.commonProperties.isAdTrackingDisabled&&this.commonProperties.isAdTrackingDisabled!=mn||(t.isAdTrackingDisabled=VizbeeTV.tv.isAdTrackingDisabled||mn),VizbeeTV.tv.deviceInfo&&(VizbeeTV.tv.deviceInfo.deviceId&&VizbeeTV.tv.deviceInfo.deviceId!=mn&&(t.deviceId=VizbeeTV.tv.deviceInfo.deviceId),VizbeeTV.tv.deviceInfo.model&&VizbeeTV.tv.deviceInfo.model!=mn&&(t.deviceModel=VizbeeTV.tv.deviceInfo.model)),this.setAttributesProviderProperties(t,t=>{this.setCommonProperties(t),e()})}};const Sn="receiver_with_applets";class _n extends an{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){bn.init(this.appConfig),bn.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"),bn.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||{};bn.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,bn.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&&bn.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&&bn.trackScreenTVSignin(e)}return e}handleNonSyncReceiveEvent(e){if(e&&e.type==Ot.SYNC_PRESENCE){let t=e.data;if(t&&this.senderMap){let e=Object.keys(this.senderMap),i=Object.keys(t);i.length>e.length?i.forEach(e=>{this.senderMap[e]||(!t[e]||"vzb0000000"===t[e].appId&&this.targetAppType===Sn||(VizbeeSDK.logger.d("MetricsExtension","handleNonSyncReceiveEvent","new sender connected, id = "+e),bn.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 In extends an{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){bn.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"),bn.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"),bn.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 En=E(wt());class Tn extends an{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?En.enableTracks(i):En.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=En.getTracks(r),i=En.getEnabledTracks(r);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 Vn extends an{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}`),En.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=En.getAudioTracks(s),i=En.getActiveAudioTrack(s);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 Pn=[nn,rn,ln,dn,class extends an{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())}},cn,class extends an{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")}},pn,In,_n,class extends an{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();V.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=V.keys(this._androidSendersWithoutFGFlagMap),i=V.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 xt(Ot.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)}},Tn,Vn],An=[nn,rn,ln,dn,cn,pn,In,_n,Tn,Vn,null];let Cn;class wn{createSync(e){let t=V.get(e,["syncInfo","syncMethod"],"pubnub").toLowerCase();return"googlecustom"==t?(Cn=this.getGoogleCustomSyncInstanceWitExtensions(e),Cn):"googledual"==t?(Cn=this.getGoogleDualSyncInstanceWitExtensions(e),Cn):"samsungmsf"==t?(Cn=this.getSamsungMsfSyncInstanceWitExtensions(e),Cn):"samsungdual"==t?(Cn=this.getSamsungDualSyncInstanceWitExtensions(e),Cn):(Cn=this.getDefaultSyncInstanceWitExtensions(e),Cn)}static getSync(){return Cn}getGoogleCustomSyncInstanceWitExtensions(e){return this.addExtensions(e,this.getGoogleCastSync(e),An)}getGoogleDualSyncInstanceWitExtensions(e){let t=this.addExtensions(e,new $i(e),Pn),i=this.addExtensions(e,this.getGoogleCastSync(e),An),n=new en(e);return n.addSyncInstance(t),n.addSyncInstance(i),n}getSamsungMsfSyncInstanceWitExtensions(e){return this.addExtensions(e,new Zi(e),Pn)}getSamsungDualSyncInstanceWitExtensions(e){let t=this.addExtensions(e,new $i(e),Pn),i=this.addExtensions(e,new Zi(e),Pn),n=new en(e);return n.addSyncInstance(t),n.addSyncInstance(i),n}getDefaultSyncInstanceWitExtensions(e){return this.addExtensions(e,new $i(e),Pn)}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 Dn=function(e){return e[e.NOT_CONNECTED=1]="NOT_CONNECTED",e[e.CONNECTING=2]="CONNECTING",e[e.CONNECTED=3]="CONNECTED",e}({});var kn,Nn,Mn,xn,On,Ln,zn,Rn,Kn=T(),Hn=Dt(),Un=function(){if(St)return bt;St=1,T();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(),bt={type:"VGAStateManager",app:{state:"app"},video:e,ad:t,reset:i,addListener:function(e){},removeListener:function(){}}}(),Fn=Qe(),Bn=kt(),Gn=wt(),Wn=Nt(),jn=750;let qn;class Yn{static getInstance(){return null==qn&&(qn=new Yn),qn}getQueueManager(){return null==this.queueManager&&(this.queueManager=new null(null.getInstance())),VizbeeSDK.logger.debug("ContinuityContext::getQueueManager - returning queue manager",this.queueManager),this.queueManager}}var Jn,$n,Xn,Qn=T(),Zn=function(){if(Ge)return Be;Ge=1;var e,t,i=We().xhr,n=T(),r={appId:null,config:null,pub_key:"pub-c-1e4f216f-168e-4fdc-8a2b-a29ffe05cb5b",sub_key:"sub-c-6da25f1b-58d7-4f17-bd10-21a30198a794"};return Be={appConfig:r,getConfig:function(s,a){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/";return s+="apps/"+r.appId+"/screen/"+e,t&&(s+="."+t),s+="?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 a&&(VizbeeSDK.logger.debug("Config:getConfig - calling callback with extended config =",r),a(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!")})}},Be}(),er=$e,tr=function(e,t){var i,n=e,r=void 0,s=void 0,a=!1,o=!1,d=!1,l=!1;let c=n&&n.features&&n.features.syncSendIntervalInMs;isNaN(c)||(jn=c);var u=[],p=[],h={};return t?(a=!0,i=Un):(a=!1,i=Hn,Gn.setAppStateManager(Hn),Wn.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 wn;(r=t.createSync(n)).onReceive=function(t){if(t)switch(t.type){case Ot.SYNC_CONNECT:!function(e){o=!0,a&&(VizbeeSDK.logger.debug("SyncController::syncConnectHandler - setting isAppAdapterAvailable to TRUE (isVGA=true)"),d=!0),g(),e(!0)}(e);break;case Ot.SYNC_MESSAGE:var i=t.data.b,n=t.data.h;if(a&&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 Ot.SYNC_PRESENCE:a||function(e){VizbeeSDK.logger.debug("SyncController::presenceHandler() - connected users count",e);var t=Kn.extend({},h);h=Kn.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),Fn.updatePresence(e)}(t.data)}var r,s,l},r.connect(e),i.addListener(S),Fn.isAppSet()&&(VizbeeSDK.logger.debug("SyncController::connect appIsSet"),d=!0,g()),u.forEach(e=>{e(Dn.CONNECTED)}),s=window.setInterval(_,jn)},disconnect:function(){VizbeeSDK.logger.debug("SyncController::disconnect() called"),clearInterval(s),i.removeListener(S),u.forEach(e=>{e(Dn.NOT_CONNECTED)}),f(),r.disconnect(),o=!1},isConnected:function(){return o},addSessionStateListener:function(e){u.push(e)},sessionState:function(){return o?Dn.CONNECTED:Dn.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():{}}};function g(){if(o&&d){a&&!l&&(l=!0,Bn.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",o,d)}function f(){if(o&&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",o,d)}function v(e,t={}){var s,a,o,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(Kn.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,Gn.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()"),Gn.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);Gn.pause();break;case"play":if("video"!==i.app.state)return void VizbeeSDK.logger.warn("play requested when not in 'video' state",i.app.state);Gn.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";Gn.stop(u);break;case"exit":s={cmd:{ns:"video",name:"olleh",type:"upd"},hstatus:{id:n.deviceId,type:"SCREEN",vip:"false"}},r.send(s),Gn.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(Kn.isUndefined(e.cmd.param))return void VizbeeSDK.logger.debug("2",e);if(a=parseInt(e.cmd.param,10),isNaN(a))return void VizbeeSDK.logger.debug("3",a);if(i.video&&i.video.duration&&(o=i.video.duration,VizbeeSDK.logger.debug("4",a,o),a>o))return;if(a<0)return void VizbeeSDK.logger.debug("5",a);Gn.seek(a);break;case"vol_up":"function"==typeof Gn.volumeUp&&Gn.volumeUp();break;case"vol_down":"function"==typeof Gn.volumeDown&&Gn.volumeDown();break;case"mute":"function"==typeof Gn.mute&&Gn.mute(!0);break;case"unmute":"function"==typeof Gn.mute&&Gn.mute(!1);break;case"set_tracks":"function"==typeof Gn.setTracks&&Gn.setTracks(e.cmd.param||[]);break;case"event":"function"==typeof Gn.onEvent&&e.einfo&&e.einfo.data&&(Gn.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),Gn.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(),a={cmd:{name:"status",ns:"video",type:"upd"}};t&&(e=t.volume,t.muted&&(e=0),a.vinfo={id:t.id,url:""},r.id||(r=s),a.vinfo.islive=!1,a.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?(a.vinfo.url=r.videourl,a.vinfo.islive=r.islive,a.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:E(t)}):s&&s.id&&(a.vinfo.url=s.videourl,a.vinfo.islive=s.islive,a.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:E(t)}),a.vinfoext.wasVideoStartedByVizbee=i.wasVideoStartedByVizbee(),a.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||(a.vstatus.du=0)),n&&t&&"PAUSED_BY_AD"==t.state&&(a.adstatus={du:parseInt(n.duration,10)||-1,id:n.id,po:parseInt(n.position,10)||-1,st:n.state});var o=Fn.getVideoInfo();return o&&(o.id&&(a.vinfo=a.vinfo||{},a.vinfo.id=o.id,a.vstatus=a.vstatus||{},a.vstatus.id=o.id),void 0!==o.videourl&&(a.vinfo=a.vinfo||{},a.vinfo.url=o.videourl),void 0!==o.islive&&(a.vinfo=a.vinfo||{},a.vinfo.islive=o.islive),void 0!==o.title&&(a.vinfoext=a.vinfoext||{},a.vinfoext.title=o.title),void 0!==o.subtitle&&(a.vinfoext=a.vinfoext||{},a.vinfoext.subtitle=o.subtitle),void 0!==o.imgurl&&(a.vinfoext=a.vinfoext||{},a.vinfoext.imgurl=o.imgurl),void 0!==o.isdvrsupported&&(a.vinfoext=a.vinfoext||{},a.vinfoext.isdvrsupported=o.isdvrsupported),void 0!==o.state&&(a.vstatus=a.vstatus||{},a.vstatus.st=o.state),void 0!==o.position&&(a.vstatus=a.vstatus||{},a.vstatus.po=parseInt(o.position,10)),void 0!==o.duration&&(a.vstatus=a.vstatus||{},a.vstatus.du=parseInt(o.duration,10))),a}function E(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}}},ir=Dt(),nr=Qe(),rr=kt(),sr=wt(),ar=Ct(),or=function(){if(Nn)return kn;Nn=1;var e,t,i=T(),n=new(0,Xe().EventEmitter),r={preparing:!1,playing:!1,alladscomplete:!1},s=-1,a=-1,o=!1;function d(e){var n={type:"ad",position:-1,duration:-1,preparing:r.preparing,playing:r.playing,alladscomplete:r.alladscomplete};return r.playing&&(a>0?(n.position=s,n.duration=a,VizbeeSDK.logger.debug("[VZB-DEBUG] AdAdapter::Status using app ad timing — po:",s,"du:",a)):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,a,o=!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&&(a="LOADING",s.id="UNKNOWN"),"play"===e.type&&(a="LOADING"),"playing"===e.type&&(a="PLAYING",t&&t.basePlayer&&t.basePlayer.videoInfo&&t.basePlayer.videoInfo.src&&(s.id=t.basePlayer.videoInfo.src)),"error"===e.type&&(a="INTERRUPTED",r.playing=!1),"ended"===e.type&&(a="FINISHED",r.playing=!1),s.playing=r.playing,a&&(s.state=a),n.emit("ad",s,o))}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?(o=!1,r.preparing=!0,l({type:"preparing"})):"ad-start"===t?(o=!1,l({type:"play"})):"ad-playing"===t?(r.playing=!0,e.data&&(void 0!==e.data.duration&&e.data.duration>0&&(a=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:",a))):("ad-pod-end"===t&&(r.playing=!1,r.alladscomplete=!0,s=-1,a=-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"}),o=!1)},t.onEnded=function(){r.playing&&(l({type:"ended"}),o=!1)},t.onTimeUpdate=function(e){r.playing&&(o?l({type:"timeupdate"}):(o=!0,l({type:"playing"})))},e||p(t))}function p(t){VizbeeSDK.logger.debug("VIZBEE: AdAdapter.setAdsManager()",t),(e=t).onEvent=c,u(e)}return kn={setAdVideo:u,setAdsManager:p,reset:function(){r.preparing=!1,r.playing=!1,r.alladscomplete=!1,s=-1,a=-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)}}}(),dr=function(){if(Ln)return On;Ln=1,T();var e=function(){if(xn)return Mn;xn=1;var e=Xe().EventEmitter;const t="ad";var i=new e,n={type:t,state:"UNKNOWN",id:"UNKNOWN",position:-1,duration:-1,playing:!1,adPodStarted:!1,adPodsPlayedDuration:0,totalAdPodsDuration:0};return Mn={adStatus:n,reset:function(){n.state="UNKNOWN",n.id="UNKNOWN",n.position=-1,n.duration=-1,n.playing=!1,n.adPodStarted=!1},resetTotalAdPodsDuration:function(){n.adPodsPlayedDuration=0,n.totalAdPodsDuration=0},addListener:function(e){i.addListener(t,e)},removeListener:function(e){i.removeListener(t,e)},notify:function(e){i.emit(t,n,e)}}}();const t=["loadedmetadata","play","playing","timeupdate","error","ended"];var i,n;function r(t){if(e.adStatus.adPodStarted){var r="LOADING";"loadedmetadata"==t.type||"play"==t.type?r="LOADING":"playing"==t.type?(e.adStatus.id=i.src,r="PLAYING"):"timeupdate"==t.type?r="PLAYING":"error"==t.type?r="FAILED":("ended"==t.type||i.ended)&&(r="FINISHED");var s=!1;r!=e.adStatus.state&&(s=!0,e.adStatus.state=r),e.adStatus.playing&&e.adStatus.duration>0&&n>=0?e.adStatus.position=1e3*i.currentTime-n:e.adStatus.position=-1,e.notify(s)}}function s(){e.reset(),n=-1}function a(){s(),e.notify()}return On={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(){a()},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:a,resetTotalAdPodsDuration:function(){e.resetTotalAdPodsDuration()},addListener:function(t){e.addListener(t)},removeListener:function(t){e.removeListener(t)}}}(),lr=Nt(),cr=(Rn||(Rn=1,zn={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)}}}),zn),ur=void 0,pr=void 0,hr=!1,gr=[],fr="vzb0000000";function vr(){if(Xn&&Xn.features&&Xn.features.shouldSyncDisconnectOnBackground){if(hr)return;ur?ur.isConnected()||(VizbeeSDK.logger.i("SDK","onForeground","connecting VGA"),hr=!0,br(fr,function(){hr=!1,pr&&!pr.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET after VGA ",$n.id),hr=!0,br($n.id,function(){hr=!1}))})):pr&&!pr.isConnected()&&(VizbeeSDK.logger.i("SDK","onForeground","connecting APPLET ",$n.id),hr=!0,br($n.id,function(){hr=!1}))}}function yr(){return VizbeeSDK.logger.i("SDK","onBackground"),Xn&&Xn.features&&Xn.features.shouldExitOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","exiting the app"),void VizbeeTV.tv.exit()):Xn&&Xn.features&&Xn.features.shouldSyncDisconnectOnBackground?(VizbeeSDK.logger.i("SDK","onBackground","disconnecting from sync"),ur&&ur.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting VGA"),ur.disconnect()),pr&&pr.isConnected()&&(VizbeeSDK.logger.i("SDK","_disconnectFromSync","disconnecting APPLET"),pr.disconnect()),void(hr=!1)):void Er()}function mr(){VizbeeSDK.logger.i("SDK","onEnd","sending olleh"),Er()}function br(e,t){Zn.getConfig({appId:e||$n.id,deviceId:"",platform:VizbeeTV.tv.cloudPlatformName,platformModel:VizbeeTV.tv.platformModel,hostProxy:$n.configServiceProxyHost},function(e){Xn=e,VizbeeSDK.logger.d("SDK","getConfig","got config=",Xn),Xn.customAttributesForMetrics=$n.customAttributesForMetrics,er.getIpv6Address(function(e){VizbeeSDK.logger.d("SDK","getIpv6Address","got response=",e),Xn.ipv6Address=e,function(e,t){cr.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),hr=!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+"]",He.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==fr||e.features&&e.features.targetAppType==Sn?(fr=e.appId,ur||(ur=new tr(e,!0)),ur.connect(function(e){e?VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connected VGA"):VizbeeSDK.logger.e("SDK","onConfigAndDeviceIDReady","failed to connect VGA")})):(pr||(VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","creating appletSyncController"),pr=new tr(e,!1),Qn.each(gr,e=>{e()})),VizbeeSDK.logger.d("SDK","onConfigAndDeviceIDReady","connecting appletSyncController"),pr.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),hr=!1,t&&t(void 0)})}(Xn,t)})})}function Sr(e){VizbeeSDK.logger.d("SDK","setApp"),nr.setApp(e)}function _r(e){VizbeeSDK.logger.d("SDK","setVideo","video=",e),sr.setVideo(e)}function Ir(e){Jn={vzb_ad_ima:null,vzb_ad_ssai:dr,vzb_ad_ssai_avplay:null,vzb_ad_default:or}[e.toLowerCase()],sr.setAdAdapter(Jn)}function Er(){lr.send({type:"sync_proxy_video_cmds",cmd:{ns:"video",name:"olleh",type:"int"}})}var Tr={ContinuityContext:Yn,QueueBase:null,QueueManager:null,QueueDelegate:null,QueueDelegateFactory:null},Vr={VERSION:"7.8.35",wasVideoStartedByVizbee:function(){return ir&&ir.wasVideoStartedByVizbee()},init:function(e){VizbeeSDK.logger.i("SDK","init"),VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.addHandler("onForeground",vr),VizbeeTV.tv.appLifeCycleManager.addHandler("onBackground",yr),VizbeeTV.tv.appLifeCycleManager.addHandler("onEnd",mr)),$n=e,VizbeeSDK.logger.i("SDK","onStart"),$n&&$n.id&&(function(e){var t;VizbeeSDK.logger.d("SDK","handleInitOptions"),e.video&&_r(e.video),e.app&&Sr(e.app),e.videoAdapter&&(t=e.videoAdapter,VizbeeSDK.logger.d("SDK","setHostVideoAdapter","video=",t),ar.setVideoAdapter(t)),e.adType&&Ir(e.adType),e.VGA&&e.isVGA&&rr.setVGA(e.VGA)}($n),sr.init(),br())},setApp:Sr,setVideo:_r,setVideoGuid:function(e,t){sr.setId(e,t)},setVideoInfo:function(e){VizbeeSDK.logger.d("SDK","setVideoInfo","videoInfo=",e),sr.setVideoInfo(e)},setVideoStop:function(){sr.setVideoStop()},setAdsVideo:function(e){VizbeeSDK.logger.d("SDK","setAdsVideo","video=",e),Jn?Jn.setAdVideo(e):VizbeeSDK.logger.d("SDK","setAdsVideo","AdAdapter not configured; skipping")},getAdsAdapter:function(){return Jn},setAdType:Ir,sendXMessage:function(e,t,i){if(!pr)return void VizbeeSDK.logger.e("XMessages",this.constructor.name,"sendXMessage","appletSyncController not initialized");if(Qn.get(Xn,["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 lr.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`),lr.send(n)},syncProxy:lr,addSyncReadyListener:function(e){gr.push(e)},removeSyncReadyListener:function(e){gr=Qn.without(gr,e)},getSyncController:function(){return pr},getMetricsManager:function(){return bn},wrapVideoCallbacks:sr.wrapCallbacks,addVideoEventListener:sr.addEventListener,removeVideoEventListener:sr.removeEventListener,reset:function(){VizbeeSDK.logger.d("SDK","reset");try{pr&&(pr.disconnect(),pr=void 0)}catch(e){VizbeeSDK.logger.e("SDK","reset","error disconnecting appletSyncController.",e)}try{ir.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppStateManager",e)}try{nr.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AppAdapter",e)}try{Jn&&Jn.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting AdAdapter",e)}try{sr.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset"," error resetting VideoAdapter",e)}try{ar.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting HostVideoAdapter",e)}try{lr.reset()}catch(e){VizbeeSDK.logger.e("SDK","reset","error resetting SyncProxy",e)}try{VizbeeTV.tv.appLifeCycleManager&&(VizbeeTV.tv.appLifeCycleManager.removeHandler("onForeground",vr),VizbeeTV.tv.appLifeCycleManager.removeHandler("onBackground",yr),VizbeeTV.tv.appLifeCycleManager.removeHandler("onEnd",mr))}catch(e){VizbeeSDK.logger.e("SDK","reset","error removing app lifecycle handlers",e)}},framework:Tr};window.VizbeeSDK||(window.VizbeeSDK={},VizbeeSDK.logger||(VizbeeSDK.logger=new He,VizbeeSDK.logger.setPrefix("[Vizbee]")));var Pr=window.VZB;Pr=Vr,window.VZB=Pr;class Ar{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 a={id:e,app:this.appAdapter,videoAdapter:this.videoAdapter,adAdapter:this.adAdapter,customAttributesForMetrics:{}};this.vgaAdapter?(a.isVGA=!0,a.VGA=this.vgaAdapter):a.video=VizbeeTV.tv.player,a.customAttributesForMetrics=Object.assign(a.customAttributesForMetrics,this.platformConfig.customAttributesForMetrics,this.vzbOptions.customAttributesForMetrics),this.vzbOptions.configServiceProxyHost&&(a.configServiceProxyHost=this.vzbOptions.configServiceProxyHost),VZB.init(a)}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 Cr={};class wr extends Ar{get VERSION(){return window.VZB?window.VZB.VERSION:""}init(e,t,i,n){let r=ze.getPlatformType();r&&this.initAppOnPlatform(e,t,r,i,t.mediaManagerAdapter,n)}initAppOnPlatform(e,t,i,n,r,s){i=i.toLowerCase(),Cr[i]&&!t.vgaAdapter?(this._apiWrapper=new Cr[i],this._apiWrapper.setOptions(s),this._apiWrapper.initAppOnPlatform(e,t,i,n,r)):(this._apiWrapper=new Ar,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 Dr,kr;class Nr{constructor(){this.virtualAPIWrapper=ms,this.vzbOptions={}}static getInstance(){return null==Dr&&(Dr=new Nr),Dr}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 xr{get ContinuityContext(){return Nr}get ContinuityOptions(){return Mr}}class Or{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 Lr{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 zr{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 Rr{constructor(e,t){this.type=e,this.data=t}}class Kr{constructor(e,t){this.adType=e,this.playerElement=t,this.vtvPlayerEvent=new Rr}updateAdStatus(e){this._isValidAdStatus(e)?this._handleAdStatus(e):vizbee.logger.verbose("AdAdapter::updateAdStatus - invalid ad status")}_isValidAdStatus(e){return e instanceof zr?-1!=[Lr.AD_POD_WAITING,Lr.AD_PREPARING,Lr.AD_POD_START,Lr.AD_POD_END,Lr.AD_START,Lr.AD_PLAYING,Lr.AD_PAUSED,Lr.AD_END,Lr.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 Hr{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 Ur{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 Fr{static get UNKNOWN(){return"unknown"}static get SSAI(){return"ssai"}static get CSAI(){return"csai"}}class Br{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 Gr{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 Wr{constructor(){this._guid="",this._state=Gr.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 jr{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 qr extends Nr{constructor(){super(),this.appAdapter=new Or,this.playerAdapter=void 0,this.adAdapter=void 0,this.adType=void 0}static getInstance(){return null==kr&&(kr=new qr,vizbee.logger.d(this.constructor.name,"getInstance","created")),kr}getAppAdapter(){return this.appAdapter}setAppAdapter(e){e instanceof Or&&(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 Wr)return e}}getAdAdapter(e){return this.adAdapter}setAdAdapter(e){return e instanceof Kr?this._isValidAdType(e.adType)?(this.adAdapter=e,this.setAdType(Fr.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 Br;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 jr;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeSigninEventHandler(t)}if(this.appAdapter&&this.appAdapter.vizbeeEventHandler&&e){let t=new jr;t.type=e.type,t.data=e.data,this.appAdapter.vizbeeEventHandler(t)}if(this.playerAdapter&&this.playerAdapter.vizbeeEventHandler&&e){let t=new jr;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:()=>{if(this.playerAdapter&&this.playerAdapter.getVideoInfo){let e=this.playerAdapter.getVideoInfo();if(e instanceof Wr){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.state&&"idle"!==e.state&&(t.state=this._mapPlayerStateToSyncState(e.state)),e.currentPosition>=0&&(t.position=e.currentPosition),e.duration>=0&&(t.duration=e.duration),t}}}},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==Ur.BITMOVIN&&(t.vtvPlayerListConfig=[{type:"bitmovin"}]),e.playerType==Ur.VIDEOJS&&(t.vtvPlayerListConfig=[{type:"videojs"}]),e.playerType==Ur.THEO&&(t.vtvPlayerListConfig=[{type:"theo"}]),e.playerType==Ur.SHAKA&&(t.vtvPlayerListConfig=[{type:"shaka"}]),t}_isValidVideoInfo(e){return e instanceof Br||(vizbee.logger.w(this.constructor.name,"_isValidVideoInfo","videoInfo should be of type vizbee.continuity.messages.VideoInfo"),!1)}_isValidPlayerAdapter(e){return e instanceof Hr?!(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==Fr.SSAI||e==Fr.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",buffering:"BUFFERING",interrupted:"INTERRUPTED",ended:"FINISHED",error:"FAILED"}[e]||e}_getAdAdapterType(e){if(e&&e.playerType)return this.adType==Fr.CSAI?"vzb_ad_default":this.adType==Fr.SSAI?e.playerType==Ur.AVPLAYER?"vzb_ad_ssai_avplay":"vzb_ad_default":void 0;vizbee.logger.w(this.constructor.name,"_getAdAdapterType","INVALID playerAdapter")}_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 Yr{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 Jr extends G{constructor(e){if(!(e instanceof G))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 Jr?this.extendedPlayer.basePlayer:void 0}isExtendedPlayerBasePlayer(){return this.extendedPlayer instanceof G&&!(this.extendedPlayer instanceof Jr)}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 $r extends Hr{constructor(){super(Ur.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===Jr.name?t=e.basePlayer:Object.getPrototypeOf(e.constructor).name===G.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 Xr{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 Qr{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 Zr{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 es extends Zr{constructor(){super(),this.type=r,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 ts{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(),k.removeClass("hidden",this.nodes.popupMessageWithIconOverlay))}hide(){this.nodes&&this.nodes.popupMessageWithIconOverlay&&this.nodes.popupMessageWithIconContainer&&(k.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,V.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 is{constructor(e){this.uiConfig=e,this.popupMessageWithIconView=void 0}show(e=8){this.hide(),this.uiConfig&&"function"==typeof this.uiConfig.toJSON?(this.popupMessageWithIconView=new ts,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 ns={TOP_LEFT:"top-left",TOP_RIGHT:"top-right",BOTTOM_LEFT:"bottom-left",BOTTOM_RIGHT:"bottom-right"};class rs{constructor(){this._message="This is a vizbee snackbar message",this._theme={color:"#FFFFFF",bgColor:"#7F98DE"},this._layout={position:ns.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 ss(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 as{constructor(){ss(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 os=function(e){return e.ANDROID_MOBILE="Android",e.IOS="iOS",e.UNKNOWN="Unknown",e}({}),ds=function(e){return e.ANDROID_MOBILE="ANDROID_MOBILE",e.IOS="IOS",e.UNKNOWN="UNKNOWN",e}({});function ls(e){switch(e){case os.ANDROID_MOBILE:return ds.ANDROID_MOBILE;case os.IOS:return ds.IOS;case os.UNKNOWN:default:return ds.UNKNOWN}}let cs=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({}),us=function(e){return e.JOIN="JOIN",e.LEAVE="LEAVE",e}({});class ps{constructor(){ss(this,"presenceCallbacks",[]),ss(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===us.JOIN?cs.JOIN:cs.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,a,o,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===(a=e.ssinfo)||void 0===a?void 0:a.modelName)&&void 0!==s?s:"UNKNOWN",modelNumber:null!==(o=null==e||null===(d=e.ssinfo)||void 0===d?void 0:d.modelNumber)&&void 0!==o?o:"UNKNOWN",manufacturer:null!==(l=null==e||null===(c=e.ssinfo)||void 0===c?void 0:c.manufacturer)&&void 0!==l?l:"UNKNOWN",deviceType:ls(null==e||null===(u=e.ssinfo)||void 0===u?void 0:u.REMOTE_DEVICE_TYPE)}}}ss(ps,"LOG_TAG","VizbeeBicastMemberPresenceClientImpl");class hs{constructor(){ss(this,"_messagingClient",null),ss(this,"_presenceClient",null)}getMessagingClient(){return this._messagingClient||(this._messagingClient=new as),this._messagingClient}getPresenceClient(){return this._presenceClient||(this._presenceClient=new ps),this._presenceClient}}class gs{constructor(){if(ss(this,"session",null),ss(this,"sessionState",Dn.NOT_CONNECTED),ss(this,"sessionStateListeners",[]),ss(this,"syncController",null),ss(this,"onSessionStateChanged",e=>{var t,i;switch(this.sessionState=e,e){case Dn.CONNECTED:null===(t=window.VizbeeSDK)||void 0===t||null===(t=t.logger)||void 0===t||t.info("VizbeeBicastSessionManager","onSessionStateChanged","CONNECTED"),this.session=new hs,this.sessionStateListeners.forEach(e=>e.onSessionStateChanged(Dn.CONNECTED));break;case Dn.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(Dn.NOT_CONNECTED))}}),gs.instance)return gs.instance;this.init(),gs.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:Dn.NOT_CONNECTED,this.sessionState===Dn.CONNECTED&&(this.session=new hs),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===Dn.CONNECTING}isConnected(){return this.sessionState===Dn.CONNECTED}}class fs{constructor(){if(ss(this,"presenceCallbacks",[]),ss(this,"vizbeeSession",null),fs.instance)return fs.instance;this.init(),fs.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===Dn.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 vs extends xr{constructor(){super()}get ContinuityContext(){return qr}get adapters(){return{AppAdapter:Or,PlayerAdapter:Hr,BasePlayerAdapter:Yr,AVPlayerAdapter:$r,PlayerType:Ur,AdAdapter:Kr,AdType:Fr,VideoStopReason:Xr}}get messages(){return{VizbeeEvent:jr,VideoInfo:Br,VideoStatus:Wr,AdEventType:Lr,AdStatus:zr,PlayerState:Gr,SubtitleTrack:es}}get analytics(){return{AnalyticsProvider:Qr}}get ui(){return{LayoutPosition:ns,Snackbar:is,SnackbarUIConfig:rs}}get analytics(){return{AnalyticsProvider:Qr}}get ui(){return{LayoutPosition:ns,Snackbar:is,SnackbarUIConfig:rs}}get xmessages(){return{VizbeeBicastSessionManager:gs,VizbeeBicastSession:hs,VizbeeMessagingClient:void 0,VizbeePresenceManager:fs}}}var ys=new class extends vs{constructor(){super()}},ms=new class extends wr{constructor(){super()}get continuity(){return ys}get framework(){return ys}};if(ms.logger=new He,ms.logger.setPrefix("[Vizbee]"),"undefined"!=typeof window){if(window.VizbeeSDK=ms,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"))}
package/package.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "vizbee-qa-sdk-lgwebos-es6",
3
+ "version": "1.0.0",
4
+ "description": "Vizbee TV SDK for LG WebOS (ES6)",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ }
10
+ }