UNPKG

@flowplayer/player

Version:
1 lines 109 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):((e="undefined"!=typeof globalThis?globalThis:e||self).flowplayer=e.flowplayer||{},e.flowplayer.ads=t())}(this,(function(){"use strict";var e;!function(e){e[e.ADS=2]="ADS",e[e.ANALYTICS=4]="ANALYTICS",e[e.NO_METERING=8]="NO_METERING",e[e.DEVELOPER_PLAN=16]="DEVELOPER_PLAN",e[e.WOWZA_VIDEO=32]="WOWZA_VIDEO"}(e||(e={}));const t=["localhost","127.0.0.1","0.0.0.0","s.codepen.io","cdpn.io","try.flowplayer.com"];function s(e,s){return!!~t.indexOf(e)||e.indexOf(s)===e.length-s.length}s.check_whitelist=function(e){return!!~t.indexOf(e)};function i(e){this.message=e}i.prototype=new Error,i.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new i("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,r,a=0,n=0,o="";r=t.charAt(n++);~r&&(s=a%4?64*s+r:r,a++%4)?o+=String.fromCharCode(255&s>>(-2*a&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return o};var a=function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,t){var s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s})))}(t)}catch(e){return r(t)}};function n(e){this.message=e}n.prototype=new Error,n.prototype.name="InvalidTokenError";var o=function(e,t){if("string"!=typeof e)throw new n("Invalid token specified");var s=!0===(t=t||{}).header?0:1;try{return JSON.parse(a(e.split(".")[s]))}catch(e){throw new n("Invalid token specified: "+e.message)}};o.InvalidTokenError=n;const d="production";function l(e,t){const s={valid_jwt:!1,raw:"",data:{acl:0},exp:0};let i={c:"{}",exp:0};t=t||{};try{i=o(e),s.valid_jwt=!0}catch(e){}return s.raw=e,s.data=JSON.parse(i.c),s.exp=i.exp,t.require_valid_token&&l.validate(s),s}function c(e){return{grant:e,is_granted:t=>(e&t)===t}}function u(){const e="undefined"!=typeof document&&"undefined"!=typeof window,t=e?navigator.userAgent:"",s=/iP(hone|od)/i.test(t)&&!/iPad/.test(t)&&!/IEMobile/i.test(t),i=/Android/.test(t)&&!/Firefox/.test(t),r=/^((?!chrome|android).)*safari/i.test(t),a=/chrome|crios/i.test(t)&&!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(t),n=/firefox|fxios/i.test(t)&&!/seamonkey/i.test(t),o=/edg/i.test(t),d=/opr|opera/i.test(t),l=/SamsungBrowser/.test(t),c=l&&/SMART-TV/.test(t);return{controls:!s,video:function(t){return e&&document.createElement("video").canPlayType(t)},lang:e&&window.navigator.language,android:i,iphone:s,safari:r,edge:o,opera:d,chrome:a,firefox:n,ios:e&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,samsung:l,samsung_tv:l&&c,touch:"ontouchstart"in window,tizen:"tizen"in window,webOS:"webos"in window}}function h(e){return{width:e.clientWidth,height:e.clientHeight}}function p(e,t,s){return"number"==typeof s&&(s+="px"),e.style.setProperty(t,s),e}l.validate=function(e){if("string"==typeof e&&(e=l(e)),!e||!e.raw){if(s.check_whitelist(window.location.hostname)||"dev"===d.toString())return!0;throw new Error("No token provided in configuration")}if(!e.valid_jwt)throw new Error("Invalid token provided");const t=window.location.hostname,i=s.bind(null,t);if("dev"!==d.toString()&&e.data.domain&&e.data.domain.length&&!e.data.domain.some(i))throw new Error("Domain not allowed");if("dev"!==d.toString()&&1e3*e.exp-Date.now()<0)throw new Error("Expired token");return!0},l.id=function(e){if(e)return"string"==typeof e&&(e=l(e)),e.data.id},c.of=c,c.from_token=function(e){const t=l(e,{require_valid_token:!0});return c.of(t.data.acl)},c.permissions=e;const g="ad-initialized";var m=Object.freeze({__proto__:null,AD_INIT:g,AD_PLAYBACK_ERROR:"ad-playback-error",AD_TEARDOWN:"ad-teardown",AD_VIDEOTAG_ATTACHED:"ad-videotag-attached",AD_BLOCKED:"ad-blocked",AD_REQUEST_ERROR:"ad-request-error",AD_REQUESTED:"ad-requested",AD_REQUEST_COMPLETED:"ad-request-completed",AD_PAUSE_CONTENT:"ad-pause-content",AD_STARTED:"ad-started",AD_COMPLETED:"ad-completed",AD_PAUSED:"ad-paused",AD_RESUMED:"ad-resumed",AD_WAITING:"ad-waiting",AD_PROGRESS:"ad-progress",AD_SKIPPED:"ad-skipped",AD_MUTED:"ad-muted",AD_VOLUME_CHANGED:"ad-volume-changed",AD_FULLSCREEN:"ad-fullscreen",AD_TIMEOUT:"ad-timeout",AD_BREAK_COMPLETED:"ad-break-completed",AD_POSTROLL_FINISHED:"ad-postroll-finished",AD_PREROLL_FINSIHED:"ad-preroll-finished",AD_MIDROLL_FINISHED:"ad-midroll-finished",VPAID_INIT:"vpaid-init",IMA_ADAPTER_INIT:"ad-ima-adapter-init",IMA_BEFORE_ADS_REQUEST:"ad-ima-before-ads-request",IMA_ADS_RENDERING_SETTINGS:"ad-ima-rendering-settings",ADAPTER_INIT_FAILED:"ad-adapter-init-failed",AD_PLAY_REQUESTED:"ad-play-requested",RELOAD_AD_REQUESTED:"reload-ad-requested",AD_ERROR:"ad-error",REQUEST_AD_PAUSE:"request/ad/pause",REQUEST_AD_PLAY:"request/ad/play",REQUEST_AD_MUTE_UNMUTE:"request/ad/muteunmute",AD_SHOW_FIRST_FRAME:"ad/show-first-frame",AD_RESIZE:"ad/resize",AD_SET_UI_FLAGS:"ad/set-ui-flags",PBJS_AVAILABLE:"ad/pbjs"});const _="is-in-viewport";function f(e,t,s){const i=function(e,t){const s=new CustomEvent(e,{detail:t,cancelable:!0});return t&&Object.defineProperty(s,"data",{get:()=>t}),s}(t,s);return e.dispatchEvent(i),e}var v;!function(){let e=!1;try{const t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("testPassive",null,t),window.removeEventListener("testPassive",null,t)}catch(e){}}(),function(e){e[e.OFF=0]="OFF",e[e.ON=1]="ON",e[e.AUDIO_REQUIRED=2]="AUDIO_REQUIRED"}(v||(v={}));function y(e){const t="number"==typeof e?e:parseInt(e,10);return(t>9?"":"0")+t}function A(e){return function(e,t){const s=e.seekable;if("object"!=typeof e.opts||0==s.length)return{head:0,tail:0};const i=b(e),r=t||e.live_state.dvr_window;return{head:i,tail:"number"!=typeof r||i-r<0?s.start(0):i-r}}(e).tail}function b(e){var t;const s=e.seekable;return s.length?e.hasState("is-chromecast-playing")||!(null===(t=e.hls)||void 0===t?void 0:t.liveSyncPosition)?s.end(s.length-1):e.hls.liveSyncPosition:0}function w(e){try{e.dvr_offset=0,e.currentTime=b(e)}catch(e){console.warn("failed to seek to now: %j",e)}}function E(e,t){if(!e.hasState("is-live")||![void 0,0,-1].includes(t)||!e.seekable.length||e.hasState("has-casted"))return e.setState("is-starting",!1);e.once("seeked",()=>e.setState("is-starting",!1)),0===t?function(e){e.currentTime=A(e)}(e):w(e)}function S(e,t){const s=function(){try{return localStorage.getItem("flowplayer/debug")}catch(e){return""}}(),i=(i,...r)=>{try{const a=(null==t?void 0:t.debug)||s;a&&e.match(a)&&console.log(`flowplayer/${e} -- ${i}`,...r)}catch(e){console.warn(e)}};return i.log=i,i}const T=(e,t)=>new(((e,t)=>{const s=e.get(t);if(!s)throw new Error(`no flowplayer component with the name ${t} exists`);const i=window.customElements.get(t);if(!i)throw new Error(`no default flowplayer component with the name ${t} exists`);const r=window.customElements.get(s);return"function"!=typeof r?i:r})(e._customElements,t))(e),L=(e,t,s)=>{window.customElements.get(t)||window.customElements.define(t,s),e.customElements.get(t)||e.customElements.set(t,t)},O="flowplayer-ad-ui",R=S("ads/lifecycle"),M=["ad-playback-error","ad-teardown","ad-break-completed"];async function k({config:e,root:t,content:s,ads:i,ima:r}){var a;R("LifeCycle::initLifeCycle",e,t,s,i,r),s.autoplay=!1;const n=e.autoplay===v.AUDIO_REQUIRED,o=function(e,t){return{muted:!(t||!e.muted),volume:e.volume}}(s,n);s.on("volumechange",()=>{o.volume=s.volume,o.muted=s.muted}),s.on("ad/show-first-frame",()=>{R("showFirstFrame"),t.classList.toggle("ad-hide-first-frame",!1)});const d=T(s,O),l=d;s.emit("ad/set-ui-flags",{ui_flags:null===(a=e.ads)||void 0===a?void 0:a.ui}),s.renderPlugin(d);const c={listening:!1,preload:null==r?void 0:r.preload_ads};if(R("initial",o),i.setVideoTag(s),e.autoplay){R("Trying to autoplay"),t.classList.add("ad-hide-first-frame"),R("hideFirstFrame");await async function e(t,s){const[i,r]=[t.muted,t.volume];R("Lifecycle::peek_content(:muted => %s, :volume => %s)",i,r);const a=()=>new Promise(e=>setTimeout(e,0,!1));s&&(t.muted=!1,t.volume=t.volume?t.volume:1);try{if(await async function(e){return R("Lifecycle::wait_for_source"),new Promise((t,s)=>{let i=0;const r=setInterval(()=>{if(++i>40)return clearInterval(r),s(new Error("No source in 2000ms, giving up"));e.currentSrc&&(t(null),clearInterval(r))},50)})}(t),await function(e){return new Promise(t=>{if(e.hasState(_))return t(null);e.once("viewenter",()=>t(null))})}(t),R("Lifecycle::peek_content::play"),t.volume&&(t.volume=.01),await new Promise(e=>setTimeout(()=>{s&&(t.opts.autoplay=2),t.setState("is-autoplay",!0),e(t.togglePlay(!0))})),t.paused)throw new Error("content failed to play");return R("Lifecycle::peek_content::pause"),await new Promise(e=>setTimeout(()=>e(t.togglePlay(!1)))),t.volume=r,R("Lifecycle::peek_content::true"),!0}catch(n){return t.volume=r,s?(t.muted=!1,0==t.volume&&(t.volume=1),await a()):i||!r?(R("Lifecycle::peek_content::false"),await a()):(R("Lifecycle::peek_content::recover"),t.muted=!0,!!await e(t)||(t.muted=i,R("Lifecycle::peek_content::false"),await a()))}}(s,n)?(R("Can autoplay, start ad"),s.opts.autoplay=1,P({ads:i,content:s,state:c,adContainer:l,ima:r,config:e})):(R("cannot autoplay(audioRequired: %s), fallback to poster state",n),e.autoplay=0,s.emit("ad/show-first-frame",{root:t}),s.setState("is-starting",!0))}e.autoplay||i.hasPreroll()&&function({content:e,ads:t,config:s,state:i,initial:r,adContainer:a,ima:n}){e.once("beforeplay",(async function(o){(e.hasState(_)||"touchend"!=o.type)&&t.shallPlayAd(0)&&(t.adapter.setAttemptingPrerollOnIOS(t.adapter.isCustomPlaybackEnabled()),t.adapter.isCustomPlaybackEnabled()||o.preventDefault(),N({ads:t,content:e,state:i}),R("user_gesture(:intercept) -> shallPlayAd(0: %s)",t.shallPlayAd(0)),s.muted=r.muted,await P({ads:t,content:e,state:i,adContainer:a,ima:n,config:s}),U({ads:t,content:e}))}))}({content:s,ads:i,config:e,state:c,initial:o,adContainer:l,ima:r}),!e.autoplay&&i.hasPreroll()&&c.preload&&P({ads:i,content:s,state:c,adContainer:l,ima:r,config:e}),C({config:e,root:t,content:s,ads:i,state:c,adContainer:l,ui:d,ima:r,initial:o});const u=async e=>{s.removeEventListener("beforeplay",u),i.resetScheduleCounter(),i.hasPreroll()&&(i.adapter.setAttemptingPrerollOnIOS(i.adapter.isCustomPlaybackEnabled()),e.preventDefault(),await i.setCurrentTime(0))};s.on("src",()=>{c.started&&(s.removeEventListener("beforeplay",u),s.addEventListener("beforeplay",u))}),s.on("beforeplay",e=>{(i.adBreak||i.adPlaying||i.adRequesting)&&(i.adBreak&&!i.adLinear||(R("prevented content from starting because ad break is active"),e.preventDefault()))})}async function P(e){e.state.started||(e.content.hasState(_)?await D(e):e.content.once("viewenter",async()=>{await D(e)}))}async function D({ads:e,content:t,adContainer:s,ima:i,state:r,config:a}){var n;r.started=!0;const o=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(s[i[r]]=e[i[r]])}return s}(i,["ads"]),d=h(t.root),l=(null==a?void 0:a.muted)||t.muted,c=Object.assign(Object.assign(Object.assign({container:s,volume:l?0:t.volume,muted:l,autoplay:(null==a?void 0:a.autoplay)||!1,video_source:t.original_src,preload_ads:null===(n=null==a?void 0:a.ima)||void 0===n?void 0:n.preload_ads},o),d));R("start():",c,r),await e.initialize(!1,c,r.preload)}function I(e,t){var s,i;return{content_width:e.clientWidth||(null===(s=e.parentNode)||void 0===s?void 0:s.clientWidth)||t.clientWidth,content_height:e.clientHeight||(null===(i=e.parentNode)||void 0===i?void 0:i.clientHeight)||t.clientHeight}}function C({config:e,root:t,content:s,ads:i,initial:r,adContainer:a,state:n,ui:o,ima:d}){R("addUIListeners()");const l=async()=>{if(i){if(!(i.adapter.isAttemptingPrerollOnIOS()||i.adapter.isCustomPlaybackEnabled()&&s.currentSrc!==s.original_src)){if(s.off("playing",l),R("addUIListeners() -> content started playing"),N({ads:i,content:s,state:n}),!i.shallPlayAd(0)||!i.adapter.isLinearAd())return R("addUIListeners() -> no more preroll ads -> resume content"),s.emit("ad/show-first-frame",{root:t}),await P({ads:i,content:s,state:n,adContainer:a,ima:d,config:e});s.togglePlay(!1),await P({ads:i,content:s,state:n,adContainer:a,ima:d,config:e}),i.shallPlayAd(0)&&i.adapter.isLinearAd()&&(o.classList.add("on","linear"),t.classList.add("is-waiting"),U({ads:i,content:s}))}}else s.off("playing",l)};s.on("playing",l),s.on(["portrait","landscape"],(function(){if(!i)return;const{content_width:e,content_height:r}=I(s,t);i.resize({height:r,width:e})})),s.on("resize",e=>{if(!i||!e.detail)return;const{width:t,height:s}=e.detail.contentRect;i.resize({width:t,height:s})}),s.on("ended",e=>{var r;const a=()=>{e.preventDefault(),Object.assign(e,{prevented:!0})};if(t.classList.contains("ad-linear")&&t.classList.contains("ads-custom-playback-enabled"))return a();i&&(R("ui_listeners(:%s, event: %o)",e.type,e.detail),(null===(r=null==e?void 0:e.detail)||void 0===r?void 0:r.from)!==i&&(a(),i.finished((function(){s.emit("ended",{from:i})}))))}),i.on("ad-requested",()=>{t.classList.toggle("is-waiting",!0)}),i.once("ad-started",()=>{s.on(["beforeplay","beforepause"],e=>{var t;if(!i.adBreak||!i.adapter.isLinearAd())return;e.preventDefault();const s=(null===(t=e.detail)||void 0===t?void 0:t.forced)?"beforeplay"===e.type:!i.adPlaying;s&&i.paused&&i.resume(),s||i.paused||i.pause()})}),i.on("ad-started",e=>{const a=e.detail,{linear:n,ad:o,ad_type:d}=a;let l;if(R(`Ad[linear: ${n}, currentTime: ${s.currentTime}] starting`,o),"preroll"==d&&!n&&s.paused&&s.togglePlay(!0),n&&(l=I(s,t)),i.resize({width:l?l.content_width:o.width,height:l?l.content_height:o.height,linear:n,resize_non_linear:!0}),s.emit("ad/resize",{opts:{linear:n,resizeContainerAlso:!0,width:n?void 0:o.width,height:n?void 0:o.height}}),t.classList.remove("is-waiting"),s.setState("ad-linear",n),s.setState("ad-non-linear",!n),!n){R("non-linear ad / restarting content");try{s.togglePlay(!0),s.volume=r.volume,s.muted=r.muted}catch(e){R(e)}}s.hasState(_)||s.hasState("is-popped-out")||!n||i.pause()}),i.on("ad-pause-content",()=>{s.emit("ad/resize",{opts:{linear:!0,width:0,height:0}})}),s.on(M,e=>async function({root:e,content:t,ads:s,eventName:i,err:r={reason:""}}){R("teardown(event: %s)",i),s.adapter.isAttemptingPrerollOnIOS()&&(s.adapter.setAttemptingPrerollOnIOS(!1),!t.paused&&t.hasState("is-starting")&&t.hasState("is-playing")&&E(t,t.opts.start_time));e.classList.add("is-seamless"),e.classList.remove("is-waiting"),["ad-non-linear","ad-linear"].forEach(e=>t.setState(e,!1)),r.reason&&R("teardown(:err, reason: %s) %o",r.reason);const a=s.getLastAd();if(t.emit("ad/show-first-frame",{root:e}),!s.shouldRestartContent())return R("Lifecycle.teardown(:skip_restart, reason: %s)","Ad prevented restarting content"),x(e);if(t.currentTime>0&&t.currentTime>=t.duration||"postroll"==s.ad_type||!1===(null==a?void 0:a.restart))return R("Lifecycle.teardown(:skip_restart, reason: %s)","was a postroll ad"),x(e);""===t.currentSrc&&t.setSrc(t.original_src);t.paused&&s.shouldRestartContent()&&(R("Lifecycle.teardown(:toggle_play, %s)","attempting to restart content"),await t.togglePlay(!0));if(!t.paused)return R("Lifecycle.teardown(:ok)","restarted video content"),x(e)}({root:t,content:s,ads:i,ui:o,err:e.detail,eventName:e.type}));let c=!!e.autoplay;var u;s.on("viewenter",()=>{c&&!1!==d.autopause&&i.resume()}),s.on("viewleave",(u=()=>{!1!==d.autopause&&(c=!i.paused,i.pause())},e=>{setTimeout((function(){if(!e.defaultPrevented&&!e.prevented)return u(e)}),0)}))}function N({ads:e,content:t,state:s}){s.listening||(t.on(["timeupdate","seeked","playing","seeking"],s=>{e.adapter.isCustomPlaybackEnabled()&&(e.adPlaying||e.paused)||(e.adPlaying&&e.adapter.isLinearAd()&&!t.paused&&t.pause(),U({ads:e,content:t,seek:"seeking"===s.type}))}),s.listening=!0)}function U({ads:e,content:t,seek:s=!1}){e&&e.setCurrentTime(t.currentTime,void 0,s)}function x(e){e.classList.remove("is-seamless")}const F=S("ads/timers");class TimerRegistry{constructor(e={},t={}){this.intervals=e,this.timers=t}}let q=-1;function B(e,t,s){const i=setInterval(s,t);if(F("TimerRegistry.createInterval() -> "+i,e.intervals),"object"==typeof i){const t=++q;return e.intervals[t]=t,t}return e.intervals[i]=i,i}function j(e){if(e)return F("TimerRegistry.empty()",Object.keys(e.timers),Object.keys(e.intervals)),Object.keys(e.intervals).forEach(t=>function(e,t){return F("TimerRegistry.removeInterval() -> "+t,e.intervals),clearInterval(e.intervals[t]),delete e.intervals[t],e}(e,t)),Object.keys(e.timers).forEach(t=>function(e,t){return F("TimerRegistry.removeTimeout() -> "+t,e.timers),clearTimeout(e.timers[t]),delete e.timers[t],e}(e,t)),e}function H(e){try{return e.getAdPodInfo().getPodIndex()}catch(e){return}}class AdLoadingController{adRequestStart(e){"number"==typeof e&&"number"!=typeof this.requestStart&&(this.requestStart=performance.now())}adRequestEnd(){this.requestStart=void 0}getRemainingAdLoadTime(e,t){return"number"!=typeof t||"number"!=typeof this.requestStart?e:Math.max(0,t-(performance.now()-this.requestStart))}}function V(e){return function(e){return!document.fullscreenEnabled&&"function"==typeof e.webkitEnterFullScreen&&"function"==typeof e.webkitExitFullScreen}(e)&&!e.root.classList.contains("no-fullscreen")}class IMA{constructor(e){this.eventHandler=e,this.log=S("ads/adapter/ima"),this.google=window.google,this._adHandlers=[],this._timers=new TimerRegistry,this._started=!1,this._volumeLevel=0,this._adLoaded=!1,this.customPlaybackEnabled=!1,this._paused=!1,this._all_ads_completed=!1,this._currentDuration=0,this._currentRemaining=0,this._currentDisplayTs=0,this._isInitialized=!1,this._adBreakTime=0,this._prepared=!1,this.opts={},this.loadingController=new AdLoadingController}async init(e){this.log("init",this.videoTag,e),this.opts=e,this._dimensions={width:e.width,height:e.height,linear:e.linear},this._prepared=!0,!this._isInitialized&&this.videoTag&&await this.initAdapter()}async initAdapter(){this.log("initAdapter",this.opts);try{await this.initialize(this.opts),this._isInitialized=!0}catch(e){this.log("initAdapter failed:",e),this._prepared=!1,this.eventHandler.trigger("ad-adapter-init-failed")}}isReady(){return!!this._isInitialized}setVideoTag(e){this.videoTag=e,this.customPlaybackEnabled=V(e),e.root.classList.toggle("ads-custom-playback-enabled",this.customPlaybackEnabled)}setAdBreakTime(e){this._adBreakTime=e}getAdBreakTime(){return this._adBreakTime}isCustomPlaybackEnabled(){return this.customPlaybackEnabled}isAttemptingPrerollOnIOS(){var e;return!!(null===(e=null==this?void 0:this.videoTag)||void 0===e?void 0:e.root.classList.contains("preroll-ios"))}setAttemptingPrerollOnIOS(e){var t;null===(t=null==this?void 0:this.videoTag)||void 0===t||t.root.classList.toggle("preroll-ios",e)}isLinearAd(){return!!this._adLinear}getVideoTag(){return this.videoTag}getDimensions(){return this._dimensions||{}}getOpts(){return this.opts}isPaused(){return this._paused}destroy(){j(this._timers),this._adHandlers&&this._adHandlers.forEach(e=>e()),this._adHandlers=void 0,this._adDisplayContainer&&this._adDisplayContainer.destroy(),this._adDisplayContainer=void 0,this._adsLoader&&this._adsLoader.destroy(),this._adsLoader=void 0,this._adsManager&&this._adsManager.destroy(),this._adsManager=void 0}stop(){this._adsManager&&this._adsManager.stop()}initialize(e){const t=this.isAdPod(),s=this._adLoaded||t;if(this.cleanup(),!this.videoTag)return console.warn("videoTag not set during initialization");this.opts=e,this._volumeLevel=e.volume;const i=this.google.ima.settings;if(e.NumRedirects=e.NumRedirects||e.redirects,i.setVpaidMode(e.VpaidMode||this.google.ima.ImaSdkSettings.VpaidMode.INSECURE),i.setDisableCustomPlaybackForIOS10Plus(!this.customPlaybackEnabled),"NumRedirects"in e&&i.setNumRedirects(e.NumRedirects),"AutoPlayAdBreaks"in e&&i.setAutoPlayAdBreaks(e.AutoPlayAdBreaks),"Locale"in e&&i.setLocale(e.Locale),"Ppid"in e&&i.setPpid(e.Ppid),!document.body.contains(e.container))throw new Error("AdDisplayContainer was not found in the document.body");this._adDisplayContainer=new this.google.ima.AdDisplayContainer(e.container,u().tizen||u().webOS?void 0:this.videoTag),this._adDisplayContainer.initialize(),this._adsLoader=new this.google.ima.AdsLoader(this._adDisplayContainer),this.log("ima.initialise(:wait -> ADS_MANAGER_LOADED)",Object.assign(Object.assign({},e),{volume:this.videoTag.volume,muted:this.videoTag.muted})),this._adsLoader.addEventListener(this.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,t=>{if(!this.videoTag)return;this.log("ima.initialise(:done -> ADS_MANAGER_LOADED)\n%o",Object.assign(Object.assign({},e),{volume:this.videoTag.volume,muted:this.videoTag.muted}));const s=new this.google.ima.AdsRenderingSettings;this.log("ima.rendering(preload: %s)",!!e.preload_ads),s.useStyledNonLinearAds=!0,s.enablePreloading=!!e.preload_ads,s.loadVideoTimeout=e.media_timeout||-1,s.restoreCustomPlaybackStateOnAdBreakComplete=this.customPlaybackEnabled,this.customPlaybackEnabled&&(s.playAdsAfterTime=this.videoTag.currentTime),this.eventHandler.trigger("ad-ima-rendering-settings",s);const i=this._adsManager=t.getAdsManager(this.videoTag,s);this.eventHandler.trigger("ad-ima-adapter-init",i),i.addEventListener(this.google.ima.AdEvent.Type.LOADED,()=>{this.log("debug(ima.adsManager): google.ima.AdEvent.Type.LOADED")}),i.addEventListener(this.google.ima.AdErrorEvent.Type.AD_ERROR,()=>{this.log("debug(ima.adsManager): google.ima.AdErrorEvent.Type.AD_ERROR")}),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>{this.log("debug(ima.adsManager): google.ima.AdEvent.Type.STARTED")}),i.addEventListener(this.google.ima.AdEvent.Type.AD_PROGRESS,e=>{var t,s;const i=null===(t=e.getAdData())||void 0===t?void 0:t.duration,r=null===(s=e.getAdData())||void 0===s?void 0:s.currentTime;isNaN(i)||isNaN(r)||(this._currentRemaining=i-r,this.eventHandler.trigger("ad-progress",{remaining:this._currentRemaining,duration:i}))}),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,e=>{this._currentRemaining=-1,this.debugEvent(e);const t=e.getAd();t&&(this._currentDuration=t.getDuration(),this._currentDisplayTs=Date.now(),this.emitWithAd("ad-started",t),t.isLinear()&&IMA.pollRemaining({ima:this,adsManager:i}))}),i.addEventListener(this.google.ima.AdEvent.Type.COMPLETE,e=>{this.debugEvent(e);const t=e.getAd();t&&this.emitWithAd("ad-completed",t),j(this._timers)}),i.addEventListener(this.google.ima.AdEvent.Type.SKIPPED,e=>{this.debugEvent(e);const t=e.getAd();t&&this.emitWithAd("ad-skipped",t)}),i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,e=>{if(this.isAdPod()&&this.videoTag){const e=Math.abs(this.videoTag.currentTime-this.videoTag.duration)<1?-1:this.videoTag.currentTime;this.setAdBreakTime(e)}this.debugEvent(e);const t=e.getAd();t&&this.emitWithAd("ad-pause-content",t)}),i.addEventListener(this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,e=>{this.debugEvent(e),this._started=!1,this._currentDisplayTs=0,this.eventHandler.trigger("ad-break-completed",{force:!0})}),i.addEventListener(this.google.ima.AdEvent.Type.VOLUME_CHANGED,e=>{this.log("IMA::volume(type: %s, event: %o)",e);const t=i.getVolume();this._volumeLevel=t,this.eventHandler.trigger("ad-volume-changed",t)});const r=e=>{this._paused=e,this.eventHandler.trigger(e?"ad-paused":"ad-resumed")};i.addEventListener(this.google.ima.AdEvent.Type.PAUSED,()=>r(!0)),i.addEventListener(this.google.ima.AdEvent.Type.RESUMED,()=>r(!1)),i.addEventListener(this.google.ima.AdEvent.Type.STARTED,()=>r(!1)),i.addEventListener(this.google.ima.AdEvent.Type.VOLUME_MUTED,e=>{this.log("IMA::volume(type: %s, event: %o)","mute",e),this.eventHandler.trigger("ad-muted")});const{width:a,height:n}=e;a&&n&&(i.init(a,n,this.google.ima.ViewMode.NORMAL),this.log("ima.initialise: done initializing"))}),s&&(this.log("Event(reload: %s)","reload-ad-requested"),this.eventHandler.trigger("reload-ad-requested",t)),this.eventHandler.trigger(g,this)}destroyManager(e="unknown"){if(!this._adsManager)return this.log("ima::destroyManager(:skip, label: %s)",e);this.log("ima::destroyManager(:ok, label: %s)",e),this._adsManager.destroy()}reset(){this.destroyManager("reset"),j(this._timers),this.clearAdHandlers(),this._started=!1,this._adLoaded=!1}cleanup(){this.destroyManager("cleanup"),this._adsLoader&&this._adsLoader.destroy(),this._adDisplayContainer&&this._adDisplayContainer.destroy(),this._adLoaded=!1}waitForAdsManager(){return new Promise(e=>{this.log("ima.waitForAdsManager:",this._adsManager),this.once(this._adsLoader,this.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,()=>{this.log("ima.waitForAdsManager(:ok)",this._adsManager),e(this._adsManager)})})}async initAd(e,t=5e3){var s;this.log(`ima.initAd(adTag: ${e}, timeout: ${t})`),this.customPlaybackEnabled||this.loadingController.adRequestStart(this.opts.total_loading_timeout);try{if(await this.requestAd(e,this.loadingController.getRemainingAdLoadTime(t,this.opts.total_loading_timeout)),this._adLoaded=!0,this.customPlaybackEnabled)return;null===(s=this._adsManager)||void 0===s||s.updateAdsRenderingSettings({loadVideoTimeout:this.loadingController.getRemainingAdLoadTime(this.opts.media_timeout||-1,this.opts.total_loading_timeout)})}catch(e){throw this.log("ima.initAd:",e),this._adLoaded=!1,e}finally{j(this._timers)}}async requestAd(e,t){if(this.destroyManager("requestAd"),!this.videoTag)return;this.setAdBreakTime(this.videoTag.currentTime);const{autoplay:s=!1}=this.opts,i=Date.now(),r=this.videoTag.muted;this._volumeLevel=this.videoTag.volume;const a=r||0==this._volumeLevel;this._all_ads_completed=!1,this.log("ima.requestAd(%o)",Object.assign(Object.assign({},this.opts),{autoplay:s,muted:r,timeout:t,adTag:e,_volumeLevel:this._volumeLevel,manager:this._adsManager})),this.clearAdHandlers();const n=new this.google.ima.AdsRequest;n.adTagUrl=e;const{height:o,width:d}=this.opts;return d&&(n.linearAdSlotWidth=d),o&&(n.linearAdSlotHeight=o),!this.opts.disable_non_linear_ads&&d&&(n.nonLinearAdSlotWidth=d),!this.opts.disable_non_linear_ads&&o&&(n.nonLinearAdSlotHeight=o-50),n.setAdWillAutoPlay(s),n.setAdWillPlayMuted(a),n.vastLoadTimeout=t,this.eventHandler.trigger("ad-ima-before-ads-request",{request:n}),this._adsLoader?new Promise(async(e,s)=>{var i;const r=this.waitForAdsManager();null===(i=this._adsLoader)||void 0===i||i.requestAds(n),this.once(this._adsLoader,this.google.ima.AdErrorEvent.Type.AD_ERROR,e=>{s(()=>(this.emitError("ad-request-error",e),Promise.reject(new Error("Ad load failed"))))}),setTimeout(()=>{s(()=>{r.then(e=>{e.destroy(),this._adsManager===e&&(this._adsManager=void 0)});const e=new Error("Ad internal timeout reached");return this.eventHandler.trigger("ad-timeout",e),Promise.reject(e)})},t),e(await r)}).then(e=>new Promise((t,s)=>{this.volume(a?0:this._volumeLevel),this.eventHandler.trigger("ad-volume-changed",this._volumeLevel);const r=this.cuepoints();if(r&&r.length&&0!==r[0])return t({ad:!1,adsManager:e});this.once(e,this.google.ima.AdErrorEvent.Type.AD_ERROR,e=>{s(()=>(this.emitError("ad-request-error",e),Promise.reject(e)))}),this.once(e,this.google.ima.AdEvent.Type.ALL_ADS_COMPLETED,()=>{this._all_ads_completed=!0,t(null)}),this.once(e,this.google.ima.AdEvent.Type.LOADED,e=>{this.eventHandler.trigger("ad-request-completed",{request_load_time:Date.now()-i});const s=e.getAd();s&&(this.log("ima.requestAd: AD_REQUEST_COMPLETED",s.getContentType()),"application/javascript"==s.getContentType()&&this.eventHandler.trigger("vpaid-init",s),t(null))}),this.once(e,this.google.ima.AdEvent.Type.CLICK,()=>{this.log("ima.requestAd: click event"),this.pause()})}),e=>e()):void 0}async playAd(){if(this.log("ima.playAd()",this),!this._adsManager||!this._adLoaded)return;const e=this.currentAd();if(e&&(!this.customPlaybackEnabled||e.isLinear()))try{await this.startAndWaitForAdCompletion(this._adsManager,e.isLinear())}catch(e){throw this.log("ima.playAd",e),e}finally{this._adLoaded=!1,j(this._timers)}}startAndWaitForAdCompletion(e,t){if(!this._started)return this.log("ima.startAndWaitForAdCompletion(manager: %o)",{volume:e.getVolume()}),new Promise((s,i)=>{let r=!1;this.once(e,this.google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{if(this.log("ima.startAndWaitForAdCompletion: CONTENT_RESUME_REQUESTED <<< happened"),this._started=!1,r)return this.log("ima.startAndWaitForAdCompletion: Content resume requested, but trying to recover from ad error");s()}),this.once(e,this.google.ima.AdErrorEvent.Type.AD_ERROR,async e=>{this.log("ima.startAndWaitForAdCompletion: beginning error recovery ->",e),r=!0;try{const{ok:t}=await IMA.pollForFatalError({err:e,ima:this});t&&(r=!1)}catch(t){this._started=!1,i(e)}});const a=this.getVideoTag();if(!a)return;const n=()=>{t&&(this._started=!0),e.start(),this.eventHandler.trigger("ad-play-requested")};if(!t||a.hasState(_)||a.hasState("is-popped-out"))return n();a.paused||a.pause(),a.once("viewenter",()=>n())})}pause(){this.log("ima.pause()"),this._adsManager&&this._adsManager.pause()}resume(){this.log("ima.resume()"),this._adsManager&&this._adsManager.resume()}volume(e){if(this._adsManager)try{return arguments.length>0&&"number"==typeof e&&this._adsManager.setVolume(e),this._volumeLevel=this._adsManager.getVolume()}catch(e){this.log("ima.volume() failed (%o)",e)}}onResize({width:e,height:t,linear:s,silent:i,resize_non_linear:r}){this._adsManager&&(this._adLinear=void 0===s?this._adLinear:s,this.opts&&(e||t)&&(!1===s&&(e+=10,t+=10),this._dimensions={width:e,height:t,linear:s},s&&(this.opts.width=e,this.opts.height=t),(this._adLinear||r)&&(i||this.log("ima.onResize %s x %s",e,t),this._adsManager.resize(e,t,this.google.ima.ViewMode.NORMAL))))}onAdRequestEnd(){var e;this.customPlaybackEnabled||(this.loadingController.adRequestEnd(),null===(e=this._adsManager)||void 0===e||e.updateAdsRenderingSettings({loadVideoTimeout:this.opts.media_timeout||-1}))}getAdInfo(){const e=this.currentAd();if(e)return{duration:e.getDuration(),currentTime:this._currentRemaining}}currentAd(){const e=this._adsManager;if(e)return e.getCurrentAd()}isAdPod(){const e=this.cuepoints();return!!(e&&e.length>1)}cuepoints(){return this._adsManager&&this._adsManager.getCuePoints()}async contentComplete(){this.log("ima.contentComplete() -> ",this),this._adsLoader&&this._adsLoader.contentComplete();const e=this.cuepoints();e&&-1!==e.indexOf(-1)&&await new Promise(e=>{IMA.race(this.eventHandler,["ad-break-completed","ad-error"],e)})}isUiDisabled(){try{const e=this.currentAd();return e&&e.isUiDisabled()}catch(e){return null}}getAdPodInfo(){try{const e=this.currentAd();return e&&e.getAdPodInfo()}catch(e){return null}}canDismissNonLinear(){const e=this.currentAd();if(!e||e.isLinear()||!this._adsManager||!this._currentDisplayTs)return!0;const t=Date.now(),s=e.getMinSuggestedDuration();return t-this._currentDisplayTs>1e3*s}static unwrapError(e,t){if(!e)return"";if("function"==typeof e.getMessage){return e.getMessage()}return e.message?e.message:t||""}static pollForFatalError({err:e,ima:t}){let s;try{const t=e.getError(),i=t.getInnerError(),r=i?IMA.unwrapError(i,t.message):"";s={reason:r,type:t.getType(),code:t.getErrorCode()}}catch(e){}const i=t._currentRemaining;return new Promise((e,r)=>{const a=setTimeout(()=>{t.eventHandler&&t.eventHandler.trigger("ad-playback-error",s),r(new Error("Ad not progressing"))},2500);t.eventHandler.once("ad-progress",t=>{const s=t.detail.remaining;-1!==s&&s<i&&(clearTimeout(a),e({ok:1}))})})}static pollRemaining({ima:e,adsManager:t}){let s=-1;return B(e._timers,250,(function(){const i=t.getRemainingTime();-1!=e._currentRemaining&&e._currentRemaining<=i||(e._currentRemaining=t.getRemainingTime(),s!=e._currentRemaining&&(s=e._currentRemaining,e.eventHandler.trigger("ad-progress",{remaining:e._currentRemaining,duration:e._currentDuration})))}))}once(e,t,s){this._adHandlers.push(function(e,t,s){const i=r=>{s(r),e.removeEventListener(t,i)};return e.addEventListener(t,i),()=>e.removeEventListener(t,i)}(e,t,s))}static race(e,t,s){t.forEach(i=>{const r=(...i)=>{t.forEach(t=>e.removeListener(t,r)),s(i)};e.on(i,r)})}clearAdHandlers(){this.log("ima.clearAdHandlers"),this._adHandlers.forEach(e=>e()),this._adHandlers=[]}emitWithAd(e,t){if(this.log("ima.emitWithAd",e,t),!this._adsManager)return;const s=function(e){try{return e.getAdPodInfo().getAdPosition()}catch(e){return}}(t),i=function(e){try{return e.getAdPodInfo().getTotalAds()}catch(e){return}}(t),r={ad:{duration:t.getDuration(),width:t.getWidth(),height:t.getHeight(),position:s,totals:i},volume:this._adsManager.getVolume(),vast_ad_id:t.getAdId(),linear:t.isLinear(),mime_type:t.getContentType(),ima_event:!0};this.log(`emitWithAd::event(name: ${e}, data: %o, ad: %o)`,r,t),this.eventHandler.trigger(e,r)}emitError(e,t){const s={vast_error_type:t.getError().getType(),reason:t.getError().getMessage(),vast_error:t.getError().getErrorCode()};this.log(`ima.error(${e})`,s),this.eventHandler.trigger(e,s)}debugEvent(e){try{const t=e.getAd();if(!t)return;this.log(`ima.event.${e.type} ->`,{event:e,data:e.getAdData(),position:H(t),ad:t})}catch(e){}}}var z=function(e){var t={exports:{}};return e(t,t.exports),t.exports}((function(e,t){var s=function(){for(var e=new Array(256),t=0;t<256;++t)e[t]="%"+((t<16?"0":"")+t.toString(16)).toUpperCase();return e}(),i=Object.prototype.hasOwnProperty;t.arrayToObject=function(e,t){for(var s=t.plainObjects?Object.create(null):{},i=0;i<e.length;++i)void 0!==e[i]&&(s[i]=e[i]);return s},t.merge=function(e,s,r){if(!s)return e;if("object"!=typeof s){if(Array.isArray(e))e.push(s);else{if("object"!=typeof e)return[e,s];(r.plainObjects||r.allowPrototypes||!i.call(Object.prototype,s))&&(e[s]=!0)}return e}if("object"!=typeof e)return[e].concat(s);var a=e;return Array.isArray(e)&&!Array.isArray(s)&&(a=t.arrayToObject(e,r)),Object.keys(s).reduce((function(e,a){var n=s[a];return i.call(e,a)?e[a]=t.merge(e[a],n,r):e[a]=n,e}),a)},t.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},t.encode=function(e){if(0===e.length)return e;for(var t="string"==typeof e?e:String(e),i="",r=0;r<t.length;++r){var a=t.charCodeAt(r);45===a||46===a||95===a||126===a||a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122?i+=t.charAt(r):a<128?i+=s[a]:a<2048?i+=s[192|a>>6]+s[128|63&a]:a<55296||a>=57344?i+=s[224|a>>12]+s[128|a>>6&63]+s[128|63&a]:(r+=1,a=65536+((1023&a)<<10|1023&t.charCodeAt(r)),i+=s[240|a>>18]+s[128|a>>12&63]+s[128|a>>6&63]+s[128|63&a])}return i},t.compact=function(e,s){if("object"!=typeof e||null===e)return e;var i=s||[],r=i.indexOf(e);if(-1!==r)return i[r];if(i.push(e),Array.isArray(e)){for(var a=[],n=0;n<e.length;++n)e[n]&&"object"==typeof e[n]?a.push(t.compact(e[n],i)):void 0!==e[n]&&a.push(e[n]);return a}for(var o=Object.keys(e),d=0;d<o.length;++d){var l=o[d];e[l]=t.compact(e[l],i)}return e},t.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},t.isBuffer=function(e){return null!=e&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}})),G={brackets:function(e){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},W={delimiter:"&",strictNullHandling:!1,skipNulls:!1,encode:!0,encoder:z.encode},Q=function e(t,s,i,r,a,n,o,d,l){var c=t;if("function"==typeof o)c=o(s,c);else if(c instanceof Date)c=c.toISOString();else if(null===c){if(r)return n?n(s):s;c=""}if("string"==typeof c||"number"==typeof c||"boolean"==typeof c||z.isBuffer(c))return n?[n(s)+"="+n(c)]:[s+"="+String(c)];var u,h=[];if(void 0===c)return h;if(Array.isArray(o))u=o;else{var p=Object.keys(c);u=d?p.sort(d):p}for(var g=0;g<u.length;++g){var m=u[g];a&&null===c[m]||(h=Array.isArray(c)?h.concat(e(c[m],i(s,m),i,r,a,n,o,d,l)):h.concat(e(c[m],s+(l?"."+m:"["+m+"]"),i,r,a,n,o,d,l)))}return h},$=Object.prototype.hasOwnProperty,K={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3,strictNullHandling:!1,plainObjects:!1,allowPrototypes:!1,allowDots:!1,decoder:z.decode},Y=function(e,t,s){if(e){var i=s.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,r=/(\[[^[\]]*])/g,a=/(\[[^[\]]*])/.exec(i),n=a?i.slice(0,a.index):i,o=[];if(n){if(!s.plainObjects&&$.call(Object.prototype,n)&&!s.allowPrototypes)return;o.push(n)}for(var d=0;null!==(a=r.exec(i))&&d<s.depth;){if(d+=1,!s.plainObjects&&$.call(Object.prototype,a[1].slice(1,-1))&&!s.allowPrototypes)return;o.push(a[1])}return a&&o.push("["+i.slice(a.index)+"]"),function e(t,s,i){if(!t.length)return s;var r,a=t.shift();if("[]"===a)r=(r=[]).concat(e(t,s,i));else{r=i.plainObjects?Object.create(null):{};var n="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,o=parseInt(n,10);!isNaN(o)&&a!==n&&String(o)===n&&o>=0&&i.parseArrays&&o<=i.arrayLimit?(r=[])[o]=e(t,s,i):r[n]=e(t,s,i)}return r}(o,t,s)}},Z=function(e,t){var s,i,r=e,a=t||{},n=void 0===a.delimiter?W.delimiter:a.delimiter,o="boolean"==typeof a.strictNullHandling?a.strictNullHandling:W.strictNullHandling,d="boolean"==typeof a.skipNulls?a.skipNulls:W.skipNulls,l=("boolean"==typeof a.encode?a.encode:W.encode)?"function"==typeof a.encoder?a.encoder:W.encoder:null,c="function"==typeof a.sort?a.sort:null,u=void 0!==a.allowDots&&a.allowDots;if(null!==a.encoder&&void 0!==a.encoder&&"function"!=typeof a.encoder)throw new TypeError("Encoder has to be a function.");"function"==typeof a.filter?r=(i=a.filter)("",r):Array.isArray(a.filter)&&(s=i=a.filter);var h,p=[];if("object"!=typeof r||null===r)return"";h=a.arrayFormat in G?a.arrayFormat:"indices"in a?a.indices?"indices":"repeat":"indices";var g=G[h];s||(s=Object.keys(r)),c&&s.sort(c);for(var m=0;m<s.length;++m){var _=s[m];d&&null===r[_]||(p=p.concat(Q(r[_],_,g,o,d,l,i,c,u)))}return p.join(n)},J=function(e,t){var s=t||{};if(null!==s.decoder&&void 0!==s.decoder&&"function"!=typeof s.decoder)throw new TypeError("Decoder has to be a function.");if(s.delimiter="string"==typeof s.delimiter||z.isRegExp(s.delimiter)?s.delimiter:K.delimiter,s.depth="number"==typeof s.depth?s.depth:K.depth,s.arrayLimit="number"==typeof s.arrayLimit?s.arrayLimit:K.arrayLimit,s.parseArrays=!1!==s.parseArrays,s.decoder="function"==typeof s.decoder?s.decoder:K.decoder,s.allowDots="boolean"==typeof s.allowDots?s.allowDots:K.allowDots,s.plainObjects="boolean"==typeof s.plainObjects?s.plainObjects:K.plainObjects,s.allowPrototypes="boolean"==typeof s.allowPrototypes?s.allowPrototypes:K.allowPrototypes,s.parameterLimit="number"==typeof s.parameterLimit?s.parameterLimit:K.parameterLimit,s.strictNullHandling="boolean"==typeof s.strictNullHandling?s.strictNullHandling:K.strictNullHandling,""===e||null==e)return s.plainObjects?Object.create(null):{};for(var i="string"==typeof e?function(e,t){for(var s={},i=e.split(t.delimiter,t.parameterLimit===1/0?void 0:t.parameterLimit),r=0;r<i.length;++r){var a,n,o=i[r],d=-1===o.indexOf("]=")?o.indexOf("="):o.indexOf("]=")+1;-1===d?(a=t.decoder(o),n=t.strictNullHandling?null:""):(a=t.decoder(o.slice(0,d)),n=t.decoder(o.slice(d+1))),$.call(s,a)?s[a]=[].concat(s[a]).concat(n):s[a]=n}return s}(e,s):e,r=s.plainObjects?Object.create(null):{},a=Object.keys(i),n=0;n<a.length;++n){var o=a[n],d=Y(o,i[o],s);r=z.merge(r,d,s)}return z.compact(r)};const X=S("fpads:macros"),ee=/\[([\s\S]+?)\]/g;class Macros{static run(e){try{return e()}catch(e){return void console.error(e)}}static merge(...e){return e.reduce((e,t)=>Object.assign(e,t),{})}static cast(e){return void 0===e?"":"function"==typeof e?encodeURIComponent(Macros.run(e)||""):"string"==typeof e?encodeURIComponent(e):"number"==typeof e||"boolean"==typeof e?e.toString():""}static normalize(e){return e.trim()}static process_obj(e,t,s){return Object.keys(e).reduce((i,r)=>{const a=Macros.process_str(r,t,s,!0),n=e[r];return null===n?(i[a]=n,i):"object"==typeof n?(i[a]=Macros.process_obj(n,t,s),i):"string"==typeof n?(i[a]=Macros.process_str(n,t,s),i):(console.error(new Error(`${n} at ${r} not a handled Macro type`)),i)},{})}static process_str(e,t,s,i=!1){return e.replace(t.pattern,(e,t)=>{const r=Macros.normalize(t);if(!(r in s)||void 0===s[r])return e;const a=s[r],n=i?a:Macros.cast(a);return X("Macro.replace(raw: %s, macro: %s, value: %s)",i,t,n),n})}constructor(e={},t=ee){this.vars=e,this.pattern=t}fork(e={},t=this.pattern){const s=Macros.merge(this.vars,e);return new Macros(s,t)}compile(e,t={}){const s=Macros.merge(this.vars,t),[i,r]=e.split("?"),a=J(r||"",{strictNullHandling:!0,decoder:e=>e}),n=Z(Macros.process_obj(a,this,s),{encode:!1,strictNullHandling:!0});return Macros.process_str(i,this,s,!0)+"?"+n}}function te(e,t={width:0,height:0}){let s,i;try{const e=document.createElement("a");e.href=s=window.location!=window.parent.location?document.referrer:document.location.href,i=e.hostname}catch(e){console.error(e)}const{width:r,height:a}=t,{video_source:n}=e||{},o=function(){const e=window;return"object"==typeof e.__flowplayerAdParameters?e.__flowplayerAdParameters:{}}();return Object.assign({random:Date.now(),page_url:s,domain:i,player_width:r,player_height:a,video_url:n,videourl:n},o)}Macros.patterns={BRACKETS:ee,CURLY:/\{([\s\S]+?)\}/g,UNDERSCORE:/__([\s\S]+?)__/g};const se=/^flowplayer:\/\/(.+)/;async function ie(e){if("string"==typeof e&&se.test(e)){const t=se.exec(e),s=t&&window[t[1]];if(s)return ie(s)}if("function"!=typeof e)return e;try{return await e()}catch(e){return""}}class Schedule{constructor(e,t={}){this._ads=e,this._opts=t,this._nextIndex=0,this._postroll=void 0,this._loadPending=!1,this._postrollActive=!1,this.reset(this._ads)}toJSON(){const e=(this._ads||[]).slice(this._nextIndex);return this._postroll&&e.push(this._postroll),e}reset(e){this.setAds(e),this._nextIndex=0,this._postrollActive=!1}resetCounter(){this._nextIndex=0,this._postrollActive=!1}setAds(e){this._ads=e||[],this.sort()}getAds(){return this._ads}getNextAd(e){return this._ads[this._nextIndex]||e}getCurrentAd(){return this._postrollActive?this._postroll:this._loadPending?0:this._ads[this._nextIndex-1]}getPostroll(){return this._postroll}isDrained(){return this._nextIndex+1>this._ads.length}setPostrollActive(){this._postrollActive=!0}updateContentDuration(e){this._opts.content_duration=e}increment(){++this._nextIndex}decrement(){this._nextIndex>0&&--this._nextIndex}getNextIndex(){return this._nextIndex}getCurrentType(){const e=this.getCurrentAd();if(e)return Schedule.kindOf(e.time)}sort(){this._postroll=this._ads.find(e=>-1===e.time),this._ads=this._ads.filter(e=>e!==this._postroll).sort((e,t)=>e.time===t.time?this._ads.indexOf(e)-this._ads.indexOf(t):e.time-t.time)}shallPlayAd(e){if(this._loadPending)return!1;const t=this.getCurrentAd()||this.getNextAd();return!!(t&&t.time<=e&&-1!==t.time)}shallPlayNext(){const e=this.getNextAd(),t=this.getCurrentAd();return!(!e||!t||e.time!==t.time)}waitForLoad(e,t,s){if(this._loadPending=!1,!t)return!1;const i=s?this._opts.preload_advance:0;return t.time>=0?this._loadPending=e<t.time-i:-1===t.time&&(this._loadPending=this._opts.content_duration>0&&-1!==e?e<this._opts.content_duration-i:-1!==e),this._loadPending}static hasPreroll(e){return!!e.find(e=>0===e.time)}static isOutstream(e){return Schedule.hasPreroll(e)&&!!e[0].outstream}static kindOf(e){switch(e){case 0:return"preroll";case-1:return"postroll";default:return"midroll"}}}const re=Object.prototype,ae=Object.getPrototypeOf;const ne=S("fpads:ads:state");var oe;!function(e){e[e.IDLE=0]="IDLE",e[e.INITIALIZING=1]="INITIALIZING",e[e.FETCHING_AD=2]="FETCHING_AD",e[e.AD_AVAILABLE=4]="AD_AVAILABLE",e[e.BREAK_ACTIVE=8]="BREAK_ACTIVE",e[e.PLAYING=16]="PLAYING",e[e.FATAL_ERROR=32]="FATAL_ERROR"}(oe||(oe={}));class AdsState{static of(){return new AdsState}constructor(e=0){this._state=e}reset(){this._state=0}toggleState(e,t){return void 0===e&&ne(new Error("AdState cannot toggleState for `undefined`")),void 0===t?this._state^=e:t?void(this._state|=e):this._state&=~e}hasAll(e){return this._state==(this._state|e)}hasAny(e){return!!(this._state&e)}get state(){return this._state}}const de={ok:S("fpads:analytics:request-queue"),err:S("fpads:analytics:request-queue:err"),warn:S("fpads:analytics:request-queue:warn")};class RequestQueue{static of(){return new RequestQueue}static is_empty(e){return 0==e.pending.length}static is_high_water(e){return e.open.length==RequestQueue.MAX_OPEN_REQUESTS}static maybe_spawn_req(e){if(RequestQueue.is_empty(e))return de.ok("maybe_spawn_req called Queue that is EMPTY"),e;if(RequestQueue.is_high_water(e))return de.warn("maybe_spawn_req called on Queue that is HIGH_WATER"),e;try{const t=RequestQueue.lpop(e);t&&RequestQueue.request(e,t)}catch(e){de.err(e)}}static increment_failures(e){return e.stats.failures++,e.stats.failures>RequestQueue.MAX_FAILURE_COUNT&&(e.stats.ttl=Date.now()+RequestQueue.REQUEST_TTL_MS),e}static handle_error(e,t){RequestQueue.rm(e,t),RequestQueue.increment_failures(e)}static request(e,[t,s,i]){if(de.ok(`Request[${i.event_type}] request`,i,e.stats),Date.now()<e.stats.ttl)return de.warn(`Request[${i.event_type}] skipping because too many errors too quickly`,e.stats);const r=new XMLHttpRequest;e.open.push(r),r.timeout=RequestQueue.REQUEST_TIMEOUT_MS,r.ontimeout=function(){RequestQueue.handle_error(e,r),de.warn(`Request[${i.event_type}] timed out in ${r.timeout}ms`,e.stats)},r.onerror=function(t){RequestQueue.handle_error(e,r),t&&de.err(t),de.warn(`Request[${i.event_type}] encountered an Error`,r.responseText,e.stats)},r.onreadystatechange=function(){r.readyState==XMLHttpRequest.DONE&&RequestQueue.rm(e,r),Math.floor(r.status/100)},r.onload=function(){RequestQueue.rm(e,r),e.stats.failures&&e.stats.failures--,de.ok(`Request[${i.event_type}] :ok`,r.status)},r.open(s,t),r.setRequestHeader("Content-Type","text/plain;charset=UTF-8");try{r.send(JSON.stringify(i))}catch(e){de.err(e)}}static rpush(e,...t){return t.forEach(t=>{if(RequestQueue.is_high_water(e))return de.warn("Too many open requests, skipping",e.stats);e.pending.push(t),RequestQueue.maybe_spawn_req(e)}),e}static lpop(e){return e.pending.shift()}static rm(e,t){const s=e.open.lastIndexOf(t);return~s&&e.open.splice(s,1),e}constructor(e=[],t=[],s={failures:0,ttl:0}){this.pending=e,this.open=t,this.stats=s}}RequestQueue.MAX_OPEN_REQUESTS=3,RequestQueue.REQUEST_TIMEOUT_MS=4e3,RequestQueue.REQUEST_TTL_MS=5e3,RequestQueue.MAX_FAILURE_COUNT=3;const le={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},ce={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},ue={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},he={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},pe={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Utils{static getFirstMatch(e,t){const s=t.match(e);return s&&s.length>0&&s[1]||""}static getSecondMatch(e,t){const s=t.match(e);return s&&s.length>1&&s[2]||""}static matchAndReturnConst(e,t,s){if(e.test(t))return s}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map(e=>parseInt(e,10)||0);if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map(e=>parseInt(e,10)||0);if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,s=!1){const i=Utils.getVersionPrecision(e),r=U