From 556fcd15c212384dd4738156499927a2ff81e619 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zacharie=20Ta=C3=AFfour?= Date: Thu, 7 Nov 2024 16:41:02 +0100 Subject: [PATCH 1/5] Handle non supported vast error --- spec/samples/outdated-vast.xml | 18 +++++++++ spec/samples/wrapper-invalid-xmlfile.xml | 38 ------------------ spec/vast_parser.spec.js | 51 ++++++++++-------------- src/fetcher/url_handler.js | 5 +-- src/parser/vast_parser.js | 22 +++++++--- 5 files changed, 59 insertions(+), 75 deletions(-) create mode 100644 spec/samples/outdated-vast.xml delete mode 100644 spec/samples/wrapper-invalid-xmlfile.xml diff --git a/spec/samples/outdated-vast.xml b/spec/samples/outdated-vast.xml new file mode 100644 index 00000000..7560cf42 --- /dev/null +++ b/spec/samples/outdated-vast.xml @@ -0,0 +1,18 @@ + + + + example-1 + 123456 + + + + \ No newline at end of file diff --git a/spec/samples/wrapper-invalid-xmlfile.xml b/spec/samples/wrapper-invalid-xmlfile.xml deleted file mode 100644 index 625599f1..00000000 --- a/spec/samples/wrapper-invalid-xmlfile.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - VAST - invalid-xmlfile.xml - http://example.com/wrapper-invalid-xmlfile_wrapper-error - http://example.com/wrapper-invalid-xmlfile_impression - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spec/vast_parser.spec.js b/spec/vast_parser.spec.js index 98433aa2..25ebccd4 100644 --- a/spec/vast_parser.spec.js +++ b/spec/vast_parser.spec.js @@ -27,42 +27,18 @@ const nodeUrlHandler = { const wrapperAVastUrl = urlFor('wrapper-a.xml'); const wrapperBVastUrl = urlFor('wrapper-b.xml'); const inlineSampleVastUrl = urlFor('sample.xml'); -const inlineVpaidVastUrl = urlFor('vpaid.xml'); const inlineInvalidVastUrl = urlFor('invalid-xmlfile.xml'); -const wrapperWithAttributesVastUrl = urlFor( - 'wrapper-attributes-multiple-ads.xml' -); -const wrapperInvalidVastUrl = urlFor('wrapper-invalid-xmlfile.xml'); -const vastWithErrorUrl = urlFor('empty-no-ad.xml'); -const ad = { - id: null, - sequence: 1, - system: { value: 'VAST', version: null }, - title: null, - description: null, - advertiser: null, - pricing: null, - survey: null, - errorURLTemplates: ['http://example.com/wrapperA-error'], - impressionURLTemplates: [], - creatives: [], - extensions: [], - adVerifications: [], - trackingEvents: { nonlinear: [], linear: [] }, - videoClickTrackingURLTemplates: [], - videoCustomClickURLTemplates: [], - viewableImpression: [], -}; describe('VASTParser', () => { let vastClient; let VastParser; let fetcher; - let inlineXml, invalidXml, errorXml, wrapperXml; + let inlineXml, invalidXml, errorXml, wrapperXml, outdatedXml; beforeAll(async () => { inlineXml = await nodeUrlHandler.get('./spec/samples/sample.xml'); errorXml = await nodeUrlHandler.get('./spec/samples/empty-no-ad.xml'); + outdatedXml = await nodeUrlHandler.get('./spec/samples/outdated-vast.xml'); wrapperXml = await nodeUrlHandler.get( './spec/samples/wrapper-attributes-multiple-ads.xml' ); @@ -136,6 +112,23 @@ describe('VASTParser', () => { } }); + it('throw a error for non supported XML vast', () => { + try { + VastParser.parseVastXml(outdatedXml.xml, { + isRootVAST: true, + url: null, + wrapperDepth: 0, + }); + } catch (e) { + expect(e.message).toBe('VAST response version not supported'); + expect(VastParser.emit).toHaveBeenLastCalledWith('VAST-ad-parsed', { + type: 'ERROR', + url: null, + wrapperDepth: 0, + }); + } + }); + it('gets vast version from original vast', () => { VastParser.parseVastXml(inlineXml.xml, { isRootVAST: true, @@ -480,7 +473,7 @@ describe('VASTParser', () => { }); describe('Wrapper URL unavailable/timeout', () => { - it('sould emits a VAST-error and track', async () => { + it('should emits a VAST-error and track', async () => { const url = './spec/samples/wrapper-unavailable-url.xml'; const response = await nodeUrlHandler.get(url); @@ -488,12 +481,12 @@ describe('VASTParser', () => { fetcher.setOptions({ ...options, url: url, previousUrl: url }); VastParser.fetchingCallback = fetcher.fetchVAST.bind(fetcher); - const vastXML = await VastParser.parseVAST(response.xml, { + const vast = await VastParser.parseVAST(response.xml, { url: url, previousUrl: url, }); // Response doesn't have any ads - expect(vastXML.ads).toEqual([]); + expect(vast.ads).toEqual([]); // Error has been trigered expect(dataTriggered.length).toBe(1); expect(dataTriggered[0].ERRORCODE).toBe(301); diff --git a/src/fetcher/url_handler.js b/src/fetcher/url_handler.js index d6d7f350..3d88bc86 100644 --- a/src/fetcher/url_handler.js +++ b/src/fetcher/url_handler.js @@ -36,7 +36,7 @@ async function handleResponse(response) { */ function handleError(response) { if ( - window.location.protocol === 'https:' && + window?.location?.protocol === 'https:' && response.url.includes('http://') ) { return 'URLHandler: Cannot go from HTTPS to HTTP.'; @@ -66,8 +66,7 @@ async function get(url, options) { ...options, signal: controller.signal, credentials: options.withCredentials ? 'include' : 'omit', - }) - .finally(()=>{ + }).finally(() => { clearTimeout(timer); }); diff --git a/src/parser/vast_parser.js b/src/parser/vast_parser.js index 3c6d0919..e6e84e1a 100644 --- a/src/parser/vast_parser.js +++ b/src/parser/vast_parser.js @@ -10,7 +10,8 @@ const DEFAULT_EVENT_DATA = { ERRORCODE: 900, extensions: [], }; - +const INVALID_VAST_ERROR = 'Invalid VAST XMLDocument'; +const NON_SUPPORTED_VAST_VERSION = 'VAST response version not supported'; /** * This class provides methods to fetch and parse a VAST document. * @export @@ -25,7 +26,10 @@ export class VASTParser extends EventEmitter { constructor({ fetcher } = {}) { super(); this.maxWrapperDepth = null; + this.rootErrorURLTemplates = []; + this.errorURLTemplates = []; this.remainingAds = []; + this.parsingOptions = {}; this.fetcher = fetcher || null; } @@ -173,7 +177,12 @@ export class VASTParser extends EventEmitter { url, wrapperDepth, }); - throw new Error('Invalid VAST XMLDocument'); + // VideoAdServingTemplate node is used for VAST 1.0 + const isNonSupportedVast = + vastXml?.documentElement?.nodeName === 'VideoAdServingTemplate'; + throw new Error( + isNonSupportedVast ? NON_SUPPORTED_VAST_VERSION : INVALID_VAST_ERROR + ); } const ads = []; @@ -414,8 +423,8 @@ export class VASTParser extends EventEmitter { }) .catch((err) => { // Timeout of VAST URI provided in Wrapper element, or of VAST URI provided in a subsequent Wrapper element. - // (URI was either unavailable or reached a timeout as defined by the video player.) - ad.errorCode = 301; + // (URI was either unavailable or reached a timeout as defined by the video player) + ad.errorCode = err.message === NON_SUPPORTED_VAST_VERSION ? 102 : 301; ad.errorMessage = err.message; resolve(ad); }); @@ -440,7 +449,10 @@ export class VASTParser extends EventEmitter { // - No Creative case - The parser has dealt with soma or/and an elements // but no creative was found const ad = vastResponse.ads[index]; - if ((ad.errorCode || ad.creatives.length === 0) && !ad.VASTAdTagURI) { + const noMediaFilesAvailable = !ad.creatives.some( + (creative) => creative.mediaFiles?.length > 0 + ); + if ((ad.errorCode || noMediaFilesAvailable) && !ad.VASTAdTagURI) { // If VASTAdTagURI is in the vastResponse, it means we are dealing with a Wrapper when using parseVAST from the VASTParser. // In that case, we dont want to modify the vastResponse since the creatives node is not required in a wrapper. this.trackVastError( From 8f20421e5a234e6e9d4771bf57170f3b17fd9745 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zacharie=20Ta=C3=AFfour?= Date: Tue, 12 Nov 2024 11:05:27 +0100 Subject: [PATCH 2/5] [doc] update error documentation --- docs/api/1.x/parser.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/api/1.x/parser.md b/docs/api/1.x/parser.md index bc64784e..5cc4f536 100644 --- a/docs/api/1.x/parser.md +++ b/docs/api/1.x/parser.md @@ -7,6 +7,8 @@ Whenever an error occurs during the VAST parsing, the parser will call on his ow * VAST error `101`: VAST schema validation error. +* VAST error `102`: VAST version of response not supported. + * VAST error `301`: Timeout of VAST URI provided in Wrapper element. * VAST error `302`: Wrapper limit reached. From a1fd2a2145128d714ac31be427cc4e660f355dab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zacharie=20Ta=C3=AFfour?= Date: Tue, 26 Nov 2024 10:16:21 +0100 Subject: [PATCH 3/5] [doc] Fix documentation & add EOF --- docs/api/1.x/parser.md | 2 -- docs/api/vast-parser.md | 1 + spec/samples/outdated-vast.xml | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/api/1.x/parser.md b/docs/api/1.x/parser.md index 5cc4f536..bc64784e 100644 --- a/docs/api/1.x/parser.md +++ b/docs/api/1.x/parser.md @@ -7,8 +7,6 @@ Whenever an error occurs during the VAST parsing, the parser will call on his ow * VAST error `101`: VAST schema validation error. -* VAST error `102`: VAST version of response not supported. - * VAST error `301`: Timeout of VAST URI provided in Wrapper element. * VAST error `302`: Wrapper limit reached. diff --git a/docs/api/vast-parser.md b/docs/api/vast-parser.md index b25c96b1..5b35d15b 100644 --- a/docs/api/vast-parser.md +++ b/docs/api/vast-parser.md @@ -17,6 +17,7 @@ Whenever an error occurs during the VAST parsing, the parser will call automatic - `no_ad`: The VAST document is empty - VAST error `101`: VAST schema validation error. +- VAST error `102`: VAST version of response not supported. - VAST error `301`: Timeout of VAST URI provided in Wrapper element. - VAST error `302`: Wrapper limit reached. - VAST error `303`: No VAST response after one or more Wrappers. diff --git a/spec/samples/outdated-vast.xml b/spec/samples/outdated-vast.xml index 7560cf42..74a5e6bb 100644 --- a/spec/samples/outdated-vast.xml +++ b/spec/samples/outdated-vast.xml @@ -15,4 +15,4 @@ - \ No newline at end of file + From a482901f3263e7a4812d4cc73636f62502df4719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zacharie=20Ta=C3=AFfour?= Date: Tue, 26 Nov 2024 16:27:56 +0100 Subject: [PATCH 4/5] Bundle release 6.0.2 --- dist/vast-client-node.js | 27 ++++++++++++++++++++------- dist/vast-client-node.min.js | 2 +- dist/vast-client.js | 27 ++++++++++++++++++++------- dist/vast-client.min.js | 2 +- 4 files changed, 42 insertions(+), 16 deletions(-) diff --git a/dist/vast-client-node.js b/dist/vast-client-node.js index c132e5dc..5a4fbda7 100644 --- a/dist/vast-client-node.js +++ b/dist/vast-client-node.js @@ -2070,7 +2070,8 @@ const DEFAULT_EVENT_DATA = { ERRORCODE: 900, extensions: [] }; - +const INVALID_VAST_ERROR = 'Invalid VAST XMLDocument'; +const NON_SUPPORTED_VAST_VERSION = 'VAST response version not supported'; /** * This class provides methods to fetch and parse a VAST document. * @export @@ -2088,7 +2089,10 @@ class VASTParser extends EventEmitter { } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); this.maxWrapperDepth = null; + this.rootErrorURLTemplates = []; + this.errorURLTemplates = []; this.remainingAds = []; + this.parsingOptions = {}; this.fetcher = fetcher || null; } @@ -2220,12 +2224,15 @@ class VASTParser extends EventEmitter { } = _ref; // check if is a valid VAST document if (!vastXml || !vastXml.documentElement || vastXml.documentElement.nodeName !== 'VAST') { + var _vastXml$documentElem; this.emit('VAST-ad-parsed', { type: 'ERROR', url, wrapperDepth }); - throw new Error('Invalid VAST XMLDocument'); + // VideoAdServingTemplate node is used for VAST 1.0 + const isNonSupportedVast = (vastXml === null || vastXml === void 0 || (_vastXml$documentElem = vastXml.documentElement) === null || _vastXml$documentElem === void 0 ? void 0 : _vastXml$documentElem.nodeName) === 'VideoAdServingTemplate'; + throw new Error(isNonSupportedVast ? NON_SUPPORTED_VAST_VERSION : INVALID_VAST_ERROR); } const ads = []; const childNodes = vastXml.documentElement.childNodes; @@ -2442,8 +2449,8 @@ class VASTParser extends EventEmitter { }); }).catch(err => { // Timeout of VAST URI provided in Wrapper element, or of VAST URI provided in a subsequent Wrapper element. - // (URI was either unavailable or reached a timeout as defined by the video player.) - ad.errorCode = 301; + // (URI was either unavailable or reached a timeout as defined by the video player) + ad.errorCode = err.message === NON_SUPPORTED_VAST_VERSION ? 102 : 301; ad.errorMessage = err.message; resolve(ad); }); @@ -2470,7 +2477,11 @@ class VASTParser extends EventEmitter { // - No Creative case - The parser has dealt with soma or/and an elements // but no creative was found const ad = vastResponse.ads[index]; - if ((ad.errorCode || ad.creatives.length === 0) && !ad.VASTAdTagURI) { + const noMediaFilesAvailable = !ad.creatives.some(creative => { + var _creative$mediaFiles; + return ((_creative$mediaFiles = creative.mediaFiles) === null || _creative$mediaFiles === void 0 ? void 0 : _creative$mediaFiles.length) > 0; + }); + if ((ad.errorCode || noMediaFilesAvailable) && !ad.VASTAdTagURI) { // If VASTAdTagURI is in the vastResponse, it means we are dealing with a Wrapper when using parseVAST from the VASTParser. // In that case, we dont want to modify the vastResponse since the creatives node is not required in a wrapper. this.trackVastError(ad.errorURLTemplates.concat(vastResponse.errorURLTemplates), { @@ -2643,7 +2654,8 @@ async function handleResponse(response) { * @returns {String | null} */ function handleError(response) { - if (window.location.protocol === 'https:' && response.url.includes('http://')) { + var _window; + if (((_window = window) === null || _window === void 0 || (_window = _window.location) === null || _window === void 0 ? void 0 : _window.protocol) === 'https:' && response.url.includes('http://')) { return 'URLHandler: Cannot go from HTTPS to HTTP.'; } if (response.status !== 200 || !response.ok) { @@ -2664,8 +2676,9 @@ async function get(url, options) { ...options, signal: controller.signal, credentials: options.withCredentials ? 'include' : 'omit' + }).finally(() => { + clearTimeout(timer); }); - clearTimeout(timer); const error = handleError(response); if (error) { return { diff --git a/dist/vast-client-node.min.js b/dist/vast-client-node.min.js index 8dd03aee..4e14bb6b 100644 --- a/dist/vast-client-node.min.js +++ b/dist/vast-client-node.min.js @@ -1 +1 @@ -"use strict";function e(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}Object.defineProperty(exports,"__esModule",{value:!0});const t=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REGULATIONS","SERVERSIDE","SERVERUA","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"];function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=[],n=s(e);!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=u(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING;for(const e in t)t[e]=c(t[e]);for(const e in n){const r=n[e];"string"==typeof r&&a.push(i(r,t))}return a}function i(e,r){const i=(e=a(e,r)).match(/[^[\]]+(?=])/g);if(!i)return e;let s=i.filter((e=>t.indexOf(e)>-1));return 0===s.length?e:(s=s.reduce(((e,t)=>(e[t]=-1,e)),{}),a(e,s))}function a(e,t){let r=e;for(const e in t){const i=t[e];r=r.replace(new RegExp("(?:\\[|%%)(".concat(e,")(?:\\]|%%)"),"g"),i)}return r}function s(e){return Array.isArray(e)?e.map((e=>e&&e.hasOwnProperty("url")?e.url:e)):e}function n(e){return/^(https?:\/\/|\/\/)/.test(e)}function o(e,t){for(let r=0;r"%".concat(e.charCodeAt(0).toString(16))))}function u(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}const d={track:function(e,t,i){r(e,t,i).forEach((e=>{if("undefined"!=typeof window&&null!==window){(new Image).src=e}}))},resolveURLTemplates:r,extractURLsFromTemplates:s,filterUrlTemplates:function(e){return e.reduce(((e,t)=>{const r=t.url||t;return n(r)?e.validUrls.push(r):e.invalidUrls.push(r),e}),{validUrls:[],invalidUrls:[]})},containsTemplateObject:o,isTemplateObjectEqual:l,encodeURIComponentRFC3986:c,replaceUrlMacros:i,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce(((t,r)=>t.concat(Array.isArray(r)?e(r):r)),[])},joinArrayOfUniqueTemplateObjs:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];return r.concat(i).reduce(((e,t)=>(o(t,e)||e.push(t),e)),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:u,isValidUrl:n,isBrowserEnvironment:function(){return"undefined"!=typeof window},formatMacrosValues:function(e){return"object"!=typeof e?e:JSON.stringify(e)}};function h(e){return["true","TRUE","True","1"].includes(e)}function p(e){if(null==e)return-1;if(d.isNumeric(e))return parseInt(e);const t=e.split(":");if(3!==t.length)return-1;const r=t[2].split(".");let i=parseInt(r[0]);2===r.length&&(i+=parseFloat("0.".concat(r[1])));const a=parseInt(60*t[1]),s=parseInt(60*t[0]*60);return isNaN(s)||isNaN(a)||isNaN(i)||a>3600||i>60?-1:s+a+i}const m={childByName:function(e,t){return Array.from(e.childNodes).find((e=>e.nodeName===t))},childrenByName:function(e,t){return Array.from(e.childNodes).filter((e=>e.nodeName===t))},resolveVastAdTagURI:function(e,t){if(!t)return e;if(e.startsWith("//")){const{protocol:t}=location;return"".concat(t).concat(e)}if(!e.includes("://")){const r=t.slice(0,t.lastIndexOf("/"));return"".concat(r,"/").concat(e)}return e},parseBoolean:h,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){const i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){return Array.from(e.attributes).reduce(((e,t)=>(e[t.nodeName]=t.nodeValue,e)),{})},parseDuration:p,splitVAST:function(e){const t=[];let r=null;return e.forEach(((i,a)=>{if(i.sequence&&(i.sequence=parseInt(i.sequence,10)),i.sequence>1){const t=e[a-1];if(t&&t.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){e&&Array.from(e).forEach((e=>{let{nodeName:r,nodeValue:i}=e;if(r&&i&&t.hasOwnProperty(r)){let e=i;"boolean"==typeof t[r]&&(e=h(e)),t[r]=e}}))},mergeWrapperAdData:function(e,t){var r;e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[...e.viewableImpression,...t.viewableImpression]),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;const i=(t.creatives||[]).filter((e=>e&&"companion"===e.type)),a=i.reduce(((e,t)=>((t.variations||[]).forEach((t=>{(t.companionClickTrackingURLTemplates||[]).forEach((t=>{d.containsTemplateObject(t,e)||e.push(t)}))})),e)),[]);e.creatives=i.concat(e.creatives);const s=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,n=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;if(e.creatives.forEach((e=>{if(t.trackingEvents&&t.trackingEvents[e.type])for(const r in t.trackingEvents[e.type]){const i=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(i)}"linear"===e.type&&(s&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),n&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&a.length&&(e.variations||[]).forEach((e=>{e.companionClickTrackingURLTemplates=d.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,a)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories)),null!==(r=t.creatives)&&void 0!==r&&r.length){const r=t.creatives.filter((e=>{var t;return(null===(t=e.icons)||void 0===t?void 0:t.length)&&!e.mediaFiles.length}));r.length&&(e.creatives=e.creatives.concat(r))}}};function g(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"companion",required:null,variations:[]}}(r);return i.required=t.getAttribute("required")||null,i.variations=m.childrenByName(t,"Companion").map((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotId:e.adSlotId||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(m.parseAttributes(e));t.htmlResources=m.childrenByName(e,"HTMLResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=m.childrenByName(e,"IFrameResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=m.childrenByName(e,"StaticResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=m.parseNodeText(m.childByName(e,"AltText"))||null;const r=m.childByName(e,"TrackingEvents");r&&m.childrenByName(r,"Tracking").forEach((e=>{const r=e.getAttribute("event"),i=m.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=m.childrenByName(e,"CompanionClickTracking").map((e=>({id:e.getAttribute("id")||null,url:m.parseNodeText(e)}))),t.companionClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"CompanionClickThrough"))||null;const i=m.childByName(e,"AdParameters");return i&&(t.adParameters={value:m.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t})),i}function v(t,r){let i;const a=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(r);a.duration=m.parseDuration(m.parseNodeText(m.childByName(t,"Duration")));const s=t.getAttribute("skipoffset");if(null==s)a.skipDelay=null;else if("%"===s.charAt(s.length-1)&&-1!==a.duration){const e=parseInt(s,10);a.skipDelay=a.duration*(e/100)}else a.skipDelay=m.parseDuration(s);const n=m.childByName(t,"VideoClicks");if(n){const e=m.childByName(n,"ClickThrough");a.videoClickThroughURLTemplate=e?{id:e.getAttribute("id")||null,url:m.parseNodeText(e)}:null,m.childrenByName(n,"ClickTracking").forEach((e=>{a.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),m.childrenByName(n,"CustomClick").forEach((e=>{a.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}))}const o=m.childByName(t,"AdParameters");o&&(a.adParameters={value:m.parseNodeText(o),xmlEncoded:o.getAttribute("xmlEncoded")||null}),m.childrenByName(t,"TrackingEvents").forEach((e=>{m.childrenByName(e,"Tracking").forEach((e=>{let t=e.getAttribute("event");const r=m.parseNodeText(e);if(t&&r){if("progress"===t){if(i=e.getAttribute("offset"),!i)return;t="%"===i.charAt(i.length-1)?"progress-".concat(i):"progress-".concat(Math.round(m.parseDuration(i)))}Array.isArray(a.trackingEvents[t])||(a.trackingEvents[t]=[]),a.trackingEvents[t].push(r)}}))})),m.childrenByName(t,"MediaFiles").forEach((e=>{m.childrenByName(e,"MediaFile").forEach((e=>{a.mediaFiles.push(function(e){const t={id:null,fileURL:null,fileSize:0,deliveryType:"progressive",mimeType:null,mediaType:null,codec:null,bitrate:0,minBitrate:0,maxBitrate:0,width:0,height:0,apiFramework:null,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=m.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);const r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=m.parseBoolean(r));const i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=m.parseBoolean(i));return t}(e))}));const t=m.childByName(e,"InteractiveCreativeFile");t&&(a.interactiveCreativeFile=function(e){const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:m.parseBoolean(e.variableDuration),fileURL:null}}(m.parseAttributes(e));return t.fileURL=m.parseNodeText(e),t}(t));const r=m.childByName(e,"ClosedCaptionFiles");r&&m.childrenByName(r,"ClosedCaptionFile").forEach((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(m.parseAttributes(e));t.fileURL=m.parseNodeText(e),a.closedCaptionFiles.push(t)}));const i=m.childByName(e,"Mezzanine"),s=function(e,t){const r={};let i=!1;return t.forEach((t=>{e&&e.getAttribute(t)?r[t]=e.getAttribute(t):i=!0})),i?null:r}(i,["delivery","type","width","height"]);if(s){const e={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};e.id=i.getAttribute("id"),e.fileURL=m.parseNodeText(i),e.delivery=s.delivery,e.codec=i.getAttribute("codec"),e.type=s.type,e.width=parseInt(s.width,10),e.height=parseInt(s.height,10),e.fileSize=parseInt(i.getAttribute("fileSize"),10),e.mediaType=i.getAttribute("mediaType")||"2D",a.mezzanine=e}}));const l=m.childByName(t,"Icons");return l&&m.childrenByName(l,"Icon").forEach((e=>{a.icons.push(function(e){const t={program:null,height:0,width:0,xPosition:0,yPosition:0,apiFramework:null,offset:null,duration:0,type:null,staticResource:null,htmlResource:null,iframeResource:null,pxratio:"1",iconClickThroughURLTemplate:null,iconClickTrackingURLTemplates:[],iconViewTrackingURLTemplate:null,iconClickFallbackImages:[]};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=m.parseDuration(e.getAttribute("offset")),t.duration=m.parseDuration(e.getAttribute("duration")),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"IconClicks");if(r){t.iconClickThroughURLTemplate=m.parseNodeText(m.childByName(r,"IconClickThrough")),m.childrenByName(r,"IconClickTracking").forEach((e=>{t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}));const e=m.childByName(r,"IconClickFallbackImages");e&&m.childrenByName(e,"IconClickFallbackImage").forEach((e=>{t.iconClickFallbackImages.push({url:m.parseNodeText(e)||null,width:e.getAttribute("width")||null,height:e.getAttribute("height")||null})}))}return t.iconViewTrackingURLTemplate=m.parseNodeText(m.childByName(e,"IconViewTracking")),t}(e))})),a}function f(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"nonlinear",variations:[],trackingEvents:{}}}(r);return m.childrenByName(t,"TrackingEvents").forEach((e=>{let t,r;m.childrenByName(e,"Tracking").forEach((e=>{t=e.getAttribute("event"),r=m.parseNodeText(e),t&&r&&(Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(r))}))})),m.childrenByName(t,"NonLinear").forEach((e=>{const t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=m.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=m.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=m.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"AdParameters");r&&(t.adParameters={value:m.parseNodeText(r),xmlEncoded:r.getAttribute("xmlEncoded")||null}),t.nonlinearClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"NonLinearClickThrough")),m.childrenByName(e,"NonLinearClickTracking").forEach((e=>{t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),i.variations.push(t)})),i}function T(e){const t=[];return e.forEach((e=>{const r=A(e);r&&t.push(r)})),t}function A(e){if("#comment"===e.nodeName)return null;const t={name:null,value:null,attributes:{},children:[]},r=e.attributes,i=e.childNodes;if(t.name=e.nodeName,e.attributes)for(const e in r)if(r.hasOwnProperty(e)){const i=r[e];i.nodeName&&i.nodeValue&&(t.attributes[i.nodeName]=i.nodeValue)}for(const e in i)if(i.hasOwnProperty(e)){const r=A(i[e]);r&&t.children.push(r)}if(0===t.children.length||1===t.children.length&&["#cdata-section","#text"].indexOf(t.children[0].name)>=0){const r=m.parseNodeText(e);""!==r&&(t.value=r),t.children=[]}return null===(a=t).value&&0===Object.keys(a.attributes).length&&0===a.children.length?null:t;var a}function R(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}const y={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function k(e,t){if(!y[e.nodeName]||!y[e.nodeName].attributes)return;const r=y[e.nodeName].attributes.filter((t=>!e.getAttribute(t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}function E(e,t,r){const i=y[e.nodeName],a=!r&&"Wrapper"!==e.nodeName;if(!i||a)return;if(i.subElements){const r=i.subElements.filter((t=>!m.childByName(e,t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:r},t)}if(!r||!i.oneOfinLineResources)return;i.oneOfinLineResources.some((t=>m.childByName(e,t)))||N({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}function b(e){return e.children&&0!==e.children.length}function N(e,t){let{name:r,parentName:i,attributes:a,subElements:s,oneOfResources:n}=e,o="Element '".concat(r,"'");o+=a?" missing required attribute(s) '".concat(a.join(", "),"' "):s?" missing required sub element(s) '".concat(s.join(", "),"' "):n?" must provide one of the following '".concat(n.join(", "),"' "):" is empty",t("VAST-warning",{message:o,parentElement:i,specVersion:4.1})}const w={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),k(t,r),b(t)){E(t,r,i);for(let a=0;a2&&void 0!==arguments[2]?arguments[2]:{};const a=Array.from(e.childNodes).filter((e=>{const t=e.nodeName.toLowerCase();return"inline"===t||!1!==i&&"wrapper"===t}));for(const i of a){if(m.copyNodeAttribute("id",e,i),m.copyNodeAttribute("sequence",e,i),m.copyNodeAttribute("adType",e,i),"Wrapper"===i.nodeName)return{ad:I(i,t),type:"WRAPPER"};if("InLine"===i.nodeName)return{ad:L(i,t,{allowMultipleAds:r}),type:"INLINE"};const a=i.nodeName.toLowerCase();t("VAST-warning",{message:"<".concat(i.nodeName,"inline"===a?"> must be written ":"> must be written "),wrongNode:i})}}function L(e,t){let{allowMultipleAds:r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return!1===r&&e.getAttribute("sequence")?null:U(e,t)}function U(e,t){let r=[];t&&w.verifyRequiredValues(e,t);const i=Array.from(e.childNodes),a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(m.parseAttributes(e));return i.forEach((e=>{switch(e.nodeName){case"Error":a.errorURLTemplates.push(m.parseNodeText(e));break;case"Impression":a.impressionURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)});break;case"Creatives":a.creatives=function(e){const t=[];return e.forEach((e=>{const r={id:e.getAttribute("id")||null,adId:R(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},i=[];let a;m.childrenByName(e,"UniversalAdId").forEach((e=>{const t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:m.parseNodeText(e)};i.push(t)}));const s=m.childByName(e,"CreativeExtensions");s&&(a=T(m.childrenByName(s,"CreativeExtension")));for(const s in e.childNodes){const n=e.childNodes[s];let o;switch(n.nodeName){case"Linear":o=v(n,r);break;case"NonLinearAds":o=f(n,r);break;case"CompanionAds":o=g(n,r)}o&&(i&&(o.universalAdIds=i),a&&(o.creativeExtensions=a),t.push(o))}})),t}(m.childrenByName(e,"Creative"));break;case"Extensions":{const t=m.childrenByName(e,"Extension");a.extensions=T(t),a.adVerifications.length||(r=function(e){let t=null,r=[];e.some((e=>t=m.childByName(e,"AdVerifications"))),t&&(r=x(m.childrenByName(t,"Verification")));return r}(t));break}case"AdVerifications":a.adVerifications=x(m.childrenByName(e,"Verification"));break;case"AdSystem":a.system={value:m.parseNodeText(e),version:e.getAttribute("version")||null};break;case"AdTitle":a.title=m.parseNodeText(e);break;case"AdServingId":a.adServingId=m.parseNodeText(e);break;case"Category":a.categories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)});break;case"Expires":a.expires=parseInt(m.parseNodeText(e),10);break;case"ViewableImpression":a.viewableImpression.push(function(e){const t=(e,t)=>{const r=m.parseNodeText(t);return r&&e.push(r),e};return{id:e.getAttribute("id")||null,viewable:m.childrenByName(e,"Viewable").reduce(t,[]),notViewable:m.childrenByName(e,"NotViewable").reduce(t,[]),viewUndetermined:m.childrenByName(e,"ViewUndetermined").reduce(t,[])}}(e));break;case"Description":a.description=m.parseNodeText(e);break;case"Advertiser":a.advertiser={id:e.getAttribute("id")||null,value:m.parseNodeText(e)};break;case"Pricing":a.pricing={value:m.parseNodeText(e),model:e.getAttribute("model")||null,currency:e.getAttribute("currency")||null};break;case"Survey":a.survey={value:m.parseNodeText(e),type:e.getAttribute("type")||null};break;case"BlockedAdCategories":a.blockedAdCategories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)})}})),r.length&&(a.adVerifications=a.adVerifications.concat(r)),a}function I(e,t){const r=U(e,t),i=e.getAttribute("followAdditionalWrappers"),a=e.getAttribute("allowMultipleAds"),s=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||m.parseBoolean(i),r.allowMultipleAds=!!a&&m.parseBoolean(a),r.fallbackOnNoAd=s?m.parseBoolean(s):null;let n=m.childByName(e,"VASTAdTagURI");if(n?r.nextWrapperURL=m.parseNodeText(n):(n=m.childByName(e,"VASTAdTagURL"),n&&(r.nextWrapperURL=m.parseNodeText(m.childByName(n,"URL")))),r.creatives.forEach((e=>{if(["linear","nonlinear"].includes(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});for(const t in e.trackingEvents){const i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((i=>{r.trackingEvents[e.type][t].push(i)}))}}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((e=>{r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((e=>{r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function x(e){const t=[];return e.forEach((e=>{const r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=Array.from(e.childNodes);m.assignAttributes(e.attributes,r),i.forEach((e=>{let{nodeName:t,textContent:i,attributes:a}=e;switch(t){case"JavaScriptResource":case"ExecutableResource":r.resource=i.trim(),m.assignAttributes(a,r);break;case"VerificationParameters":r.parameters=i.trim()}}));const a=m.childByName(e,"TrackingEvents");a&&m.childrenByName(a,"Tracking").forEach((e=>{const t=e.getAttribute("event"),i=m.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}class S{constructor(){this._handlers=[]}on(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof t));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(typeof e));return this._handlers.push({event:e,handler:t}),this}once(e,t){return this.on(e,function(e,t,r){const i={fired:!1,wrapFn:void 0};function a(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e)(...arguments))}return i.wrapFn=a,a}(this,e,t))}off(e,t){return this._handlers=this._handlers.filter((r=>r.event!==e||r.handler!==t)),this}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i{"*"===t.event&&(a=!0,t.handler(e,...r)),t.event===e&&(a=!0,t.handler(...r))})),a}removeAllListeners(e){return e?(this._handlers=this._handlers.filter((t=>t.event!==e)),this):(this._handlers=[],this)}listenerCount(e){return this._handlers.filter((t=>t.event===e)).length}listeners(e){return this._handlers.reduce(((t,r)=>(r.event===e&&t.push(r.handler),t)),[])}eventNames(){return this._handlers.map((e=>e.event))}}let D=0,V=0;const O=(e,t)=>{if(!e||!t||e<=0||t<=0)return;V=(V*D+8*e/t)/++D},F={ERRORCODE:900,extensions:[]};class B extends S{constructor(){let{fetcher:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.maxWrapperDepth=null,this.remainingAds=[],this.fetcher=e||null}trackVastError(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a0&&void 0!==arguments[0]?arguments[0]:{};this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.rootURL="",this.resetParsingStatus(),O(e.byteLength,e.requestDuration)}resetParsingStatus(){this.errorURLTemplates=[],this.rootErrorURLTemplates=[],this.vastVersion=null}getRemainingAds(e){if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));const t=e?d.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.resolveAds(t,{wrapperDepth:0,url:this.rootURL}).then((e=>this.buildVASTResponse(e)))}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(t),t.isRootVAST=!0,this.parse(e,t).then((e=>this.buildVASTResponse(e)))}buildVASTResponse(e){const t=function(e){let{ads:t,errorURLTemplates:r,version:i}=e;return{ads:t||[],errorURLTemplates:r||[],version:i||null}}({ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion});return this.completeWrapperResolving(t),t}parseVastXml(e,t){let{isRootVAST:r=!1,url:i=null,wrapperDepth:a=0,allowMultipleAds:s,followAdditionalWrappers:n}=t;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:i,wrapperDepth:a}),new Error("Invalid VAST XMLDocument");const o=[],l=e.documentElement.childNodes,c=e.documentElement.getAttribute("version");r&&c&&(this.vastVersion=c);for(const e in l){const t=l[e];if("Error"===t.nodeName){const e=m.parseNodeText(t);r?this.rootErrorURLTemplates.push(e):this.errorURLTemplates.push(e)}else if("Ad"===t.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)s=!0;else if(!1===s&&o.length>1)break;const e=C(t,this.emit.bind(this),{allowMultipleAds:s,followAdditionalWrappers:n});e.ad?(o.push(e.ad),this.emit("VAST-ad-parsed",{type:e.type,url:i,wrapperDepth:a,adIndex:o.length-1,vastVersion:c})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return o}parse(e){let{url:t=null,resolveAll:r=!0,wrapperSequence:i=null,previousUrl:a=null,wrapperDepth:s=0,isRootVAST:n=!1,followAdditionalWrappers:o,allowMultipleAds:l}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},c=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&n&&(l=!0);try{c=this.parseVastXml(e,{isRootVAST:n,url:t,wrapperDepth:s,allowMultipleAds:l,followAdditionalWrappers:o})}catch(e){return Promise.reject(e)}return 1===c.length&&null!=i&&(c[0].sequence=i),!1===r&&(this.remainingAds=m.splitVAST(c),c=this.remainingAds.shift()),this.resolveAds(c,{wrapperDepth:s,previousUrl:a,url:t})}resolveAds(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],{wrapperDepth:t,previousUrl:r,url:i}=arguments.length>1?arguments[1]:void 0;const a=[];return r=i,e.forEach((e=>{const i=this.resolveWrappers(e,t,r);a.push(i)})),Promise.all(a).then((e=>d.flatten(e)))}resolveWrappers(e,t,r){const i={...e};return new Promise((e=>{var a;if(t++,!i.nextWrapperURL)return delete i.nextWrapperURL,e(i);if(!this.fetcher)return i.VASTAdTagURI=i.nextWrapperURL,delete i.nextWrapperURL,e(i);if(t>=this.maxWrapperDepth)return i.errorCode=302,delete i.nextWrapperURL,e(i);i.nextWrapperURL=m.resolveVastAdTagURI(i.nextWrapperURL,r);const s=null!==(a=this.parsingOptions.allowMultipleAds)&&void 0!==a?a:i.allowMultipleAds,n=i.sequence;this.fetcher.fetchVAST({url:i.nextWrapperURL,emitter:this.emit.bind(this),maxWrapperDepth:this.maxWrapperDepth}).then((a=>this.parse(a,{url:i.nextWrapperURL,previousUrl:r,wrapperSequence:n,wrapperDepth:t,followAdditionalWrappers:i.followAdditionalWrappers,allowMultipleAds:s}).then((t=>{if(delete i.nextWrapperURL,0===t.length)return i.creatives=[],e(i);t.forEach((e=>{e&&m.mergeWrapperAdData(e,i)})),e(t)})))).catch((t=>{i.errorCode=301,i.errorMessage=t.message,e(i)}))}))}completeWrapperResolving(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(let t=e.ads.length-1;t>=0;t--){const r=e.ads[t];!r.errorCode&&0!==r.creatives.length||r.VASTAdTagURI||(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}let P=null;const M={data:{},length:0,getItem(e){return this.data[e]},setItem(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem(e){delete this.data[e],this.length=Object.keys(this.data).length},clear(){this.data={},this.length=0}};class W{constructor(){this.storage=this.initStorage()}initStorage(){if(P)return P;try{P="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){P=null}return P&&!this.isStorageDisabled(P)||(P=M,P.clear()),P}isStorageDisabled(e){const t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}getItem(e){return this.storage.getItem(e)}setItem(e,t){return this.storage.setItem(e,t)}removeItem(e){return this.storage.removeItem(e)}clear(){return this.storage.clear()}}const j=12e4;const q={get:async function(e,t){try{const r=new AbortController,i=setTimeout((()=>{throw r.abort(),new Error("URLHandler: Request timed out after ".concat(t.timeout||j," ms (408)"))}),t.timeout||j),a=await fetch(e,{...t,signal:r.signal,credentials:t.withCredentials?"include":"omit"});clearTimeout(i);const s=function(e){return"https:"===window.location.protocol&&e.url.includes("http://")?"URLHandler: Cannot go from HTTPS to HTTP.":200===e.status&&e.ok?null:"URLHandler: ".concat(e.statusText," (").concat(e.status,")")}(a);return s?{error:new Error(s),statusCode:a.status}:async function(e){const t=await e.text();let r;r=d.isBrowserEnvironment()?new DOMParser:new((await Promise.resolve().then((function(){return require("./chunks/xmldom-623c1b6b.min.js")}))).DOMParser);return{xml:r.parseFromString(t,"text/xml"),details:{byteLength:t.length,statusCode:e.status,rawXml:t}}}(a)}catch(e){return{error:e,statusCode:"AbortError"===e.name?408:null}}}};class K{constructor(){this.URLTemplateFilters=[]}setOptions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.urlHandler=e.urlHandler||e.urlhandler||q,this.fetchingOptions={timeout:e.timeout||j,withCredentials:Boolean(e.withCredentials)}}addURLTemplateFilter(e){"function"==typeof e&&this.URLTemplateFilters.push(e)}removeLastURLTemplateFilter(){this.URLTemplateFilters.pop()}countURLTemplateFilters(){return this.URLTemplateFilters.length}clearURLTemplateFilters(){this.URLTemplateFilters=[]}async fetchVAST(e){var t;let{url:r,maxWrapperDepth:i,emitter:a,wrapperDepth:s=0,previousUrl:n=null,wrapperAd:o=null}=e;const l=Date.now();this.URLTemplateFilters.forEach((e=>{r=e(r)})),a("VAST-resolving",{url:r,previousUrl:n,wrapperDepth:s,maxWrapperDepth:i,timeout:this.fetchingOptions.timeout,wrapperAd:o});const c=await this.urlHandler.get(r,this.fetchingOptions),u=Math.round(Date.now()-l);if(a("VAST-resolved",{url:r,previousUrl:n,wrapperDepth:s,error:(null==c?void 0:c.error)||null,duration:u,statusCode:(null==c?void 0:c.statusCode)||null,...null==c?void 0:c.details}),O(null==c||null===(t=c.details)||void 0===t?void 0:t.byteLength,u),c.error)throw new Error(c.error);return c.xml}}exports.VASTClient=class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new W;this.cappingFreeLunch=e,this.cappingMinimumTimeInterval=t,this.fetcher=new K,this.vastParser=new B({fetcher:this.fetcher}),this.storage=r,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}addURLTemplateFilter(e){this.fetcher.addURLTemplateFilter(e)}removeLastURLTemplateFilter(){this.fetcher.removeLastURLTemplateFilter()}countURLTemplateFilters(){return this.fetcher.countURLTemplateFilters()}clearURLTemplateFilters(){this.fetcher.clearURLTemplateFilters()}getParser(){return this.vastParser}get lastSuccessfulAd(){return this.storage.getItem("vast-client-last-successful-ad")}set lastSuccessfulAd(e){this.storage.setItem("vast-client-last-successful-ad",e)}get totalCalls(){return this.storage.getItem("vast-client-total-calls")}set totalCalls(e){this.storage.setItem("vast-client-total-calls",e)}get totalCallsTimeout(){return this.storage.getItem("vast-client-total-calls-timeout")}set totalCallsTimeout(e){this.storage.setItem("vast-client-total-calls-timeout",e)}hasRemainingAds(){return this.vastParser.remainingAds.length>0}getNextAds(e){return this.vastParser.getRemainingAds(e)}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.fetcher.setOptions(t),this.vastParser.parseVAST(e,t)}get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=Date.now();return t.hasOwnProperty("resolveAll")||(t.resolveAll=!1),this.totalCallsTimeout{if(this.cappingFreeLunch>=this.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(this.totalCalls,"/").concat(this.cappingFreeLunch)));const s=r-this.lastSuccessfulAd;if(s<0)this.lastSuccessfulAd=0;else if(s(t.previousUrl=e,t.isRootVAST=!0,t.url=e,this.vastParser.parse(r,t).then((e=>{const t=this.vastParser.buildVASTResponse(e);i(t)}))))).catch((e=>a(e)))}))}},exports.VASTParser=B,exports.VASTTracker=class extends S{constructor(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),this.ad=t,this.creative=r,this.variation=i,this.muted=a,this.impressed=!1,this.skippable=!1,this.trackingEvents={},this.lastPercentage=0,this._alreadyTriggeredQuartiles={},this.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"];for(const e in this.creative.trackingEvents){const t=this.creative.trackingEvents[e];this.trackingEvents[e]=t.slice(0)}!function(e){return"linear"===e.type}(this.creative)?this._initVariationTracking():this._initLinearTracking(),e&&this.on("start",(()=>{e.lastSuccessfulAd=Date.now()}))}_initLinearTracking(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}_initVariationTracking(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(const e in this.variation.trackingEvents){const t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}setDuration(e){d.isValidTimeValue(e)?(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100}):this.emit("TRACKER-error",{message:"the duration provided is not valid. duration: ".concat(e)})}setProgress(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!d.isValidTimeValue(e)||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given setProgress parameter has the wrong type. progress: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});const i=this.skipDelay||-1;if(-1===i||this.skippable||(i>e?this.emit("skip-countdown",i-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){const i=Math.round(e/this.assetDuration*100),a=[];if(e>0){a.push("start");for(let e=this.lastPercentage;e{this.track(e,{macros:t,once:r})})),e1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e):this.emit("TRACKER-error",{message:"One given setMuted parameter has the wrong type. muted: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setPaused(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e):this.emit("TRACKER-error",{message:"One given setPaused parameter has the wrong type. paused: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setFullscreen(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e):this.emit("TRACKER-error",{message:"One given setFullScreen parameter has the wrong type. fullscreen: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setExpand(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e):this.emit("TRACKER-error",{message:"One given setExpand parameter has the wrong type. expanded: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setSkipDelay(e){d.isValidTimeValue(e)?this.skipDelay=e:this.emit("TRACKER-error",{message:"setSkipDelay parameter does not have a valid value. duration: ".concat(e)})}trackImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})):this.emit("TRACKER-error",{message:"trackImpression parameter has the wrong type. macros: ".concat(e)})}trackViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewable,e)})):this.emit("TRACKER-error",{message:"trackViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackNotViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.notViewable,e)})):this.emit("TRACKER-error",{message:"trackNotViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackUndeterminedImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewUndetermined,e)})):this.emit("TRACKER-error",{message:"trackUndeterminedImpression given macros has the wrong type. macros: ".concat(e)})}error(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"==typeof e&&"boolean"==typeof t?this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t}):this.emit("TRACKER-error",{message:"One given error parameter has the wrong type. macros: ".concat(d.formatMacrosValues(e),", isCustomCode: ").concat(t)})}errorWithCode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t?(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead")):this.emit("TRACKER-error",{message:"One given errorWithCode parameter has the wrong type. errorCode: ".concat(e,", isCustomCode: ").concat(t)})}complete(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("complete",{macros:e}):this.emit("TRACKER-error",{message:"complete given macros has the wrong type. macros: ".concat(e)})}notUsed(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?(this.track("notUsed",{macros:e}),this.trackingEvents=[]):this.emit("TRACKER-error",{message:"notUsed given macros has the wrong type. macros: ".concat(e)})}otherAdInteraction(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("otherAdInteraction",{macros:e}):this.emit("TRACKER-error",{message:"otherAdInteraction given macros has the wrong type. macros: ".concat(e)})}acceptInvitation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("acceptInvitation",{macros:e}):this.emit("TRACKER-error",{message:"acceptInvitation given macros has the wrong type. macros: ".concat(e)})}adExpand(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adExpand",{macros:e}):this.emit("TRACKER-error",{message:"adExpand given macros has the wrong type. macros: ".concat(e)})}adCollapse(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adCollapse",{macros:e}):this.emit("TRACKER-error",{message:"adCollapse given macros has the wrong type. macros: ".concat(e)})}minimize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("minimize",{macros:e}):this.emit("TRACKER-error",{message:"minimize given macros has the wrong type. macros: ".concat(e)})}verificationNotExecuted(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given verificationNotExecuted parameter has to wrong type. vendor: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");const r=this.ad.adVerifications.find((t=>t.vendor===e));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));const i=r.trackingEvents;if(i&&i.verificationNotExecuted){const e=i.verificationNotExecuted;this.trackURLs(e,t),this.emit("verificationNotExecuted",{trackingURLTemplates:e})}}overlayViewDuration(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"==typeof t?(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t})):this.emit("TRACKER-error",{message:"One given overlayViewDuration parameters has the wrong type. formattedDuration: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}close(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track(this.linear?"closeLinear":"close",{macros:e}):this.emit("TRACKER-error",{message:"close given macros has the wrong type. macros: ".concat(e)})}skip(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("skip",{macros:e}):this.emit("TRACKER-error",{message:"skip given macros has the wrong type. macros: ".concat(e)})}load(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("loaded",{macros:e}):this.emit("TRACKER-error",{message:"load given macros has the wrong type. macros: ".concat(e)})}click(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!==e&&"string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given click parameter has the wrong type. fallbackClickThroughURL: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);const r=this.clickThroughURLTemplate||e,i={...t};if(r){this.progress&&(i.ADPLAYHEAD=this.progressFormatted());const e=d.resolveURLTemplates([r],i)[0];this.emit("clickthrough",e)}}track(e){let{macros:t={},once:r=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"!=typeof t)return void this.emit("TRACKER-error",{message:"track given macros has the wrong type. macros: ".concat(t)});"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");const i=this.trackingEvents[e],a=this.emitAlwaysEvents.indexOf(e)>-1;i?(this.emit(e,{trackingURLTemplates:i}),this.trackURLs(i,t)):a&&this.emit(e,null),r&&(delete this.trackingEvents[e],a&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}trackURLs(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{validUrls:a,invalidUrls:s}=d.filterUrlTemplates(e);s.length&&this.emit("TRACKER-error",{message:"Provided urls are malformed. url: ".concat(s)});const n={...r};this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(n.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(n.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(t=t.universalAdIds)&&void 0!==t&&t.length&&(n.UNIVERSALADID=this.creative.universalAdIds.map((e=>e.idRegistry.concat(" ",e.value))).join(",")),this.ad&&(this.ad.sequence&&(n.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(n.ADTYPE=this.ad.adType),this.ad.adServingId&&(n.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(n.ADCATEGORIES=this.ad.categories.map((e=>e.value)).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(n.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories.map((e=>e.value)).join(","))),d.track(a,n,i)}convertToTimecode(e){if(!d.isValidTimeValue(e))return"";const t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),a=Math.floor(t/1e3%60),s=Math.floor(t%1e3);return"".concat(d.addLeadingZeros(r,2),":").concat(d.addLeadingZeros(i,2),":").concat(d.addLeadingZeros(a,2),".").concat(d.addLeadingZeros(s,3))}progressFormatted(){return this.convertToTimecode(this.progress)}},exports.parseDuration=p; +"use strict";function e(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}Object.defineProperty(exports,"__esModule",{value:!0});const t=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REGULATIONS","SERVERSIDE","SERVERUA","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"];function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=[],n=s(e);!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=u(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING;for(const e in t)t[e]=c(t[e]);for(const e in n){const r=n[e];"string"==typeof r&&a.push(i(r,t))}return a}function i(e,r){const i=(e=a(e,r)).match(/[^[\]]+(?=])/g);if(!i)return e;let s=i.filter((e=>t.indexOf(e)>-1));return 0===s.length?e:(s=s.reduce(((e,t)=>(e[t]=-1,e)),{}),a(e,s))}function a(e,t){let r=e;for(const e in t){const i=t[e];r=r.replace(new RegExp("(?:\\[|%%)(".concat(e,")(?:\\]|%%)"),"g"),i)}return r}function s(e){return Array.isArray(e)?e.map((e=>e&&e.hasOwnProperty("url")?e.url:e)):e}function n(e){return/^(https?:\/\/|\/\/)/.test(e)}function o(e,t){for(let r=0;r"%".concat(e.charCodeAt(0).toString(16))))}function u(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}const d={track:function(e,t,i){r(e,t,i).forEach((e=>{if("undefined"!=typeof window&&null!==window){(new Image).src=e}}))},resolveURLTemplates:r,extractURLsFromTemplates:s,filterUrlTemplates:function(e){return e.reduce(((e,t)=>{const r=t.url||t;return n(r)?e.validUrls.push(r):e.invalidUrls.push(r),e}),{validUrls:[],invalidUrls:[]})},containsTemplateObject:o,isTemplateObjectEqual:l,encodeURIComponentRFC3986:c,replaceUrlMacros:i,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce(((t,r)=>t.concat(Array.isArray(r)?e(r):r)),[])},joinArrayOfUniqueTemplateObjs:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];return r.concat(i).reduce(((e,t)=>(o(t,e)||e.push(t),e)),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:u,isValidUrl:n,isBrowserEnvironment:function(){return"undefined"!=typeof window},formatMacrosValues:function(e){return"object"!=typeof e?e:JSON.stringify(e)}};function h(e){return["true","TRUE","True","1"].includes(e)}function p(e){if(null==e)return-1;if(d.isNumeric(e))return parseInt(e);const t=e.split(":");if(3!==t.length)return-1;const r=t[2].split(".");let i=parseInt(r[0]);2===r.length&&(i+=parseFloat("0.".concat(r[1])));const a=parseInt(60*t[1]),s=parseInt(60*t[0]*60);return isNaN(s)||isNaN(a)||isNaN(i)||a>3600||i>60?-1:s+a+i}const m={childByName:function(e,t){return Array.from(e.childNodes).find((e=>e.nodeName===t))},childrenByName:function(e,t){return Array.from(e.childNodes).filter((e=>e.nodeName===t))},resolveVastAdTagURI:function(e,t){if(!t)return e;if(e.startsWith("//")){const{protocol:t}=location;return"".concat(t).concat(e)}if(!e.includes("://")){const r=t.slice(0,t.lastIndexOf("/"));return"".concat(r,"/").concat(e)}return e},parseBoolean:h,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){const i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){return Array.from(e.attributes).reduce(((e,t)=>(e[t.nodeName]=t.nodeValue,e)),{})},parseDuration:p,splitVAST:function(e){const t=[];let r=null;return e.forEach(((i,a)=>{if(i.sequence&&(i.sequence=parseInt(i.sequence,10)),i.sequence>1){const t=e[a-1];if(t&&t.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){e&&Array.from(e).forEach((e=>{let{nodeName:r,nodeValue:i}=e;if(r&&i&&t.hasOwnProperty(r)){let e=i;"boolean"==typeof t[r]&&(e=h(e)),t[r]=e}}))},mergeWrapperAdData:function(e,t){var r;e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[...e.viewableImpression,...t.viewableImpression]),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;const i=(t.creatives||[]).filter((e=>e&&"companion"===e.type)),a=i.reduce(((e,t)=>((t.variations||[]).forEach((t=>{(t.companionClickTrackingURLTemplates||[]).forEach((t=>{d.containsTemplateObject(t,e)||e.push(t)}))})),e)),[]);e.creatives=i.concat(e.creatives);const s=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,n=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;if(e.creatives.forEach((e=>{if(t.trackingEvents&&t.trackingEvents[e.type])for(const r in t.trackingEvents[e.type]){const i=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(i)}"linear"===e.type&&(s&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),n&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&a.length&&(e.variations||[]).forEach((e=>{e.companionClickTrackingURLTemplates=d.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,a)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories)),null!==(r=t.creatives)&&void 0!==r&&r.length){const r=t.creatives.filter((e=>{var t;return(null===(t=e.icons)||void 0===t?void 0:t.length)&&!e.mediaFiles.length}));r.length&&(e.creatives=e.creatives.concat(r))}}};function g(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"companion",required:null,variations:[]}}(r);return i.required=t.getAttribute("required")||null,i.variations=m.childrenByName(t,"Companion").map((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotId:e.adSlotId||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(m.parseAttributes(e));t.htmlResources=m.childrenByName(e,"HTMLResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=m.childrenByName(e,"IFrameResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=m.childrenByName(e,"StaticResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=m.parseNodeText(m.childByName(e,"AltText"))||null;const r=m.childByName(e,"TrackingEvents");r&&m.childrenByName(r,"Tracking").forEach((e=>{const r=e.getAttribute("event"),i=m.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=m.childrenByName(e,"CompanionClickTracking").map((e=>({id:e.getAttribute("id")||null,url:m.parseNodeText(e)}))),t.companionClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"CompanionClickThrough"))||null;const i=m.childByName(e,"AdParameters");return i&&(t.adParameters={value:m.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t})),i}function v(t,r){let i;const a=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(r);a.duration=m.parseDuration(m.parseNodeText(m.childByName(t,"Duration")));const s=t.getAttribute("skipoffset");if(null==s)a.skipDelay=null;else if("%"===s.charAt(s.length-1)&&-1!==a.duration){const e=parseInt(s,10);a.skipDelay=a.duration*(e/100)}else a.skipDelay=m.parseDuration(s);const n=m.childByName(t,"VideoClicks");if(n){const e=m.childByName(n,"ClickThrough");a.videoClickThroughURLTemplate=e?{id:e.getAttribute("id")||null,url:m.parseNodeText(e)}:null,m.childrenByName(n,"ClickTracking").forEach((e=>{a.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),m.childrenByName(n,"CustomClick").forEach((e=>{a.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}))}const o=m.childByName(t,"AdParameters");o&&(a.adParameters={value:m.parseNodeText(o),xmlEncoded:o.getAttribute("xmlEncoded")||null}),m.childrenByName(t,"TrackingEvents").forEach((e=>{m.childrenByName(e,"Tracking").forEach((e=>{let t=e.getAttribute("event");const r=m.parseNodeText(e);if(t&&r){if("progress"===t){if(i=e.getAttribute("offset"),!i)return;t="%"===i.charAt(i.length-1)?"progress-".concat(i):"progress-".concat(Math.round(m.parseDuration(i)))}Array.isArray(a.trackingEvents[t])||(a.trackingEvents[t]=[]),a.trackingEvents[t].push(r)}}))})),m.childrenByName(t,"MediaFiles").forEach((e=>{m.childrenByName(e,"MediaFile").forEach((e=>{a.mediaFiles.push(function(e){const t={id:null,fileURL:null,fileSize:0,deliveryType:"progressive",mimeType:null,mediaType:null,codec:null,bitrate:0,minBitrate:0,maxBitrate:0,width:0,height:0,apiFramework:null,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=m.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);const r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=m.parseBoolean(r));const i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=m.parseBoolean(i));return t}(e))}));const t=m.childByName(e,"InteractiveCreativeFile");t&&(a.interactiveCreativeFile=function(e){const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:m.parseBoolean(e.variableDuration),fileURL:null}}(m.parseAttributes(e));return t.fileURL=m.parseNodeText(e),t}(t));const r=m.childByName(e,"ClosedCaptionFiles");r&&m.childrenByName(r,"ClosedCaptionFile").forEach((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(m.parseAttributes(e));t.fileURL=m.parseNodeText(e),a.closedCaptionFiles.push(t)}));const i=m.childByName(e,"Mezzanine"),s=function(e,t){const r={};let i=!1;return t.forEach((t=>{e&&e.getAttribute(t)?r[t]=e.getAttribute(t):i=!0})),i?null:r}(i,["delivery","type","width","height"]);if(s){const e={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};e.id=i.getAttribute("id"),e.fileURL=m.parseNodeText(i),e.delivery=s.delivery,e.codec=i.getAttribute("codec"),e.type=s.type,e.width=parseInt(s.width,10),e.height=parseInt(s.height,10),e.fileSize=parseInt(i.getAttribute("fileSize"),10),e.mediaType=i.getAttribute("mediaType")||"2D",a.mezzanine=e}}));const l=m.childByName(t,"Icons");return l&&m.childrenByName(l,"Icon").forEach((e=>{a.icons.push(function(e){const t={program:null,height:0,width:0,xPosition:0,yPosition:0,apiFramework:null,offset:null,duration:0,type:null,staticResource:null,htmlResource:null,iframeResource:null,pxratio:"1",iconClickThroughURLTemplate:null,iconClickTrackingURLTemplates:[],iconViewTrackingURLTemplate:null,iconClickFallbackImages:[]};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=m.parseDuration(e.getAttribute("offset")),t.duration=m.parseDuration(e.getAttribute("duration")),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"IconClicks");if(r){t.iconClickThroughURLTemplate=m.parseNodeText(m.childByName(r,"IconClickThrough")),m.childrenByName(r,"IconClickTracking").forEach((e=>{t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}));const e=m.childByName(r,"IconClickFallbackImages");e&&m.childrenByName(e,"IconClickFallbackImage").forEach((e=>{t.iconClickFallbackImages.push({url:m.parseNodeText(e)||null,width:e.getAttribute("width")||null,height:e.getAttribute("height")||null})}))}return t.iconViewTrackingURLTemplate=m.parseNodeText(m.childByName(e,"IconViewTracking")),t}(e))})),a}function f(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"nonlinear",variations:[],trackingEvents:{}}}(r);return m.childrenByName(t,"TrackingEvents").forEach((e=>{let t,r;m.childrenByName(e,"Tracking").forEach((e=>{t=e.getAttribute("event"),r=m.parseNodeText(e),t&&r&&(Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(r))}))})),m.childrenByName(t,"NonLinear").forEach((e=>{const t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=m.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=m.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=m.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"AdParameters");r&&(t.adParameters={value:m.parseNodeText(r),xmlEncoded:r.getAttribute("xmlEncoded")||null}),t.nonlinearClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"NonLinearClickThrough")),m.childrenByName(e,"NonLinearClickTracking").forEach((e=>{t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),i.variations.push(t)})),i}function T(e){const t=[];return e.forEach((e=>{const r=A(e);r&&t.push(r)})),t}function A(e){if("#comment"===e.nodeName)return null;const t={name:null,value:null,attributes:{},children:[]},r=e.attributes,i=e.childNodes;if(t.name=e.nodeName,e.attributes)for(const e in r)if(r.hasOwnProperty(e)){const i=r[e];i.nodeName&&i.nodeValue&&(t.attributes[i.nodeName]=i.nodeValue)}for(const e in i)if(i.hasOwnProperty(e)){const r=A(i[e]);r&&t.children.push(r)}if(0===t.children.length||1===t.children.length&&["#cdata-section","#text"].indexOf(t.children[0].name)>=0){const r=m.parseNodeText(e);""!==r&&(t.value=r),t.children=[]}return null===(a=t).value&&0===Object.keys(a.attributes).length&&0===a.children.length?null:t;var a}function R(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}const y={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function k(e,t){if(!y[e.nodeName]||!y[e.nodeName].attributes)return;const r=y[e.nodeName].attributes.filter((t=>!e.getAttribute(t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}function E(e,t,r){const i=y[e.nodeName],a=!r&&"Wrapper"!==e.nodeName;if(!i||a)return;if(i.subElements){const r=i.subElements.filter((t=>!m.childByName(e,t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:r},t)}if(!r||!i.oneOfinLineResources)return;i.oneOfinLineResources.some((t=>m.childByName(e,t)))||N({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}function b(e){return e.children&&0!==e.children.length}function N(e,t){let{name:r,parentName:i,attributes:a,subElements:s,oneOfResources:n}=e,o="Element '".concat(r,"'");o+=a?" missing required attribute(s) '".concat(a.join(", "),"' "):s?" missing required sub element(s) '".concat(s.join(", "),"' "):n?" must provide one of the following '".concat(n.join(", "),"' "):" is empty",t("VAST-warning",{message:o,parentElement:i,specVersion:4.1})}const w={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),k(t,r),b(t)){E(t,r,i);for(let a=0;a2&&void 0!==arguments[2]?arguments[2]:{};const a=Array.from(e.childNodes).filter((e=>{const t=e.nodeName.toLowerCase();return"inline"===t||!1!==i&&"wrapper"===t}));for(const i of a){if(m.copyNodeAttribute("id",e,i),m.copyNodeAttribute("sequence",e,i),m.copyNodeAttribute("adType",e,i),"Wrapper"===i.nodeName)return{ad:I(i,t),type:"WRAPPER"};if("InLine"===i.nodeName)return{ad:C(i,t,{allowMultipleAds:r}),type:"INLINE"};const a=i.nodeName.toLowerCase();t("VAST-warning",{message:"<".concat(i.nodeName,"inline"===a?"> must be written ":"> must be written "),wrongNode:i})}}function C(e,t){let{allowMultipleAds:r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return!1===r&&e.getAttribute("sequence")?null:U(e,t)}function U(e,t){let r=[];t&&w.verifyRequiredValues(e,t);const i=Array.from(e.childNodes),a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(m.parseAttributes(e));return i.forEach((e=>{switch(e.nodeName){case"Error":a.errorURLTemplates.push(m.parseNodeText(e));break;case"Impression":a.impressionURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)});break;case"Creatives":a.creatives=function(e){const t=[];return e.forEach((e=>{const r={id:e.getAttribute("id")||null,adId:R(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},i=[];let a;m.childrenByName(e,"UniversalAdId").forEach((e=>{const t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:m.parseNodeText(e)};i.push(t)}));const s=m.childByName(e,"CreativeExtensions");s&&(a=T(m.childrenByName(s,"CreativeExtension")));for(const s in e.childNodes){const n=e.childNodes[s];let o;switch(n.nodeName){case"Linear":o=v(n,r);break;case"NonLinearAds":o=f(n,r);break;case"CompanionAds":o=g(n,r)}o&&(i&&(o.universalAdIds=i),a&&(o.creativeExtensions=a),t.push(o))}})),t}(m.childrenByName(e,"Creative"));break;case"Extensions":{const t=m.childrenByName(e,"Extension");a.extensions=T(t),a.adVerifications.length||(r=function(e){let t=null,r=[];e.some((e=>t=m.childByName(e,"AdVerifications"))),t&&(r=x(m.childrenByName(t,"Verification")));return r}(t));break}case"AdVerifications":a.adVerifications=x(m.childrenByName(e,"Verification"));break;case"AdSystem":a.system={value:m.parseNodeText(e),version:e.getAttribute("version")||null};break;case"AdTitle":a.title=m.parseNodeText(e);break;case"AdServingId":a.adServingId=m.parseNodeText(e);break;case"Category":a.categories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)});break;case"Expires":a.expires=parseInt(m.parseNodeText(e),10);break;case"ViewableImpression":a.viewableImpression.push(function(e){const t=(e,t)=>{const r=m.parseNodeText(t);return r&&e.push(r),e};return{id:e.getAttribute("id")||null,viewable:m.childrenByName(e,"Viewable").reduce(t,[]),notViewable:m.childrenByName(e,"NotViewable").reduce(t,[]),viewUndetermined:m.childrenByName(e,"ViewUndetermined").reduce(t,[])}}(e));break;case"Description":a.description=m.parseNodeText(e);break;case"Advertiser":a.advertiser={id:e.getAttribute("id")||null,value:m.parseNodeText(e)};break;case"Pricing":a.pricing={value:m.parseNodeText(e),model:e.getAttribute("model")||null,currency:e.getAttribute("currency")||null};break;case"Survey":a.survey={value:m.parseNodeText(e),type:e.getAttribute("type")||null};break;case"BlockedAdCategories":a.blockedAdCategories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)})}})),r.length&&(a.adVerifications=a.adVerifications.concat(r)),a}function I(e,t){const r=U(e,t),i=e.getAttribute("followAdditionalWrappers"),a=e.getAttribute("allowMultipleAds"),s=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||m.parseBoolean(i),r.allowMultipleAds=!!a&&m.parseBoolean(a),r.fallbackOnNoAd=s?m.parseBoolean(s):null;let n=m.childByName(e,"VASTAdTagURI");if(n?r.nextWrapperURL=m.parseNodeText(n):(n=m.childByName(e,"VASTAdTagURL"),n&&(r.nextWrapperURL=m.parseNodeText(m.childByName(n,"URL")))),r.creatives.forEach((e=>{if(["linear","nonlinear"].includes(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});for(const t in e.trackingEvents){const i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((i=>{r.trackingEvents[e.type][t].push(i)}))}}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((e=>{r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((e=>{r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function x(e){const t=[];return e.forEach((e=>{const r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=Array.from(e.childNodes);m.assignAttributes(e.attributes,r),i.forEach((e=>{let{nodeName:t,textContent:i,attributes:a}=e;switch(t){case"JavaScriptResource":case"ExecutableResource":r.resource=i.trim(),m.assignAttributes(a,r);break;case"VerificationParameters":r.parameters=i.trim()}}));const a=m.childByName(e,"TrackingEvents");a&&m.childrenByName(a,"Tracking").forEach((e=>{const t=e.getAttribute("event"),i=m.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}class S{constructor(){this._handlers=[]}on(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof t));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(typeof e));return this._handlers.push({event:e,handler:t}),this}once(e,t){return this.on(e,function(e,t,r){const i={fired:!1,wrapFn:void 0};function a(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e)(...arguments))}return i.wrapFn=a,a}(this,e,t))}off(e,t){return this._handlers=this._handlers.filter((r=>r.event!==e||r.handler!==t)),this}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i{"*"===t.event&&(a=!0,t.handler(e,...r)),t.event===e&&(a=!0,t.handler(...r))})),a}removeAllListeners(e){return e?(this._handlers=this._handlers.filter((t=>t.event!==e)),this):(this._handlers=[],this)}listenerCount(e){return this._handlers.filter((t=>t.event===e)).length}listeners(e){return this._handlers.reduce(((t,r)=>(r.event===e&&t.push(r.handler),t)),[])}eventNames(){return this._handlers.map((e=>e.event))}}let V=0,D=0;const O=(e,t)=>{if(!e||!t||e<=0||t<=0)return;D=(D*V+8*e/t)/++V},F={ERRORCODE:900,extensions:[]},B="VAST response version not supported";class P extends S{constructor(){let{fetcher:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.maxWrapperDepth=null,this.rootErrorURLTemplates=[],this.errorURLTemplates=[],this.remainingAds=[],this.parsingOptions={},this.fetcher=e||null}trackVastError(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a0&&void 0!==arguments[0]?arguments[0]:{};this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.rootURL="",this.resetParsingStatus(),O(e.byteLength,e.requestDuration)}resetParsingStatus(){this.errorURLTemplates=[],this.rootErrorURLTemplates=[],this.vastVersion=null}getRemainingAds(e){if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));const t=e?d.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.resolveAds(t,{wrapperDepth:0,url:this.rootURL}).then((e=>this.buildVASTResponse(e)))}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(t),t.isRootVAST=!0,this.parse(e,t).then((e=>this.buildVASTResponse(e)))}buildVASTResponse(e){const t=function(e){let{ads:t,errorURLTemplates:r,version:i}=e;return{ads:t||[],errorURLTemplates:r||[],version:i||null}}({ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion});return this.completeWrapperResolving(t),t}parseVastXml(e,t){let{isRootVAST:r=!1,url:i=null,wrapperDepth:a=0,allowMultipleAds:s,followAdditionalWrappers:n}=t;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName){var o;this.emit("VAST-ad-parsed",{type:"ERROR",url:i,wrapperDepth:a});const t="VideoAdServingTemplate"===(null==e||null===(o=e.documentElement)||void 0===o?void 0:o.nodeName);throw new Error(t?B:"Invalid VAST XMLDocument")}const l=[],c=e.documentElement.childNodes,u=e.documentElement.getAttribute("version");r&&u&&(this.vastVersion=u);for(const e in c){const t=c[e];if("Error"===t.nodeName){const e=m.parseNodeText(t);r?this.rootErrorURLTemplates.push(e):this.errorURLTemplates.push(e)}else if("Ad"===t.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)s=!0;else if(!1===s&&l.length>1)break;const e=L(t,this.emit.bind(this),{allowMultipleAds:s,followAdditionalWrappers:n});e.ad?(l.push(e.ad),this.emit("VAST-ad-parsed",{type:e.type,url:i,wrapperDepth:a,adIndex:l.length-1,vastVersion:u})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return l}parse(e){let{url:t=null,resolveAll:r=!0,wrapperSequence:i=null,previousUrl:a=null,wrapperDepth:s=0,isRootVAST:n=!1,followAdditionalWrappers:o,allowMultipleAds:l}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},c=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&n&&(l=!0);try{c=this.parseVastXml(e,{isRootVAST:n,url:t,wrapperDepth:s,allowMultipleAds:l,followAdditionalWrappers:o})}catch(e){return Promise.reject(e)}return 1===c.length&&null!=i&&(c[0].sequence=i),!1===r&&(this.remainingAds=m.splitVAST(c),c=this.remainingAds.shift()),this.resolveAds(c,{wrapperDepth:s,previousUrl:a,url:t})}resolveAds(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],{wrapperDepth:t,previousUrl:r,url:i}=arguments.length>1?arguments[1]:void 0;const a=[];return r=i,e.forEach((e=>{const i=this.resolveWrappers(e,t,r);a.push(i)})),Promise.all(a).then((e=>d.flatten(e)))}resolveWrappers(e,t,r){const i={...e};return new Promise((e=>{var a;if(t++,!i.nextWrapperURL)return delete i.nextWrapperURL,e(i);if(!this.fetcher)return i.VASTAdTagURI=i.nextWrapperURL,delete i.nextWrapperURL,e(i);if(t>=this.maxWrapperDepth)return i.errorCode=302,delete i.nextWrapperURL,e(i);i.nextWrapperURL=m.resolveVastAdTagURI(i.nextWrapperURL,r);const s=null!==(a=this.parsingOptions.allowMultipleAds)&&void 0!==a?a:i.allowMultipleAds,n=i.sequence;this.fetcher.fetchVAST({url:i.nextWrapperURL,emitter:this.emit.bind(this),maxWrapperDepth:this.maxWrapperDepth}).then((a=>this.parse(a,{url:i.nextWrapperURL,previousUrl:r,wrapperSequence:n,wrapperDepth:t,followAdditionalWrappers:i.followAdditionalWrappers,allowMultipleAds:s}).then((t=>{if(delete i.nextWrapperURL,0===t.length)return i.creatives=[],e(i);t.forEach((e=>{e&&m.mergeWrapperAdData(e,i)})),e(t)})))).catch((t=>{i.errorCode=t.message===B?102:301,i.errorMessage=t.message,e(i)}))}))}completeWrapperResolving(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(let t=e.ads.length-1;t>=0;t--){const r=e.ads[t],i=!r.creatives.some((e=>{var t;return(null===(t=e.mediaFiles)||void 0===t?void 0:t.length)>0}));!r.errorCode&&!i||r.VASTAdTagURI||(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}let M=null;const W={data:{},length:0,getItem(e){return this.data[e]},setItem(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem(e){delete this.data[e],this.length=Object.keys(this.data).length},clear(){this.data={},this.length=0}};class j{constructor(){this.storage=this.initStorage()}initStorage(){if(M)return M;try{M="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){M=null}return M&&!this.isStorageDisabled(M)||(M=W,M.clear()),M}isStorageDisabled(e){const t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}getItem(e){return this.storage.getItem(e)}setItem(e,t){return this.storage.setItem(e,t)}removeItem(e){return this.storage.removeItem(e)}clear(){return this.storage.clear()}}const q=12e4;const K={get:async function(e,t){try{const r=new AbortController,i=setTimeout((()=>{throw r.abort(),new Error("URLHandler: Request timed out after ".concat(t.timeout||q," ms (408)"))}),t.timeout||q),a=await fetch(e,{...t,signal:r.signal,credentials:t.withCredentials?"include":"omit"}).finally((()=>{clearTimeout(i)})),s=function(e){var t;return"https:"===(null===(t=window)||void 0===t||null===(t=t.location)||void 0===t?void 0:t.protocol)&&e.url.includes("http://")?"URLHandler: Cannot go from HTTPS to HTTP.":200===e.status&&e.ok?null:"URLHandler: ".concat(e.statusText," (").concat(e.status,")")}(a);return s?{error:new Error(s),statusCode:a.status}:async function(e){const t=await e.text();let r;r=d.isBrowserEnvironment()?new DOMParser:new((await Promise.resolve().then((function(){return require("./chunks/xmldom-623c1b6b.min.js")}))).DOMParser);return{xml:r.parseFromString(t,"text/xml"),details:{byteLength:t.length,statusCode:e.status,rawXml:t}}}(a)}catch(e){return{error:e,statusCode:"AbortError"===e.name?408:null}}}};class H{constructor(){this.URLTemplateFilters=[]}setOptions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.urlHandler=e.urlHandler||e.urlhandler||K,this.fetchingOptions={timeout:e.timeout||q,withCredentials:Boolean(e.withCredentials)}}addURLTemplateFilter(e){"function"==typeof e&&this.URLTemplateFilters.push(e)}removeLastURLTemplateFilter(){this.URLTemplateFilters.pop()}countURLTemplateFilters(){return this.URLTemplateFilters.length}clearURLTemplateFilters(){this.URLTemplateFilters=[]}async fetchVAST(e){var t;let{url:r,maxWrapperDepth:i,emitter:a,wrapperDepth:s=0,previousUrl:n=null,wrapperAd:o=null}=e;const l=Date.now();this.URLTemplateFilters.forEach((e=>{r=e(r)})),a("VAST-resolving",{url:r,previousUrl:n,wrapperDepth:s,maxWrapperDepth:i,timeout:this.fetchingOptions.timeout,wrapperAd:o});const c=await this.urlHandler.get(r,this.fetchingOptions),u=Math.round(Date.now()-l);if(a("VAST-resolved",{url:r,previousUrl:n,wrapperDepth:s,error:(null==c?void 0:c.error)||null,duration:u,statusCode:(null==c?void 0:c.statusCode)||null,...null==c?void 0:c.details}),O(null==c||null===(t=c.details)||void 0===t?void 0:t.byteLength,u),c.error)throw new Error(c.error);return c.xml}}exports.VASTClient=class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new j;this.cappingFreeLunch=e,this.cappingMinimumTimeInterval=t,this.fetcher=new H,this.vastParser=new P({fetcher:this.fetcher}),this.storage=r,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}addURLTemplateFilter(e){this.fetcher.addURLTemplateFilter(e)}removeLastURLTemplateFilter(){this.fetcher.removeLastURLTemplateFilter()}countURLTemplateFilters(){return this.fetcher.countURLTemplateFilters()}clearURLTemplateFilters(){this.fetcher.clearURLTemplateFilters()}getParser(){return this.vastParser}get lastSuccessfulAd(){return this.storage.getItem("vast-client-last-successful-ad")}set lastSuccessfulAd(e){this.storage.setItem("vast-client-last-successful-ad",e)}get totalCalls(){return this.storage.getItem("vast-client-total-calls")}set totalCalls(e){this.storage.setItem("vast-client-total-calls",e)}get totalCallsTimeout(){return this.storage.getItem("vast-client-total-calls-timeout")}set totalCallsTimeout(e){this.storage.setItem("vast-client-total-calls-timeout",e)}hasRemainingAds(){return this.vastParser.remainingAds.length>0}getNextAds(e){return this.vastParser.getRemainingAds(e)}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.fetcher.setOptions(t),this.vastParser.parseVAST(e,t)}get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=Date.now();return t.hasOwnProperty("resolveAll")||(t.resolveAll=!1),this.totalCallsTimeout{if(this.cappingFreeLunch>=this.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(this.totalCalls,"/").concat(this.cappingFreeLunch)));const s=r-this.lastSuccessfulAd;if(s<0)this.lastSuccessfulAd=0;else if(s(t.previousUrl=e,t.isRootVAST=!0,t.url=e,this.vastParser.parse(r,t).then((e=>{const t=this.vastParser.buildVASTResponse(e);i(t)}))))).catch((e=>a(e)))}))}},exports.VASTParser=P,exports.VASTTracker=class extends S{constructor(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),this.ad=t,this.creative=r,this.variation=i,this.muted=a,this.impressed=!1,this.skippable=!1,this.trackingEvents={},this.lastPercentage=0,this._alreadyTriggeredQuartiles={},this.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"];for(const e in this.creative.trackingEvents){const t=this.creative.trackingEvents[e];this.trackingEvents[e]=t.slice(0)}!function(e){return"linear"===e.type}(this.creative)?this._initVariationTracking():this._initLinearTracking(),e&&this.on("start",(()=>{e.lastSuccessfulAd=Date.now()}))}_initLinearTracking(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}_initVariationTracking(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(const e in this.variation.trackingEvents){const t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}setDuration(e){d.isValidTimeValue(e)?(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100}):this.emit("TRACKER-error",{message:"the duration provided is not valid. duration: ".concat(e)})}setProgress(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!d.isValidTimeValue(e)||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given setProgress parameter has the wrong type. progress: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});const i=this.skipDelay||-1;if(-1===i||this.skippable||(i>e?this.emit("skip-countdown",i-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){const i=Math.round(e/this.assetDuration*100),a=[];if(e>0){a.push("start");for(let e=this.lastPercentage;e{this.track(e,{macros:t,once:r})})),e1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e):this.emit("TRACKER-error",{message:"One given setMuted parameter has the wrong type. muted: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setPaused(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e):this.emit("TRACKER-error",{message:"One given setPaused parameter has the wrong type. paused: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setFullscreen(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e):this.emit("TRACKER-error",{message:"One given setFullScreen parameter has the wrong type. fullscreen: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setExpand(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e):this.emit("TRACKER-error",{message:"One given setExpand parameter has the wrong type. expanded: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setSkipDelay(e){d.isValidTimeValue(e)?this.skipDelay=e:this.emit("TRACKER-error",{message:"setSkipDelay parameter does not have a valid value. duration: ".concat(e)})}trackImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})):this.emit("TRACKER-error",{message:"trackImpression parameter has the wrong type. macros: ".concat(e)})}trackViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewable,e)})):this.emit("TRACKER-error",{message:"trackViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackNotViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.notViewable,e)})):this.emit("TRACKER-error",{message:"trackNotViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackUndeterminedImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewUndetermined,e)})):this.emit("TRACKER-error",{message:"trackUndeterminedImpression given macros has the wrong type. macros: ".concat(e)})}error(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"==typeof e&&"boolean"==typeof t?this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t}):this.emit("TRACKER-error",{message:"One given error parameter has the wrong type. macros: ".concat(d.formatMacrosValues(e),", isCustomCode: ").concat(t)})}errorWithCode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t?(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead")):this.emit("TRACKER-error",{message:"One given errorWithCode parameter has the wrong type. errorCode: ".concat(e,", isCustomCode: ").concat(t)})}complete(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("complete",{macros:e}):this.emit("TRACKER-error",{message:"complete given macros has the wrong type. macros: ".concat(e)})}notUsed(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?(this.track("notUsed",{macros:e}),this.trackingEvents=[]):this.emit("TRACKER-error",{message:"notUsed given macros has the wrong type. macros: ".concat(e)})}otherAdInteraction(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("otherAdInteraction",{macros:e}):this.emit("TRACKER-error",{message:"otherAdInteraction given macros has the wrong type. macros: ".concat(e)})}acceptInvitation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("acceptInvitation",{macros:e}):this.emit("TRACKER-error",{message:"acceptInvitation given macros has the wrong type. macros: ".concat(e)})}adExpand(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adExpand",{macros:e}):this.emit("TRACKER-error",{message:"adExpand given macros has the wrong type. macros: ".concat(e)})}adCollapse(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adCollapse",{macros:e}):this.emit("TRACKER-error",{message:"adCollapse given macros has the wrong type. macros: ".concat(e)})}minimize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("minimize",{macros:e}):this.emit("TRACKER-error",{message:"minimize given macros has the wrong type. macros: ".concat(e)})}verificationNotExecuted(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given verificationNotExecuted parameter has to wrong type. vendor: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");const r=this.ad.adVerifications.find((t=>t.vendor===e));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));const i=r.trackingEvents;if(i&&i.verificationNotExecuted){const e=i.verificationNotExecuted;this.trackURLs(e,t),this.emit("verificationNotExecuted",{trackingURLTemplates:e})}}overlayViewDuration(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"==typeof t?(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t})):this.emit("TRACKER-error",{message:"One given overlayViewDuration parameters has the wrong type. formattedDuration: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}close(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track(this.linear?"closeLinear":"close",{macros:e}):this.emit("TRACKER-error",{message:"close given macros has the wrong type. macros: ".concat(e)})}skip(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("skip",{macros:e}):this.emit("TRACKER-error",{message:"skip given macros has the wrong type. macros: ".concat(e)})}load(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("loaded",{macros:e}):this.emit("TRACKER-error",{message:"load given macros has the wrong type. macros: ".concat(e)})}click(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!==e&&"string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given click parameter has the wrong type. fallbackClickThroughURL: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);const r=this.clickThroughURLTemplate||e,i={...t};if(r){this.progress&&(i.ADPLAYHEAD=this.progressFormatted());const e=d.resolveURLTemplates([r],i)[0];this.emit("clickthrough",e)}}track(e){let{macros:t={},once:r=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"!=typeof t)return void this.emit("TRACKER-error",{message:"track given macros has the wrong type. macros: ".concat(t)});"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");const i=this.trackingEvents[e],a=this.emitAlwaysEvents.indexOf(e)>-1;i?(this.emit(e,{trackingURLTemplates:i}),this.trackURLs(i,t)):a&&this.emit(e,null),r&&(delete this.trackingEvents[e],a&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}trackURLs(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{validUrls:a,invalidUrls:s}=d.filterUrlTemplates(e);s.length&&this.emit("TRACKER-error",{message:"Provided urls are malformed. url: ".concat(s)});const n={...r};this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(n.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(n.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(t=t.universalAdIds)&&void 0!==t&&t.length&&(n.UNIVERSALADID=this.creative.universalAdIds.map((e=>e.idRegistry.concat(" ",e.value))).join(",")),this.ad&&(this.ad.sequence&&(n.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(n.ADTYPE=this.ad.adType),this.ad.adServingId&&(n.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(n.ADCATEGORIES=this.ad.categories.map((e=>e.value)).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(n.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories.map((e=>e.value)).join(","))),d.track(a,n,i)}convertToTimecode(e){if(!d.isValidTimeValue(e))return"";const t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),a=Math.floor(t/1e3%60),s=Math.floor(t%1e3);return"".concat(d.addLeadingZeros(r,2),":").concat(d.addLeadingZeros(i,2),":").concat(d.addLeadingZeros(a,2),".").concat(d.addLeadingZeros(s,3))}progressFormatted(){return this.convertToTimecode(this.progress)}},exports.parseDuration=p; diff --git a/dist/vast-client.js b/dist/vast-client.js index 8a719dcd..674d1606 100644 --- a/dist/vast-client.js +++ b/dist/vast-client.js @@ -2066,7 +2066,8 @@ const DEFAULT_EVENT_DATA = { ERRORCODE: 900, extensions: [] }; - +const INVALID_VAST_ERROR = 'Invalid VAST XMLDocument'; +const NON_SUPPORTED_VAST_VERSION = 'VAST response version not supported'; /** * This class provides methods to fetch and parse a VAST document. * @export @@ -2084,7 +2085,10 @@ class VASTParser extends EventEmitter { } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; super(); this.maxWrapperDepth = null; + this.rootErrorURLTemplates = []; + this.errorURLTemplates = []; this.remainingAds = []; + this.parsingOptions = {}; this.fetcher = fetcher || null; } @@ -2216,12 +2220,15 @@ class VASTParser extends EventEmitter { } = _ref; // check if is a valid VAST document if (!vastXml || !vastXml.documentElement || vastXml.documentElement.nodeName !== 'VAST') { + var _vastXml$documentElem; this.emit('VAST-ad-parsed', { type: 'ERROR', url, wrapperDepth }); - throw new Error('Invalid VAST XMLDocument'); + // VideoAdServingTemplate node is used for VAST 1.0 + const isNonSupportedVast = (vastXml === null || vastXml === void 0 || (_vastXml$documentElem = vastXml.documentElement) === null || _vastXml$documentElem === void 0 ? void 0 : _vastXml$documentElem.nodeName) === 'VideoAdServingTemplate'; + throw new Error(isNonSupportedVast ? NON_SUPPORTED_VAST_VERSION : INVALID_VAST_ERROR); } const ads = []; const childNodes = vastXml.documentElement.childNodes; @@ -2438,8 +2445,8 @@ class VASTParser extends EventEmitter { }); }).catch(err => { // Timeout of VAST URI provided in Wrapper element, or of VAST URI provided in a subsequent Wrapper element. - // (URI was either unavailable or reached a timeout as defined by the video player.) - ad.errorCode = 301; + // (URI was either unavailable or reached a timeout as defined by the video player) + ad.errorCode = err.message === NON_SUPPORTED_VAST_VERSION ? 102 : 301; ad.errorMessage = err.message; resolve(ad); }); @@ -2466,7 +2473,11 @@ class VASTParser extends EventEmitter { // - No Creative case - The parser has dealt with soma or/and an elements // but no creative was found const ad = vastResponse.ads[index]; - if ((ad.errorCode || ad.creatives.length === 0) && !ad.VASTAdTagURI) { + const noMediaFilesAvailable = !ad.creatives.some(creative => { + var _creative$mediaFiles; + return ((_creative$mediaFiles = creative.mediaFiles) === null || _creative$mediaFiles === void 0 ? void 0 : _creative$mediaFiles.length) > 0; + }); + if ((ad.errorCode || noMediaFilesAvailable) && !ad.VASTAdTagURI) { // If VASTAdTagURI is in the vastResponse, it means we are dealing with a Wrapper when using parseVAST from the VASTParser. // In that case, we dont want to modify the vastResponse since the creatives node is not required in a wrapper. this.trackVastError(ad.errorURLTemplates.concat(vastResponse.errorURLTemplates), { @@ -2639,7 +2650,8 @@ async function handleResponse(response) { * @returns {String | null} */ function handleError(response) { - if (window.location.protocol === 'https:' && response.url.includes('http://')) { + var _window; + if (((_window = window) === null || _window === void 0 || (_window = _window.location) === null || _window === void 0 ? void 0 : _window.protocol) === 'https:' && response.url.includes('http://')) { return 'URLHandler: Cannot go from HTTPS to HTTP.'; } if (response.status !== 200 || !response.ok) { @@ -2660,8 +2672,9 @@ async function get(url, options) { ...options, signal: controller.signal, credentials: options.withCredentials ? 'include' : 'omit' + }).finally(() => { + clearTimeout(timer); }); - clearTimeout(timer); const error = handleError(response); if (error) { return { diff --git a/dist/vast-client.min.js b/dist/vast-client.min.js index 0cee002e..febfc22e 100644 --- a/dist/vast-client.min.js +++ b/dist/vast-client.min.js @@ -1 +1 @@ -function e(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}const t=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REGULATIONS","SERVERSIDE","SERVERUA","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"];function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=[],n=s(e);!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=u(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING;for(const e in t)t[e]=c(t[e]);for(const e in n){const r=n[e];"string"==typeof r&&a.push(i(r,t))}return a}function i(e,r){const i=(e=a(e,r)).match(/[^[\]]+(?=])/g);if(!i)return e;let s=i.filter((e=>t.indexOf(e)>-1));return 0===s.length?e:(s=s.reduce(((e,t)=>(e[t]=-1,e)),{}),a(e,s))}function a(e,t){let r=e;for(const e in t){const i=t[e];r=r.replace(new RegExp("(?:\\[|%%)(".concat(e,")(?:\\]|%%)"),"g"),i)}return r}function s(e){return Array.isArray(e)?e.map((e=>e&&e.hasOwnProperty("url")?e.url:e)):e}function n(e){return/^(https?:\/\/|\/\/)/.test(e)}function o(e,t){for(let r=0;r"%".concat(e.charCodeAt(0).toString(16))))}function u(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}const d={track:function(e,t,i){r(e,t,i).forEach((e=>{if("undefined"!=typeof window&&null!==window){(new Image).src=e}}))},resolveURLTemplates:r,extractURLsFromTemplates:s,filterUrlTemplates:function(e){return e.reduce(((e,t)=>{const r=t.url||t;return n(r)?e.validUrls.push(r):e.invalidUrls.push(r),e}),{validUrls:[],invalidUrls:[]})},containsTemplateObject:o,isTemplateObjectEqual:l,encodeURIComponentRFC3986:c,replaceUrlMacros:i,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce(((t,r)=>t.concat(Array.isArray(r)?e(r):r)),[])},joinArrayOfUniqueTemplateObjs:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];return r.concat(i).reduce(((e,t)=>(o(t,e)||e.push(t),e)),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:u,isValidUrl:n,isBrowserEnvironment:function(){return"undefined"!=typeof window},formatMacrosValues:function(e){return"object"!=typeof e?e:JSON.stringify(e)}};function h(e){return["true","TRUE","True","1"].includes(e)}function p(e){if(null==e)return-1;if(d.isNumeric(e))return parseInt(e);const t=e.split(":");if(3!==t.length)return-1;const r=t[2].split(".");let i=parseInt(r[0]);2===r.length&&(i+=parseFloat("0.".concat(r[1])));const a=parseInt(60*t[1]),s=parseInt(60*t[0]*60);return isNaN(s)||isNaN(a)||isNaN(i)||a>3600||i>60?-1:s+a+i}const m={childByName:function(e,t){return Array.from(e.childNodes).find((e=>e.nodeName===t))},childrenByName:function(e,t){return Array.from(e.childNodes).filter((e=>e.nodeName===t))},resolveVastAdTagURI:function(e,t){if(!t)return e;if(e.startsWith("//")){const{protocol:t}=location;return"".concat(t).concat(e)}if(!e.includes("://")){const r=t.slice(0,t.lastIndexOf("/"));return"".concat(r,"/").concat(e)}return e},parseBoolean:h,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){const i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){return Array.from(e.attributes).reduce(((e,t)=>(e[t.nodeName]=t.nodeValue,e)),{})},parseDuration:p,splitVAST:function(e){const t=[];let r=null;return e.forEach(((i,a)=>{if(i.sequence&&(i.sequence=parseInt(i.sequence,10)),i.sequence>1){const t=e[a-1];if(t&&t.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){e&&Array.from(e).forEach((e=>{let{nodeName:r,nodeValue:i}=e;if(r&&i&&t.hasOwnProperty(r)){let e=i;"boolean"==typeof t[r]&&(e=h(e)),t[r]=e}}))},mergeWrapperAdData:function(e,t){var r;e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[...e.viewableImpression,...t.viewableImpression]),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;const i=(t.creatives||[]).filter((e=>e&&"companion"===e.type)),a=i.reduce(((e,t)=>((t.variations||[]).forEach((t=>{(t.companionClickTrackingURLTemplates||[]).forEach((t=>{d.containsTemplateObject(t,e)||e.push(t)}))})),e)),[]);e.creatives=i.concat(e.creatives);const s=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,n=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;if(e.creatives.forEach((e=>{if(t.trackingEvents&&t.trackingEvents[e.type])for(const r in t.trackingEvents[e.type]){const i=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(i)}"linear"===e.type&&(s&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),n&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&a.length&&(e.variations||[]).forEach((e=>{e.companionClickTrackingURLTemplates=d.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,a)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories)),null!==(r=t.creatives)&&void 0!==r&&r.length){const r=t.creatives.filter((e=>{var t;return(null===(t=e.icons)||void 0===t?void 0:t.length)&&!e.mediaFiles.length}));r.length&&(e.creatives=e.creatives.concat(r))}}};function g(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"companion",required:null,variations:[]}}(r);return i.required=t.getAttribute("required")||null,i.variations=m.childrenByName(t,"Companion").map((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotId:e.adSlotId||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(m.parseAttributes(e));t.htmlResources=m.childrenByName(e,"HTMLResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=m.childrenByName(e,"IFrameResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=m.childrenByName(e,"StaticResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=m.parseNodeText(m.childByName(e,"AltText"))||null;const r=m.childByName(e,"TrackingEvents");r&&m.childrenByName(r,"Tracking").forEach((e=>{const r=e.getAttribute("event"),i=m.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=m.childrenByName(e,"CompanionClickTracking").map((e=>({id:e.getAttribute("id")||null,url:m.parseNodeText(e)}))),t.companionClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"CompanionClickThrough"))||null;const i=m.childByName(e,"AdParameters");return i&&(t.adParameters={value:m.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t})),i}function v(t,r){let i;const a=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(r);a.duration=m.parseDuration(m.parseNodeText(m.childByName(t,"Duration")));const s=t.getAttribute("skipoffset");if(null==s)a.skipDelay=null;else if("%"===s.charAt(s.length-1)&&-1!==a.duration){const e=parseInt(s,10);a.skipDelay=a.duration*(e/100)}else a.skipDelay=m.parseDuration(s);const n=m.childByName(t,"VideoClicks");if(n){const e=m.childByName(n,"ClickThrough");a.videoClickThroughURLTemplate=e?{id:e.getAttribute("id")||null,url:m.parseNodeText(e)}:null,m.childrenByName(n,"ClickTracking").forEach((e=>{a.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),m.childrenByName(n,"CustomClick").forEach((e=>{a.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}))}const o=m.childByName(t,"AdParameters");o&&(a.adParameters={value:m.parseNodeText(o),xmlEncoded:o.getAttribute("xmlEncoded")||null}),m.childrenByName(t,"TrackingEvents").forEach((e=>{m.childrenByName(e,"Tracking").forEach((e=>{let t=e.getAttribute("event");const r=m.parseNodeText(e);if(t&&r){if("progress"===t){if(i=e.getAttribute("offset"),!i)return;t="%"===i.charAt(i.length-1)?"progress-".concat(i):"progress-".concat(Math.round(m.parseDuration(i)))}Array.isArray(a.trackingEvents[t])||(a.trackingEvents[t]=[]),a.trackingEvents[t].push(r)}}))})),m.childrenByName(t,"MediaFiles").forEach((e=>{m.childrenByName(e,"MediaFile").forEach((e=>{a.mediaFiles.push(function(e){const t={id:null,fileURL:null,fileSize:0,deliveryType:"progressive",mimeType:null,mediaType:null,codec:null,bitrate:0,minBitrate:0,maxBitrate:0,width:0,height:0,apiFramework:null,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=m.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);const r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=m.parseBoolean(r));const i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=m.parseBoolean(i));return t}(e))}));const t=m.childByName(e,"InteractiveCreativeFile");t&&(a.interactiveCreativeFile=function(e){const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:m.parseBoolean(e.variableDuration),fileURL:null}}(m.parseAttributes(e));return t.fileURL=m.parseNodeText(e),t}(t));const r=m.childByName(e,"ClosedCaptionFiles");r&&m.childrenByName(r,"ClosedCaptionFile").forEach((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(m.parseAttributes(e));t.fileURL=m.parseNodeText(e),a.closedCaptionFiles.push(t)}));const i=m.childByName(e,"Mezzanine"),s=function(e,t){const r={};let i=!1;return t.forEach((t=>{e&&e.getAttribute(t)?r[t]=e.getAttribute(t):i=!0})),i?null:r}(i,["delivery","type","width","height"]);if(s){const e={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};e.id=i.getAttribute("id"),e.fileURL=m.parseNodeText(i),e.delivery=s.delivery,e.codec=i.getAttribute("codec"),e.type=s.type,e.width=parseInt(s.width,10),e.height=parseInt(s.height,10),e.fileSize=parseInt(i.getAttribute("fileSize"),10),e.mediaType=i.getAttribute("mediaType")||"2D",a.mezzanine=e}}));const l=m.childByName(t,"Icons");return l&&m.childrenByName(l,"Icon").forEach((e=>{a.icons.push(function(e){const t={program:null,height:0,width:0,xPosition:0,yPosition:0,apiFramework:null,offset:null,duration:0,type:null,staticResource:null,htmlResource:null,iframeResource:null,pxratio:"1",iconClickThroughURLTemplate:null,iconClickTrackingURLTemplates:[],iconViewTrackingURLTemplate:null,iconClickFallbackImages:[]};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=m.parseDuration(e.getAttribute("offset")),t.duration=m.parseDuration(e.getAttribute("duration")),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"IconClicks");if(r){t.iconClickThroughURLTemplate=m.parseNodeText(m.childByName(r,"IconClickThrough")),m.childrenByName(r,"IconClickTracking").forEach((e=>{t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}));const e=m.childByName(r,"IconClickFallbackImages");e&&m.childrenByName(e,"IconClickFallbackImage").forEach((e=>{t.iconClickFallbackImages.push({url:m.parseNodeText(e)||null,width:e.getAttribute("width")||null,height:e.getAttribute("height")||null})}))}return t.iconViewTrackingURLTemplate=m.parseNodeText(m.childByName(e,"IconViewTracking")),t}(e))})),a}function f(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"nonlinear",variations:[],trackingEvents:{}}}(r);return m.childrenByName(t,"TrackingEvents").forEach((e=>{let t,r;m.childrenByName(e,"Tracking").forEach((e=>{t=e.getAttribute("event"),r=m.parseNodeText(e),t&&r&&(Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(r))}))})),m.childrenByName(t,"NonLinear").forEach((e=>{const t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=m.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=m.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=m.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"AdParameters");r&&(t.adParameters={value:m.parseNodeText(r),xmlEncoded:r.getAttribute("xmlEncoded")||null}),t.nonlinearClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"NonLinearClickThrough")),m.childrenByName(e,"NonLinearClickTracking").forEach((e=>{t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),i.variations.push(t)})),i}function T(e){const t=[];return e.forEach((e=>{const r=A(e);r&&t.push(r)})),t}function A(e){if("#comment"===e.nodeName)return null;const t={name:null,value:null,attributes:{},children:[]},r=e.attributes,i=e.childNodes;if(t.name=e.nodeName,e.attributes)for(const e in r)if(r.hasOwnProperty(e)){const i=r[e];i.nodeName&&i.nodeValue&&(t.attributes[i.nodeName]=i.nodeValue)}for(const e in i)if(i.hasOwnProperty(e)){const r=A(i[e]);r&&t.children.push(r)}if(0===t.children.length||1===t.children.length&&["#cdata-section","#text"].indexOf(t.children[0].name)>=0){const r=m.parseNodeText(e);""!==r&&(t.value=r),t.children=[]}return null===(a=t).value&&0===Object.keys(a.attributes).length&&0===a.children.length?null:t;var a}function R(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}const y={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function k(e,t){if(!y[e.nodeName]||!y[e.nodeName].attributes)return;const r=y[e.nodeName].attributes.filter((t=>!e.getAttribute(t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}function E(e,t,r){const i=y[e.nodeName],a=!r&&"Wrapper"!==e.nodeName;if(!i||a)return;if(i.subElements){const r=i.subElements.filter((t=>!m.childByName(e,t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:r},t)}if(!r||!i.oneOfinLineResources)return;i.oneOfinLineResources.some((t=>m.childByName(e,t)))||N({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}function b(e){return e.children&&0!==e.children.length}function N(e,t){let{name:r,parentName:i,attributes:a,subElements:s,oneOfResources:n}=e,o="Element '".concat(r,"'");o+=a?" missing required attribute(s) '".concat(a.join(", "),"' "):s?" missing required sub element(s) '".concat(s.join(", "),"' "):n?" must provide one of the following '".concat(n.join(", "),"' "):" is empty",t("VAST-warning",{message:o,parentElement:i,specVersion:4.1})}const w={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),k(t,r),b(t)){E(t,r,i);for(let a=0;a2&&void 0!==arguments[2]?arguments[2]:{};const a=Array.from(e.childNodes).filter((e=>{const t=e.nodeName.toLowerCase();return"inline"===t||!1!==i&&"wrapper"===t}));for(const i of a){if(m.copyNodeAttribute("id",e,i),m.copyNodeAttribute("sequence",e,i),m.copyNodeAttribute("adType",e,i),"Wrapper"===i.nodeName)return{ad:I(i,t),type:"WRAPPER"};if("InLine"===i.nodeName)return{ad:L(i,t,{allowMultipleAds:r}),type:"INLINE"};const a=i.nodeName.toLowerCase();t("VAST-warning",{message:"<".concat(i.nodeName,"inline"===a?"> must be written ":"> must be written "),wrongNode:i})}}function L(e,t){let{allowMultipleAds:r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return!1===r&&e.getAttribute("sequence")?null:U(e,t)}function U(e,t){let r=[];t&&w.verifyRequiredValues(e,t);const i=Array.from(e.childNodes),a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(m.parseAttributes(e));return i.forEach((e=>{switch(e.nodeName){case"Error":a.errorURLTemplates.push(m.parseNodeText(e));break;case"Impression":a.impressionURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)});break;case"Creatives":a.creatives=function(e){const t=[];return e.forEach((e=>{const r={id:e.getAttribute("id")||null,adId:R(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},i=[];let a;m.childrenByName(e,"UniversalAdId").forEach((e=>{const t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:m.parseNodeText(e)};i.push(t)}));const s=m.childByName(e,"CreativeExtensions");s&&(a=T(m.childrenByName(s,"CreativeExtension")));for(const s in e.childNodes){const n=e.childNodes[s];let o;switch(n.nodeName){case"Linear":o=v(n,r);break;case"NonLinearAds":o=f(n,r);break;case"CompanionAds":o=g(n,r)}o&&(i&&(o.universalAdIds=i),a&&(o.creativeExtensions=a),t.push(o))}})),t}(m.childrenByName(e,"Creative"));break;case"Extensions":{const t=m.childrenByName(e,"Extension");a.extensions=T(t),a.adVerifications.length||(r=function(e){let t=null,r=[];e.some((e=>t=m.childByName(e,"AdVerifications"))),t&&(r=x(m.childrenByName(t,"Verification")));return r}(t));break}case"AdVerifications":a.adVerifications=x(m.childrenByName(e,"Verification"));break;case"AdSystem":a.system={value:m.parseNodeText(e),version:e.getAttribute("version")||null};break;case"AdTitle":a.title=m.parseNodeText(e);break;case"AdServingId":a.adServingId=m.parseNodeText(e);break;case"Category":a.categories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)});break;case"Expires":a.expires=parseInt(m.parseNodeText(e),10);break;case"ViewableImpression":a.viewableImpression.push(function(e){const t=(e,t)=>{const r=m.parseNodeText(t);return r&&e.push(r),e};return{id:e.getAttribute("id")||null,viewable:m.childrenByName(e,"Viewable").reduce(t,[]),notViewable:m.childrenByName(e,"NotViewable").reduce(t,[]),viewUndetermined:m.childrenByName(e,"ViewUndetermined").reduce(t,[])}}(e));break;case"Description":a.description=m.parseNodeText(e);break;case"Advertiser":a.advertiser={id:e.getAttribute("id")||null,value:m.parseNodeText(e)};break;case"Pricing":a.pricing={value:m.parseNodeText(e),model:e.getAttribute("model")||null,currency:e.getAttribute("currency")||null};break;case"Survey":a.survey={value:m.parseNodeText(e),type:e.getAttribute("type")||null};break;case"BlockedAdCategories":a.blockedAdCategories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)})}})),r.length&&(a.adVerifications=a.adVerifications.concat(r)),a}function I(e,t){const r=U(e,t),i=e.getAttribute("followAdditionalWrappers"),a=e.getAttribute("allowMultipleAds"),s=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||m.parseBoolean(i),r.allowMultipleAds=!!a&&m.parseBoolean(a),r.fallbackOnNoAd=s?m.parseBoolean(s):null;let n=m.childByName(e,"VASTAdTagURI");if(n?r.nextWrapperURL=m.parseNodeText(n):(n=m.childByName(e,"VASTAdTagURL"),n&&(r.nextWrapperURL=m.parseNodeText(m.childByName(n,"URL")))),r.creatives.forEach((e=>{if(["linear","nonlinear"].includes(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});for(const t in e.trackingEvents){const i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((i=>{r.trackingEvents[e.type][t].push(i)}))}}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((e=>{r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((e=>{r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function x(e){const t=[];return e.forEach((e=>{const r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=Array.from(e.childNodes);m.assignAttributes(e.attributes,r),i.forEach((e=>{let{nodeName:t,textContent:i,attributes:a}=e;switch(t){case"JavaScriptResource":case"ExecutableResource":r.resource=i.trim(),m.assignAttributes(a,r);break;case"VerificationParameters":r.parameters=i.trim()}}));const a=m.childByName(e,"TrackingEvents");a&&m.childrenByName(a,"Tracking").forEach((e=>{const t=e.getAttribute("event"),i=m.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}class S{constructor(){this._handlers=[]}on(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof t));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(typeof e));return this._handlers.push({event:e,handler:t}),this}once(e,t){return this.on(e,function(e,t,r){const i={fired:!1,wrapFn:void 0};function a(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e)(...arguments))}return i.wrapFn=a,a}(this,e,t))}off(e,t){return this._handlers=this._handlers.filter((r=>r.event!==e||r.handler!==t)),this}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i{"*"===t.event&&(a=!0,t.handler(e,...r)),t.event===e&&(a=!0,t.handler(...r))})),a}removeAllListeners(e){return e?(this._handlers=this._handlers.filter((t=>t.event!==e)),this):(this._handlers=[],this)}listenerCount(e){return this._handlers.filter((t=>t.event===e)).length}listeners(e){return this._handlers.reduce(((t,r)=>(r.event===e&&t.push(r.handler),t)),[])}eventNames(){return this._handlers.map((e=>e.event))}}let D=0,V=0;const O=(e,t)=>{if(!e||!t||e<=0||t<=0)return;V=(V*D+8*e/t)/++D},F={ERRORCODE:900,extensions:[]};class B extends S{constructor(){let{fetcher:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.maxWrapperDepth=null,this.remainingAds=[],this.fetcher=e||null}trackVastError(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a0&&void 0!==arguments[0]?arguments[0]:{};this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.rootURL="",this.resetParsingStatus(),O(e.byteLength,e.requestDuration)}resetParsingStatus(){this.errorURLTemplates=[],this.rootErrorURLTemplates=[],this.vastVersion=null}getRemainingAds(e){if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));const t=e?d.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.resolveAds(t,{wrapperDepth:0,url:this.rootURL}).then((e=>this.buildVASTResponse(e)))}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(t),t.isRootVAST=!0,this.parse(e,t).then((e=>this.buildVASTResponse(e)))}buildVASTResponse(e){const t=function(e){let{ads:t,errorURLTemplates:r,version:i}=e;return{ads:t||[],errorURLTemplates:r||[],version:i||null}}({ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion});return this.completeWrapperResolving(t),t}parseVastXml(e,t){let{isRootVAST:r=!1,url:i=null,wrapperDepth:a=0,allowMultipleAds:s,followAdditionalWrappers:n}=t;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName)throw this.emit("VAST-ad-parsed",{type:"ERROR",url:i,wrapperDepth:a}),new Error("Invalid VAST XMLDocument");const o=[],l=e.documentElement.childNodes,c=e.documentElement.getAttribute("version");r&&c&&(this.vastVersion=c);for(const e in l){const t=l[e];if("Error"===t.nodeName){const e=m.parseNodeText(t);r?this.rootErrorURLTemplates.push(e):this.errorURLTemplates.push(e)}else if("Ad"===t.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)s=!0;else if(!1===s&&o.length>1)break;const e=C(t,this.emit.bind(this),{allowMultipleAds:s,followAdditionalWrappers:n});e.ad?(o.push(e.ad),this.emit("VAST-ad-parsed",{type:e.type,url:i,wrapperDepth:a,adIndex:o.length-1,vastVersion:c})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return o}parse(e){let{url:t=null,resolveAll:r=!0,wrapperSequence:i=null,previousUrl:a=null,wrapperDepth:s=0,isRootVAST:n=!1,followAdditionalWrappers:o,allowMultipleAds:l}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},c=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&n&&(l=!0);try{c=this.parseVastXml(e,{isRootVAST:n,url:t,wrapperDepth:s,allowMultipleAds:l,followAdditionalWrappers:o})}catch(e){return Promise.reject(e)}return 1===c.length&&null!=i&&(c[0].sequence=i),!1===r&&(this.remainingAds=m.splitVAST(c),c=this.remainingAds.shift()),this.resolveAds(c,{wrapperDepth:s,previousUrl:a,url:t})}resolveAds(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],{wrapperDepth:t,previousUrl:r,url:i}=arguments.length>1?arguments[1]:void 0;const a=[];return r=i,e.forEach((e=>{const i=this.resolveWrappers(e,t,r);a.push(i)})),Promise.all(a).then((e=>d.flatten(e)))}resolveWrappers(e,t,r){const i={...e};return new Promise((e=>{var a;if(t++,!i.nextWrapperURL)return delete i.nextWrapperURL,e(i);if(!this.fetcher)return i.VASTAdTagURI=i.nextWrapperURL,delete i.nextWrapperURL,e(i);if(t>=this.maxWrapperDepth)return i.errorCode=302,delete i.nextWrapperURL,e(i);i.nextWrapperURL=m.resolveVastAdTagURI(i.nextWrapperURL,r);const s=null!==(a=this.parsingOptions.allowMultipleAds)&&void 0!==a?a:i.allowMultipleAds,n=i.sequence;this.fetcher.fetchVAST({url:i.nextWrapperURL,emitter:this.emit.bind(this),maxWrapperDepth:this.maxWrapperDepth}).then((a=>this.parse(a,{url:i.nextWrapperURL,previousUrl:r,wrapperSequence:n,wrapperDepth:t,followAdditionalWrappers:i.followAdditionalWrappers,allowMultipleAds:s}).then((t=>{if(delete i.nextWrapperURL,0===t.length)return i.creatives=[],e(i);t.forEach((e=>{e&&m.mergeWrapperAdData(e,i)})),e(t)})))).catch((t=>{i.errorCode=301,i.errorMessage=t.message,e(i)}))}))}completeWrapperResolving(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(let t=e.ads.length-1;t>=0;t--){const r=e.ads[t];!r.errorCode&&0!==r.creatives.length||r.VASTAdTagURI||(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}let P=null;const M={data:{},length:0,getItem(e){return this.data[e]},setItem(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem(e){delete this.data[e],this.length=Object.keys(this.data).length},clear(){this.data={},this.length=0}};class W{constructor(){this.storage=this.initStorage()}initStorage(){if(P)return P;try{P="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){P=null}return P&&!this.isStorageDisabled(P)||(P=M,P.clear()),P}isStorageDisabled(e){const t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}getItem(e){return this.storage.getItem(e)}setItem(e,t){return this.storage.setItem(e,t)}removeItem(e){return this.storage.removeItem(e)}clear(){return this.storage.clear()}}const j=12e4;const q={get:async function(e,t){try{const r=new AbortController,i=setTimeout((()=>{throw r.abort(),new Error("URLHandler: Request timed out after ".concat(t.timeout||j," ms (408)"))}),t.timeout||j),a=await fetch(e,{...t,signal:r.signal,credentials:t.withCredentials?"include":"omit"});clearTimeout(i);const s=function(e){return"https:"===window.location.protocol&&e.url.includes("http://")?"URLHandler: Cannot go from HTTPS to HTTP.":200===e.status&&e.ok?null:"URLHandler: ".concat(e.statusText," (").concat(e.status,")")}(a);return s?{error:new Error(s),statusCode:a.status}:async function(e){const t=await e.text();let r;r=d.isBrowserEnvironment()?new DOMParser:new((await import("@xmldom/xmldom")).DOMParser);return{xml:r.parseFromString(t,"text/xml"),details:{byteLength:t.length,statusCode:e.status,rawXml:t}}}(a)}catch(e){return{error:e,statusCode:"AbortError"===e.name?408:null}}}};class K{constructor(){this.URLTemplateFilters=[]}setOptions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.urlHandler=e.urlHandler||e.urlhandler||q,this.fetchingOptions={timeout:e.timeout||j,withCredentials:Boolean(e.withCredentials)}}addURLTemplateFilter(e){"function"==typeof e&&this.URLTemplateFilters.push(e)}removeLastURLTemplateFilter(){this.URLTemplateFilters.pop()}countURLTemplateFilters(){return this.URLTemplateFilters.length}clearURLTemplateFilters(){this.URLTemplateFilters=[]}async fetchVAST(e){var t;let{url:r,maxWrapperDepth:i,emitter:a,wrapperDepth:s=0,previousUrl:n=null,wrapperAd:o=null}=e;const l=Date.now();this.URLTemplateFilters.forEach((e=>{r=e(r)})),a("VAST-resolving",{url:r,previousUrl:n,wrapperDepth:s,maxWrapperDepth:i,timeout:this.fetchingOptions.timeout,wrapperAd:o});const c=await this.urlHandler.get(r,this.fetchingOptions),u=Math.round(Date.now()-l);if(a("VAST-resolved",{url:r,previousUrl:n,wrapperDepth:s,error:(null==c?void 0:c.error)||null,duration:u,statusCode:(null==c?void 0:c.statusCode)||null,...null==c?void 0:c.details}),O(null==c||null===(t=c.details)||void 0===t?void 0:t.byteLength,u),c.error)throw new Error(c.error);return c.xml}}class H{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new W;this.cappingFreeLunch=e,this.cappingMinimumTimeInterval=t,this.fetcher=new K,this.vastParser=new B({fetcher:this.fetcher}),this.storage=r,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}addURLTemplateFilter(e){this.fetcher.addURLTemplateFilter(e)}removeLastURLTemplateFilter(){this.fetcher.removeLastURLTemplateFilter()}countURLTemplateFilters(){return this.fetcher.countURLTemplateFilters()}clearURLTemplateFilters(){this.fetcher.clearURLTemplateFilters()}getParser(){return this.vastParser}get lastSuccessfulAd(){return this.storage.getItem("vast-client-last-successful-ad")}set lastSuccessfulAd(e){this.storage.setItem("vast-client-last-successful-ad",e)}get totalCalls(){return this.storage.getItem("vast-client-total-calls")}set totalCalls(e){this.storage.setItem("vast-client-total-calls",e)}get totalCallsTimeout(){return this.storage.getItem("vast-client-total-calls-timeout")}set totalCallsTimeout(e){this.storage.setItem("vast-client-total-calls-timeout",e)}hasRemainingAds(){return this.vastParser.remainingAds.length>0}getNextAds(e){return this.vastParser.getRemainingAds(e)}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.fetcher.setOptions(t),this.vastParser.parseVAST(e,t)}get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=Date.now();return t.hasOwnProperty("resolveAll")||(t.resolveAll=!1),this.totalCallsTimeout{if(this.cappingFreeLunch>=this.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(this.totalCalls,"/").concat(this.cappingFreeLunch)));const s=r-this.lastSuccessfulAd;if(s<0)this.lastSuccessfulAd=0;else if(s(t.previousUrl=e,t.isRootVAST=!0,t.url=e,this.vastParser.parse(r,t).then((e=>{const t=this.vastParser.buildVASTResponse(e);i(t)}))))).catch((e=>a(e)))}))}}class _ extends S{constructor(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),this.ad=t,this.creative=r,this.variation=i,this.muted=a,this.impressed=!1,this.skippable=!1,this.trackingEvents={},this.lastPercentage=0,this._alreadyTriggeredQuartiles={},this.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"];for(const e in this.creative.trackingEvents){const t=this.creative.trackingEvents[e];this.trackingEvents[e]=t.slice(0)}!function(e){return"linear"===e.type}(this.creative)?this._initVariationTracking():this._initLinearTracking(),e&&this.on("start",(()=>{e.lastSuccessfulAd=Date.now()}))}_initLinearTracking(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}_initVariationTracking(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(const e in this.variation.trackingEvents){const t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}setDuration(e){d.isValidTimeValue(e)?(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100}):this.emit("TRACKER-error",{message:"the duration provided is not valid. duration: ".concat(e)})}setProgress(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!d.isValidTimeValue(e)||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given setProgress parameter has the wrong type. progress: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});const i=this.skipDelay||-1;if(-1===i||this.skippable||(i>e?this.emit("skip-countdown",i-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){const i=Math.round(e/this.assetDuration*100),a=[];if(e>0){a.push("start");for(let e=this.lastPercentage;e{this.track(e,{macros:t,once:r})})),e1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e):this.emit("TRACKER-error",{message:"One given setMuted parameter has the wrong type. muted: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setPaused(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e):this.emit("TRACKER-error",{message:"One given setPaused parameter has the wrong type. paused: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setFullscreen(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e):this.emit("TRACKER-error",{message:"One given setFullScreen parameter has the wrong type. fullscreen: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setExpand(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e):this.emit("TRACKER-error",{message:"One given setExpand parameter has the wrong type. expanded: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}setSkipDelay(e){d.isValidTimeValue(e)?this.skipDelay=e:this.emit("TRACKER-error",{message:"setSkipDelay parameter does not have a valid value. duration: ".concat(e)})}trackImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})):this.emit("TRACKER-error",{message:"trackImpression parameter has the wrong type. macros: ".concat(e)})}trackViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewable,e)})):this.emit("TRACKER-error",{message:"trackViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackNotViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.notViewable,e)})):this.emit("TRACKER-error",{message:"trackNotViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackUndeterminedImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewUndetermined,e)})):this.emit("TRACKER-error",{message:"trackUndeterminedImpression given macros has the wrong type. macros: ".concat(e)})}error(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"==typeof e&&"boolean"==typeof t?this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t}):this.emit("TRACKER-error",{message:"One given error parameter has the wrong type. macros: ".concat(d.formatMacrosValues(e),", isCustomCode: ").concat(t)})}errorWithCode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t?(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead")):this.emit("TRACKER-error",{message:"One given errorWithCode parameter has the wrong type. errorCode: ".concat(e,", isCustomCode: ").concat(t)})}complete(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("complete",{macros:e}):this.emit("TRACKER-error",{message:"complete given macros has the wrong type. macros: ".concat(e)})}notUsed(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?(this.track("notUsed",{macros:e}),this.trackingEvents=[]):this.emit("TRACKER-error",{message:"notUsed given macros has the wrong type. macros: ".concat(e)})}otherAdInteraction(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("otherAdInteraction",{macros:e}):this.emit("TRACKER-error",{message:"otherAdInteraction given macros has the wrong type. macros: ".concat(e)})}acceptInvitation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("acceptInvitation",{macros:e}):this.emit("TRACKER-error",{message:"acceptInvitation given macros has the wrong type. macros: ".concat(e)})}adExpand(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adExpand",{macros:e}):this.emit("TRACKER-error",{message:"adExpand given macros has the wrong type. macros: ".concat(e)})}adCollapse(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adCollapse",{macros:e}):this.emit("TRACKER-error",{message:"adCollapse given macros has the wrong type. macros: ".concat(e)})}minimize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("minimize",{macros:e}):this.emit("TRACKER-error",{message:"minimize given macros has the wrong type. macros: ".concat(e)})}verificationNotExecuted(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given verificationNotExecuted parameter has to wrong type. vendor: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");const r=this.ad.adVerifications.find((t=>t.vendor===e));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));const i=r.trackingEvents;if(i&&i.verificationNotExecuted){const e=i.verificationNotExecuted;this.trackURLs(e,t),this.emit("verificationNotExecuted",{trackingURLTemplates:e})}}overlayViewDuration(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"==typeof t?(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t})):this.emit("TRACKER-error",{message:"One given overlayViewDuration parameters has the wrong type. formattedDuration: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))})}close(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track(this.linear?"closeLinear":"close",{macros:e}):this.emit("TRACKER-error",{message:"close given macros has the wrong type. macros: ".concat(e)})}skip(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("skip",{macros:e}):this.emit("TRACKER-error",{message:"skip given macros has the wrong type. macros: ".concat(e)})}load(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("loaded",{macros:e}):this.emit("TRACKER-error",{message:"load given macros has the wrong type. macros: ".concat(e)})}click(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!==e&&"string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given click parameter has the wrong type. fallbackClickThroughURL: ".concat(e,", macros: ").concat(d.formatMacrosValues(t))});this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);const r=this.clickThroughURLTemplate||e,i={...t};if(r){this.progress&&(i.ADPLAYHEAD=this.progressFormatted());const e=d.resolveURLTemplates([r],i)[0];this.emit("clickthrough",e)}}track(e){let{macros:t={},once:r=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"!=typeof t)return void this.emit("TRACKER-error",{message:"track given macros has the wrong type. macros: ".concat(t)});"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");const i=this.trackingEvents[e],a=this.emitAlwaysEvents.indexOf(e)>-1;i?(this.emit(e,{trackingURLTemplates:i}),this.trackURLs(i,t)):a&&this.emit(e,null),r&&(delete this.trackingEvents[e],a&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}trackURLs(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{validUrls:a,invalidUrls:s}=d.filterUrlTemplates(e);s.length&&this.emit("TRACKER-error",{message:"Provided urls are malformed. url: ".concat(s)});const n={...r};this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(n.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(n.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(t=t.universalAdIds)&&void 0!==t&&t.length&&(n.UNIVERSALADID=this.creative.universalAdIds.map((e=>e.idRegistry.concat(" ",e.value))).join(",")),this.ad&&(this.ad.sequence&&(n.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(n.ADTYPE=this.ad.adType),this.ad.adServingId&&(n.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(n.ADCATEGORIES=this.ad.categories.map((e=>e.value)).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(n.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories.map((e=>e.value)).join(","))),d.track(a,n,i)}convertToTimecode(e){if(!d.isValidTimeValue(e))return"";const t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),a=Math.floor(t/1e3%60),s=Math.floor(t%1e3);return"".concat(d.addLeadingZeros(r,2),":").concat(d.addLeadingZeros(i,2),":").concat(d.addLeadingZeros(a,2),".").concat(d.addLeadingZeros(s,3))}progressFormatted(){return this.convertToTimecode(this.progress)}}export{H as VASTClient,B as VASTParser,_ as VASTTracker,p as parseDuration}; +function e(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adId:e.adId||null,sequence:e.sequence||null,apiFramework:e.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}const t=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REGULATIONS","SERVERSIDE","SERVERUA","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"];function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const a=[],n=s(e);!t.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(t.ERRORCODE)||(t.ERRORCODE=900),t.CACHEBUSTING=d(Math.round(1e8*Math.random())),t.TIMESTAMP=(new Date).toISOString(),t.RANDOM=t.random=t.CACHEBUSTING;for(const e in t)t[e]=c(t[e]);for(const e in n){const r=n[e];"string"==typeof r&&a.push(i(r,t))}return a}function i(e,r){const i=(e=a(e,r)).match(/[^[\]]+(?=])/g);if(!i)return e;let s=i.filter((e=>t.indexOf(e)>-1));return 0===s.length?e:(s=s.reduce(((e,t)=>(e[t]=-1,e)),{}),a(e,s))}function a(e,t){let r=e;for(const e in t){const i=t[e];r=r.replace(new RegExp("(?:\\[|%%)(".concat(e,")(?:\\]|%%)"),"g"),i)}return r}function s(e){return Array.isArray(e)?e.map((e=>e&&e.hasOwnProperty("url")?e.url:e)):e}function n(e){return/^(https?:\/\/|\/\/)/.test(e)}function o(e,t){for(let r=0;r"%".concat(e.charCodeAt(0).toString(16))))}function d(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8;return e.toString().padStart(t,"0")}const u={track:function(e,t,i){r(e,t,i).forEach((e=>{if("undefined"!=typeof window&&null!==window){(new Image).src=e}}))},resolveURLTemplates:r,extractURLsFromTemplates:s,filterUrlTemplates:function(e){return e.reduce(((e,t)=>{const r=t.url||t;return n(r)?e.validUrls.push(r):e.invalidUrls.push(r),e}),{validUrls:[],invalidUrls:[]})},containsTemplateObject:o,isTemplateObjectEqual:l,encodeURIComponentRFC3986:c,replaceUrlMacros:i,isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},flatten:function e(t){return t.reduce(((t,r)=>t.concat(Array.isArray(r)?e(r):r)),[])},joinArrayOfUniqueTemplateObjs:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];return r.concat(i).reduce(((e,t)=>(o(t,e)||e.push(t),e)),[])},isValidTimeValue:function(e){return Number.isFinite(e)&&e>=-2},addLeadingZeros:d,isValidUrl:n,isBrowserEnvironment:function(){return"undefined"!=typeof window},formatMacrosValues:function(e){return"object"!=typeof e?e:JSON.stringify(e)}};function h(e){return["true","TRUE","True","1"].includes(e)}function p(e){if(null==e)return-1;if(u.isNumeric(e))return parseInt(e);const t=e.split(":");if(3!==t.length)return-1;const r=t[2].split(".");let i=parseInt(r[0]);2===r.length&&(i+=parseFloat("0.".concat(r[1])));const a=parseInt(60*t[1]),s=parseInt(60*t[0]*60);return isNaN(s)||isNaN(a)||isNaN(i)||a>3600||i>60?-1:s+a+i}const m={childByName:function(e,t){return Array.from(e.childNodes).find((e=>e.nodeName===t))},childrenByName:function(e,t){return Array.from(e.childNodes).filter((e=>e.nodeName===t))},resolveVastAdTagURI:function(e,t){if(!t)return e;if(e.startsWith("//")){const{protocol:t}=location;return"".concat(t).concat(e)}if(!e.includes("://")){const r=t.slice(0,t.lastIndexOf("/"));return"".concat(r,"/").concat(e)}return e},parseBoolean:h,parseNodeText:function(e){return e&&(e.textContent||e.text||"").trim()},copyNodeAttribute:function(e,t,r){const i=t.getAttribute(e);i&&r.setAttribute(e,i)},parseAttributes:function(e){return Array.from(e.attributes).reduce(((e,t)=>(e[t.nodeName]=t.nodeValue,e)),{})},parseDuration:p,splitVAST:function(e){const t=[];let r=null;return e.forEach(((i,a)=>{if(i.sequence&&(i.sequence=parseInt(i.sequence,10)),i.sequence>1){const t=e[a-1];if(t&&t.sequence===i.sequence-1)return void(r&&r.push(i));delete i.sequence}r=[i],t.push(r)})),t},assignAttributes:function(e,t){e&&Array.from(e).forEach((e=>{let{nodeName:r,nodeValue:i}=e;if(r&&i&&t.hasOwnProperty(r)){let e=i;"boolean"==typeof t[r]&&(e=h(e)),t[r]=e}}))},mergeWrapperAdData:function(e,t){var r;e.errorURLTemplates=t.errorURLTemplates.concat(e.errorURLTemplates),e.impressionURLTemplates=t.impressionURLTemplates.concat(e.impressionURLTemplates),e.extensions=t.extensions.concat(e.extensions),t.viewableImpression.length>0&&(e.viewableImpression=[...e.viewableImpression,...t.viewableImpression]),e.followAdditionalWrappers=t.followAdditionalWrappers,e.allowMultipleAds=t.allowMultipleAds,e.fallbackOnNoAd=t.fallbackOnNoAd;const i=(t.creatives||[]).filter((e=>e&&"companion"===e.type)),a=i.reduce(((e,t)=>((t.variations||[]).forEach((t=>{(t.companionClickTrackingURLTemplates||[]).forEach((t=>{u.containsTemplateObject(t,e)||e.push(t)}))})),e)),[]);e.creatives=i.concat(e.creatives);const s=t.videoClickTrackingURLTemplates&&t.videoClickTrackingURLTemplates.length,n=t.videoCustomClickURLTemplates&&t.videoCustomClickURLTemplates.length;if(e.creatives.forEach((e=>{if(t.trackingEvents&&t.trackingEvents[e.type])for(const r in t.trackingEvents[e.type]){const i=t.trackingEvents[e.type][r];Array.isArray(e.trackingEvents[r])||(e.trackingEvents[r]=[]),e.trackingEvents[r]=e.trackingEvents[r].concat(i)}"linear"===e.type&&(s&&(e.videoClickTrackingURLTemplates=e.videoClickTrackingURLTemplates.concat(t.videoClickTrackingURLTemplates)),n&&(e.videoCustomClickURLTemplates=e.videoCustomClickURLTemplates.concat(t.videoCustomClickURLTemplates)),!t.videoClickThroughURLTemplate||null!==e.videoClickThroughURLTemplate&&void 0!==e.videoClickThroughURLTemplate||(e.videoClickThroughURLTemplate=t.videoClickThroughURLTemplate)),"companion"===e.type&&a.length&&(e.variations||[]).forEach((e=>{e.companionClickTrackingURLTemplates=u.joinArrayOfUniqueTemplateObjs(e.companionClickTrackingURLTemplates,a)}))})),t.adVerifications&&(e.adVerifications=e.adVerifications.concat(t.adVerifications)),t.blockedAdCategories&&(e.blockedAdCategories=e.blockedAdCategories.concat(t.blockedAdCategories)),null!==(r=t.creatives)&&void 0!==r&&r.length){const r=t.creatives.filter((e=>{var t;return(null===(t=e.icons)||void 0===t?void 0:t.length)&&!e.mediaFiles.length}));r.length&&(e.creatives=e.creatives.concat(r))}}};function g(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"companion",required:null,variations:[]}}(r);return i.required=t.getAttribute("required")||null,i.variations=m.childrenByName(t,"Companion").map((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,adType:"companionAd",width:e.width||0,height:e.height||0,assetWidth:e.assetWidth||null,assetHeight:e.assetHeight||null,expandedWidth:e.expandedWidth||null,expandedHeight:e.expandedHeight||null,apiFramework:e.apiFramework||null,adSlotId:e.adSlotId||null,pxratio:e.pxratio||"1",renderingMode:e.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(m.parseAttributes(e));t.htmlResources=m.childrenByName(e,"HTMLResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.iframeResources=m.childrenByName(e,"IFrameResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat(r):e}),[]),t.staticResources=m.childrenByName(e,"StaticResource").reduce(((e,t)=>{const r=m.parseNodeText(t);return r?e.concat({url:r,creativeType:t.getAttribute("creativeType")||null}):e}),[]),t.altText=m.parseNodeText(m.childByName(e,"AltText"))||null;const r=m.childByName(e,"TrackingEvents");r&&m.childrenByName(r,"Tracking").forEach((e=>{const r=e.getAttribute("event"),i=m.parseNodeText(e);r&&i&&(Array.isArray(t.trackingEvents[r])||(t.trackingEvents[r]=[]),t.trackingEvents[r].push(i))})),t.companionClickTrackingURLTemplates=m.childrenByName(e,"CompanionClickTracking").map((e=>({id:e.getAttribute("id")||null,url:m.parseNodeText(e)}))),t.companionClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"CompanionClickThrough"))||null;const i=m.childByName(e,"AdParameters");return i&&(t.adParameters={value:m.parseNodeText(i),xmlEncoded:i.getAttribute("xmlEncoded")||null}),t})),i}function v(t,r){let i;const a=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(r);a.duration=m.parseDuration(m.parseNodeText(m.childByName(t,"Duration")));const s=t.getAttribute("skipoffset");if(null==s)a.skipDelay=null;else if("%"===s.charAt(s.length-1)&&-1!==a.duration){const e=parseInt(s,10);a.skipDelay=a.duration*(e/100)}else a.skipDelay=m.parseDuration(s);const n=m.childByName(t,"VideoClicks");if(n){const e=m.childByName(n,"ClickThrough");a.videoClickThroughURLTemplate=e?{id:e.getAttribute("id")||null,url:m.parseNodeText(e)}:null,m.childrenByName(n,"ClickTracking").forEach((e=>{a.videoClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),m.childrenByName(n,"CustomClick").forEach((e=>{a.videoCustomClickURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}))}const o=m.childByName(t,"AdParameters");o&&(a.adParameters={value:m.parseNodeText(o),xmlEncoded:o.getAttribute("xmlEncoded")||null}),m.childrenByName(t,"TrackingEvents").forEach((e=>{m.childrenByName(e,"Tracking").forEach((e=>{let t=e.getAttribute("event");const r=m.parseNodeText(e);if(t&&r){if("progress"===t){if(i=e.getAttribute("offset"),!i)return;t="%"===i.charAt(i.length-1)?"progress-".concat(i):"progress-".concat(Math.round(m.parseDuration(i)))}Array.isArray(a.trackingEvents[t])||(a.trackingEvents[t]=[]),a.trackingEvents[t].push(r)}}))})),m.childrenByName(t,"MediaFiles").forEach((e=>{m.childrenByName(e,"MediaFile").forEach((e=>{a.mediaFiles.push(function(e){const t={id:null,fileURL:null,fileSize:0,deliveryType:"progressive",mimeType:null,mediaType:null,codec:null,bitrate:0,minBitrate:0,maxBitrate:0,width:0,height:0,apiFramework:null,scalable:null,maintainAspectRatio:null};t.id=e.getAttribute("id"),t.fileURL=m.parseNodeText(e),t.deliveryType=e.getAttribute("delivery"),t.codec=e.getAttribute("codec"),t.mimeType=e.getAttribute("type"),t.mediaType=e.getAttribute("mediaType")||"2D",t.apiFramework=e.getAttribute("apiFramework"),t.fileSize=parseInt(e.getAttribute("fileSize")||0),t.bitrate=parseInt(e.getAttribute("bitrate")||0),t.minBitrate=parseInt(e.getAttribute("minBitrate")||0),t.maxBitrate=parseInt(e.getAttribute("maxBitrate")||0),t.width=parseInt(e.getAttribute("width")||0),t.height=parseInt(e.getAttribute("height")||0);const r=e.getAttribute("scalable");r&&"string"==typeof r&&(t.scalable=m.parseBoolean(r));const i=e.getAttribute("maintainAspectRatio");i&&"string"==typeof i&&(t.maintainAspectRatio=m.parseBoolean(i));return t}(e))}));const t=m.childByName(e,"InteractiveCreativeFile");t&&(a.interactiveCreativeFile=function(e){const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,apiFramework:e.apiFramework||null,variableDuration:m.parseBoolean(e.variableDuration),fileURL:null}}(m.parseAttributes(e));return t.fileURL=m.parseNodeText(e),t}(t));const r=m.childByName(e,"ClosedCaptionFiles");r&&m.childrenByName(r,"ClosedCaptionFile").forEach((e=>{const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:e.type||null,language:e.language||null,fileURL:null}}(m.parseAttributes(e));t.fileURL=m.parseNodeText(e),a.closedCaptionFiles.push(t)}));const i=m.childByName(e,"Mezzanine"),s=function(e,t){const r={};let i=!1;return t.forEach((t=>{e&&e.getAttribute(t)?r[t]=e.getAttribute(t):i=!0})),i?null:r}(i,["delivery","type","width","height"]);if(s){const e={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};e.id=i.getAttribute("id"),e.fileURL=m.parseNodeText(i),e.delivery=s.delivery,e.codec=i.getAttribute("codec"),e.type=s.type,e.width=parseInt(s.width,10),e.height=parseInt(s.height,10),e.fileSize=parseInt(i.getAttribute("fileSize"),10),e.mediaType=i.getAttribute("mediaType")||"2D",a.mezzanine=e}}));const l=m.childByName(t,"Icons");return l&&m.childrenByName(l,"Icon").forEach((e=>{a.icons.push(function(e){const t={program:null,height:0,width:0,xPosition:0,yPosition:0,apiFramework:null,offset:null,duration:0,type:null,staticResource:null,htmlResource:null,iframeResource:null,pxratio:"1",iconClickThroughURLTemplate:null,iconClickTrackingURLTemplates:[],iconViewTrackingURLTemplate:null,iconClickFallbackImages:[]};t.program=e.getAttribute("program"),t.height=parseInt(e.getAttribute("height")||0),t.width=parseInt(e.getAttribute("width")||0),t.xPosition=function(e){if(-1!==["left","right"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("xPosition")),t.yPosition=function(e){if(-1!==["top","bottom"].indexOf(e))return e;return parseInt(e||0)}(e.getAttribute("yPosition")),t.apiFramework=e.getAttribute("apiFramework"),t.pxratio=e.getAttribute("pxratio")||"1",t.offset=m.parseDuration(e.getAttribute("offset")),t.duration=m.parseDuration(e.getAttribute("duration")),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"IconClicks");if(r){t.iconClickThroughURLTemplate=m.parseNodeText(m.childByName(r,"IconClickThrough")),m.childrenByName(r,"IconClickTracking").forEach((e=>{t.iconClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})}));const e=m.childByName(r,"IconClickFallbackImages");e&&m.childrenByName(e,"IconClickFallbackImage").forEach((e=>{t.iconClickFallbackImages.push({url:m.parseNodeText(e)||null,width:e.getAttribute("width")||null,height:e.getAttribute("height")||null})}))}return t.iconViewTrackingURLTemplate=m.parseNodeText(m.childByName(e,"IconViewTracking")),t}(e))})),a}function f(t,r){const i=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{id:r,adId:i,sequence:a,apiFramework:s}=e(t);return{id:r,adId:i,sequence:a,apiFramework:s,type:"nonlinear",variations:[],trackingEvents:{}}}(r);return m.childrenByName(t,"TrackingEvents").forEach((e=>{let t,r;m.childrenByName(e,"Tracking").forEach((e=>{t=e.getAttribute("event"),r=m.parseNodeText(e),t&&r&&(Array.isArray(i.trackingEvents[t])||(i.trackingEvents[t]=[]),i.trackingEvents[t].push(r))}))})),m.childrenByName(t,"NonLinear").forEach((e=>{const t={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};t.id=e.getAttribute("id")||null,t.width=e.getAttribute("width"),t.height=e.getAttribute("height"),t.expandedWidth=e.getAttribute("expandedWidth"),t.expandedHeight=e.getAttribute("expandedHeight"),t.scalable=m.parseBoolean(e.getAttribute("scalable")),t.maintainAspectRatio=m.parseBoolean(e.getAttribute("maintainAspectRatio")),t.minSuggestedDuration=m.parseDuration(e.getAttribute("minSuggestedDuration")),t.apiFramework=e.getAttribute("apiFramework"),m.childrenByName(e,"HTMLResource").forEach((e=>{t.type=e.getAttribute("creativeType")||"text/html",t.htmlResource=m.parseNodeText(e)})),m.childrenByName(e,"IFrameResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.iframeResource=m.parseNodeText(e)})),m.childrenByName(e,"StaticResource").forEach((e=>{t.type=e.getAttribute("creativeType")||0,t.staticResource=m.parseNodeText(e)}));const r=m.childByName(e,"AdParameters");r&&(t.adParameters={value:m.parseNodeText(r),xmlEncoded:r.getAttribute("xmlEncoded")||null}),t.nonlinearClickThroughURLTemplate=m.parseNodeText(m.childByName(e,"NonLinearClickThrough")),m.childrenByName(e,"NonLinearClickTracking").forEach((e=>{t.nonlinearClickTrackingURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)})})),i.variations.push(t)})),i}function T(e){const t=[];return e.forEach((e=>{const r=A(e);r&&t.push(r)})),t}function A(e){if("#comment"===e.nodeName)return null;const t={name:null,value:null,attributes:{},children:[]},r=e.attributes,i=e.childNodes;if(t.name=e.nodeName,e.attributes)for(const e in r)if(r.hasOwnProperty(e)){const i=r[e];i.nodeName&&i.nodeValue&&(t.attributes[i.nodeName]=i.nodeValue)}for(const e in i)if(i.hasOwnProperty(e)){const r=A(i[e]);r&&t.children.push(r)}if(0===t.children.length||1===t.children.length&&["#cdata-section","#text"].indexOf(t.children[0].name)>=0){const r=m.parseNodeText(e);""!==r&&(t.value=r),t.children=[]}return null===(a=t).value&&0===Object.keys(a.attributes).length&&0===a.children.length?null:t;var a}function R(e){return e.getAttribute("AdID")||e.getAttribute("adID")||e.getAttribute("adId")||null}const y={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function k(e,t){if(!y[e.nodeName]||!y[e.nodeName].attributes)return;const r=y[e.nodeName].attributes.filter((t=>!e.getAttribute(t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,attributes:r},t)}function E(e,t,r){const i=y[e.nodeName],a=!r&&"Wrapper"!==e.nodeName;if(!i||a)return;if(i.subElements){const r=i.subElements.filter((t=>!m.childByName(e,t)));r.length>0&&N({name:e.nodeName,parentName:e.parentNode.nodeName,subElements:r},t)}if(!r||!i.oneOfinLineResources)return;i.oneOfinLineResources.some((t=>m.childByName(e,t)))||N({name:e.nodeName,parentName:e.parentNode.nodeName,oneOfResources:i.oneOfinLineResources},t)}function b(e){return e.children&&0!==e.children.length}function N(e,t){let{name:r,parentName:i,attributes:a,subElements:s,oneOfResources:n}=e,o="Element '".concat(r,"'");o+=a?" missing required attribute(s) '".concat(a.join(", "),"' "):s?" missing required sub element(s) '".concat(s.join(", "),"' "):n?" must provide one of the following '".concat(n.join(", "),"' "):" is empty",t("VAST-warning",{message:o,parentElement:i,specVersion:4.1})}const w={verifyRequiredValues:function e(t,r,i){if(t&&t.nodeName)if("InLine"===t.nodeName&&(i=!0),k(t,r),b(t)){E(t,r,i);for(let a=0;a2&&void 0!==arguments[2]?arguments[2]:{};const a=Array.from(e.childNodes).filter((e=>{const t=e.nodeName.toLowerCase();return"inline"===t||!1!==i&&"wrapper"===t}));for(const i of a){if(m.copyNodeAttribute("id",e,i),m.copyNodeAttribute("sequence",e,i),m.copyNodeAttribute("adType",e,i),"Wrapper"===i.nodeName)return{ad:I(i,t),type:"WRAPPER"};if("InLine"===i.nodeName)return{ad:C(i,t,{allowMultipleAds:r}),type:"INLINE"};const a=i.nodeName.toLowerCase();t("VAST-warning",{message:"<".concat(i.nodeName,"inline"===a?"> must be written ":"> must be written "),wrongNode:i})}}function C(e,t){let{allowMultipleAds:r}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return!1===r&&e.getAttribute("sequence")?null:U(e,t)}function U(e,t){let r=[];t&&w.verifyRequiredValues(e,t);const i=Array.from(e.childNodes),a=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{id:e.id||null,sequence:e.sequence||null,adType:e.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(m.parseAttributes(e));return i.forEach((e=>{switch(e.nodeName){case"Error":a.errorURLTemplates.push(m.parseNodeText(e));break;case"Impression":a.impressionURLTemplates.push({id:e.getAttribute("id")||null,url:m.parseNodeText(e)});break;case"Creatives":a.creatives=function(e){const t=[];return e.forEach((e=>{const r={id:e.getAttribute("id")||null,adId:R(e),sequence:e.getAttribute("sequence")||null,apiFramework:e.getAttribute("apiFramework")||null},i=[];let a;m.childrenByName(e,"UniversalAdId").forEach((e=>{const t={idRegistry:e.getAttribute("idRegistry")||"unknown",value:m.parseNodeText(e)};i.push(t)}));const s=m.childByName(e,"CreativeExtensions");s&&(a=T(m.childrenByName(s,"CreativeExtension")));for(const s in e.childNodes){const n=e.childNodes[s];let o;switch(n.nodeName){case"Linear":o=v(n,r);break;case"NonLinearAds":o=f(n,r);break;case"CompanionAds":o=g(n,r)}o&&(i&&(o.universalAdIds=i),a&&(o.creativeExtensions=a),t.push(o))}})),t}(m.childrenByName(e,"Creative"));break;case"Extensions":{const t=m.childrenByName(e,"Extension");a.extensions=T(t),a.adVerifications.length||(r=function(e){let t=null,r=[];e.some((e=>t=m.childByName(e,"AdVerifications"))),t&&(r=x(m.childrenByName(t,"Verification")));return r}(t));break}case"AdVerifications":a.adVerifications=x(m.childrenByName(e,"Verification"));break;case"AdSystem":a.system={value:m.parseNodeText(e),version:e.getAttribute("version")||null};break;case"AdTitle":a.title=m.parseNodeText(e);break;case"AdServingId":a.adServingId=m.parseNodeText(e);break;case"Category":a.categories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)});break;case"Expires":a.expires=parseInt(m.parseNodeText(e),10);break;case"ViewableImpression":a.viewableImpression.push(function(e){const t=(e,t)=>{const r=m.parseNodeText(t);return r&&e.push(r),e};return{id:e.getAttribute("id")||null,viewable:m.childrenByName(e,"Viewable").reduce(t,[]),notViewable:m.childrenByName(e,"NotViewable").reduce(t,[]),viewUndetermined:m.childrenByName(e,"ViewUndetermined").reduce(t,[])}}(e));break;case"Description":a.description=m.parseNodeText(e);break;case"Advertiser":a.advertiser={id:e.getAttribute("id")||null,value:m.parseNodeText(e)};break;case"Pricing":a.pricing={value:m.parseNodeText(e),model:e.getAttribute("model")||null,currency:e.getAttribute("currency")||null};break;case"Survey":a.survey={value:m.parseNodeText(e),type:e.getAttribute("type")||null};break;case"BlockedAdCategories":a.blockedAdCategories.push({authority:e.getAttribute("authority")||null,value:m.parseNodeText(e)})}})),r.length&&(a.adVerifications=a.adVerifications.concat(r)),a}function I(e,t){const r=U(e,t),i=e.getAttribute("followAdditionalWrappers"),a=e.getAttribute("allowMultipleAds"),s=e.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!i||m.parseBoolean(i),r.allowMultipleAds=!!a&&m.parseBoolean(a),r.fallbackOnNoAd=s?m.parseBoolean(s):null;let n=m.childByName(e,"VASTAdTagURI");if(n?r.nextWrapperURL=m.parseNodeText(n):(n=m.childByName(e,"VASTAdTagURL"),n&&(r.nextWrapperURL=m.parseNodeText(m.childByName(n,"URL")))),r.creatives.forEach((e=>{if(["linear","nonlinear"].includes(e.type)){if(e.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[e.type]||(r.trackingEvents[e.type]={});for(const t in e.trackingEvents){const i=e.trackingEvents[t];Array.isArray(r.trackingEvents[e.type][t])||(r.trackingEvents[e.type][t]=[]),i.forEach((i=>{r.trackingEvents[e.type][t].push(i)}))}}e.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),e.videoClickTrackingURLTemplates.forEach((e=>{r.videoClickTrackingURLTemplates.push(e)}))),e.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate),e.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),e.videoCustomClickURLTemplates.forEach((e=>{r.videoCustomClickURLTemplates.push(e)})))}})),r.nextWrapperURL)return r}function x(e){const t=[];return e.forEach((e=>{const r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=Array.from(e.childNodes);m.assignAttributes(e.attributes,r),i.forEach((e=>{let{nodeName:t,textContent:i,attributes:a}=e;switch(t){case"JavaScriptResource":case"ExecutableResource":r.resource=i.trim(),m.assignAttributes(a,r);break;case"VerificationParameters":r.parameters=i.trim()}}));const a=m.childByName(e,"TrackingEvents");a&&m.childrenByName(a,"Tracking").forEach((e=>{const t=e.getAttribute("event"),i=m.parseNodeText(e);t&&i&&(Array.isArray(r.trackingEvents[t])||(r.trackingEvents[t]=[]),r.trackingEvents[t].push(i))})),t.push(r)})),t}class S{constructor(){this._handlers=[]}on(e,t){if("function"!=typeof t)throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof t));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(typeof e));return this._handlers.push({event:e,handler:t}),this}once(e,t){return this.on(e,function(e,t,r){const i={fired:!1,wrapFn:void 0};function a(){i.fired||(e.off(t,i.wrapFn),i.fired=!0,r.bind(e)(...arguments))}return i.wrapFn=a,a}(this,e,t))}off(e,t){return this._handlers=this._handlers.filter((r=>r.event!==e||r.handler!==t)),this}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i{"*"===t.event&&(a=!0,t.handler(e,...r)),t.event===e&&(a=!0,t.handler(...r))})),a}removeAllListeners(e){return e?(this._handlers=this._handlers.filter((t=>t.event!==e)),this):(this._handlers=[],this)}listenerCount(e){return this._handlers.filter((t=>t.event===e)).length}listeners(e){return this._handlers.reduce(((t,r)=>(r.event===e&&t.push(r.handler),t)),[])}eventNames(){return this._handlers.map((e=>e.event))}}let D=0,V=0;const O=(e,t)=>{if(!e||!t||e<=0||t<=0)return;V=(V*D+8*e/t)/++D},F={ERRORCODE:900,extensions:[]},B="VAST response version not supported";class P extends S{constructor(){let{fetcher:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.maxWrapperDepth=null,this.rootErrorURLTemplates=[],this.errorURLTemplates=[],this.remainingAds=[],this.parsingOptions={},this.fetcher=e||null}trackVastError(e,t){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a0&&void 0!==arguments[0]?arguments[0]:{};this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.rootURL="",this.resetParsingStatus(),O(e.byteLength,e.requestDuration)}resetParsingStatus(){this.errorURLTemplates=[],this.rootErrorURLTemplates=[],this.vastVersion=null}getRemainingAds(e){if(0===this.remainingAds.length)return Promise.reject(new Error("No more ads are available for the given VAST"));const t=e?u.flatten(this.remainingAds):this.remainingAds.shift();return this.errorURLTemplates=[],this.resolveAds(t,{wrapperDepth:0,url:this.rootURL}).then((e=>this.buildVASTResponse(e)))}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initParsingStatus(t),t.isRootVAST=!0,this.parse(e,t).then((e=>this.buildVASTResponse(e)))}buildVASTResponse(e){const t=function(e){let{ads:t,errorURLTemplates:r,version:i}=e;return{ads:t||[],errorURLTemplates:r||[],version:i||null}}({ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion});return this.completeWrapperResolving(t),t}parseVastXml(e,t){let{isRootVAST:r=!1,url:i=null,wrapperDepth:a=0,allowMultipleAds:s,followAdditionalWrappers:n}=t;if(!e||!e.documentElement||"VAST"!==e.documentElement.nodeName){var o;this.emit("VAST-ad-parsed",{type:"ERROR",url:i,wrapperDepth:a});const t="VideoAdServingTemplate"===(null==e||null===(o=e.documentElement)||void 0===o?void 0:o.nodeName);throw new Error(t?B:"Invalid VAST XMLDocument")}const l=[],c=e.documentElement.childNodes,d=e.documentElement.getAttribute("version");r&&d&&(this.vastVersion=d);for(const e in c){const t=c[e];if("Error"===t.nodeName){const e=m.parseNodeText(t);r?this.rootErrorURLTemplates.push(e):this.errorURLTemplates.push(e)}else if("Ad"===t.nodeName){if(this.vastVersion&&parseFloat(this.vastVersion)<3)s=!0;else if(!1===s&&l.length>1)break;const e=L(t,this.emit.bind(this),{allowMultipleAds:s,followAdditionalWrappers:n});e.ad?(l.push(e.ad),this.emit("VAST-ad-parsed",{type:e.type,url:i,wrapperDepth:a,adIndex:l.length-1,vastVersion:d})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return l}parse(e){let{url:t=null,resolveAll:r=!0,wrapperSequence:i=null,previousUrl:a=null,wrapperDepth:s=0,isRootVAST:n=!1,followAdditionalWrappers:o,allowMultipleAds:l}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},c=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&n&&(l=!0);try{c=this.parseVastXml(e,{isRootVAST:n,url:t,wrapperDepth:s,allowMultipleAds:l,followAdditionalWrappers:o})}catch(e){return Promise.reject(e)}return 1===c.length&&null!=i&&(c[0].sequence=i),!1===r&&(this.remainingAds=m.splitVAST(c),c=this.remainingAds.shift()),this.resolveAds(c,{wrapperDepth:s,previousUrl:a,url:t})}resolveAds(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],{wrapperDepth:t,previousUrl:r,url:i}=arguments.length>1?arguments[1]:void 0;const a=[];return r=i,e.forEach((e=>{const i=this.resolveWrappers(e,t,r);a.push(i)})),Promise.all(a).then((e=>u.flatten(e)))}resolveWrappers(e,t,r){const i={...e};return new Promise((e=>{var a;if(t++,!i.nextWrapperURL)return delete i.nextWrapperURL,e(i);if(!this.fetcher)return i.VASTAdTagURI=i.nextWrapperURL,delete i.nextWrapperURL,e(i);if(t>=this.maxWrapperDepth)return i.errorCode=302,delete i.nextWrapperURL,e(i);i.nextWrapperURL=m.resolveVastAdTagURI(i.nextWrapperURL,r);const s=null!==(a=this.parsingOptions.allowMultipleAds)&&void 0!==a?a:i.allowMultipleAds,n=i.sequence;this.fetcher.fetchVAST({url:i.nextWrapperURL,emitter:this.emit.bind(this),maxWrapperDepth:this.maxWrapperDepth}).then((a=>this.parse(a,{url:i.nextWrapperURL,previousUrl:r,wrapperSequence:n,wrapperDepth:t,followAdditionalWrappers:i.followAdditionalWrappers,allowMultipleAds:s}).then((t=>{if(delete i.nextWrapperURL,0===t.length)return i.creatives=[],e(i);t.forEach((e=>{e&&m.mergeWrapperAdData(e,i)})),e(t)})))).catch((t=>{i.errorCode=t.message===B?102:301,i.errorMessage=t.message,e(i)}))}))}completeWrapperResolving(e){if(0===e.ads.length)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(let t=e.ads.length-1;t>=0;t--){const r=e.ads[t],i=!r.creatives.some((e=>{var t;return(null===(t=e.mediaFiles)||void 0===t?void 0:t.length)>0}));!r.errorCode&&!i||r.VASTAdTagURI||(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),e.ads.splice(t,1))}}}let M=null;const W={data:{},length:0,getItem(e){return this.data[e]},setItem(e,t){this.data[e]=t,this.length=Object.keys(this.data).length},removeItem(e){delete this.data[e],this.length=Object.keys(this.data).length},clear(){this.data={},this.length=0}};class j{constructor(){this.storage=this.initStorage()}initStorage(){if(M)return M;try{M="undefined"!=typeof window&&null!==window?window.localStorage||window.sessionStorage:null}catch(e){M=null}return M&&!this.isStorageDisabled(M)||(M=W,M.clear()),M}isStorageDisabled(e){const t="__VASTStorage__";try{if(e.setItem(t,t),e.getItem(t)!==t)return e.removeItem(t),!0}catch(e){return!0}return e.removeItem(t),!1}getItem(e){return this.storage.getItem(e)}setItem(e,t){return this.storage.setItem(e,t)}removeItem(e){return this.storage.removeItem(e)}clear(){return this.storage.clear()}}const q=12e4;const K={get:async function(e,t){try{const r=new AbortController,i=setTimeout((()=>{throw r.abort(),new Error("URLHandler: Request timed out after ".concat(t.timeout||q," ms (408)"))}),t.timeout||q),a=await fetch(e,{...t,signal:r.signal,credentials:t.withCredentials?"include":"omit"}).finally((()=>{clearTimeout(i)})),s=function(e){var t;return"https:"===(null===(t=window)||void 0===t||null===(t=t.location)||void 0===t?void 0:t.protocol)&&e.url.includes("http://")?"URLHandler: Cannot go from HTTPS to HTTP.":200===e.status&&e.ok?null:"URLHandler: ".concat(e.statusText," (").concat(e.status,")")}(a);return s?{error:new Error(s),statusCode:a.status}:async function(e){const t=await e.text();let r;r=u.isBrowserEnvironment()?new DOMParser:new((await import("@xmldom/xmldom")).DOMParser);return{xml:r.parseFromString(t,"text/xml"),details:{byteLength:t.length,statusCode:e.status,rawXml:t}}}(a)}catch(e){return{error:e,statusCode:"AbortError"===e.name?408:null}}}};class H{constructor(){this.URLTemplateFilters=[]}setOptions(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.urlHandler=e.urlHandler||e.urlhandler||K,this.fetchingOptions={timeout:e.timeout||q,withCredentials:Boolean(e.withCredentials)}}addURLTemplateFilter(e){"function"==typeof e&&this.URLTemplateFilters.push(e)}removeLastURLTemplateFilter(){this.URLTemplateFilters.pop()}countURLTemplateFilters(){return this.URLTemplateFilters.length}clearURLTemplateFilters(){this.URLTemplateFilters=[]}async fetchVAST(e){var t;let{url:r,maxWrapperDepth:i,emitter:a,wrapperDepth:s=0,previousUrl:n=null,wrapperAd:o=null}=e;const l=Date.now();this.URLTemplateFilters.forEach((e=>{r=e(r)})),a("VAST-resolving",{url:r,previousUrl:n,wrapperDepth:s,maxWrapperDepth:i,timeout:this.fetchingOptions.timeout,wrapperAd:o});const c=await this.urlHandler.get(r,this.fetchingOptions),d=Math.round(Date.now()-l);if(a("VAST-resolved",{url:r,previousUrl:n,wrapperDepth:s,error:(null==c?void 0:c.error)||null,duration:d,statusCode:(null==c?void 0:c.statusCode)||null,...null==c?void 0:c.details}),O(null==c||null===(t=c.details)||void 0===t?void 0:t.byteLength,d),c.error)throw new Error(c.error);return c.xml}}class _{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new j;this.cappingFreeLunch=e,this.cappingMinimumTimeInterval=t,this.fetcher=new H,this.vastParser=new P({fetcher:this.fetcher}),this.storage=r,void 0===this.lastSuccessfulAd&&(this.lastSuccessfulAd=0),void 0===this.totalCalls&&(this.totalCalls=0),void 0===this.totalCallsTimeout&&(this.totalCallsTimeout=0)}addURLTemplateFilter(e){this.fetcher.addURLTemplateFilter(e)}removeLastURLTemplateFilter(){this.fetcher.removeLastURLTemplateFilter()}countURLTemplateFilters(){return this.fetcher.countURLTemplateFilters()}clearURLTemplateFilters(){this.fetcher.clearURLTemplateFilters()}getParser(){return this.vastParser}get lastSuccessfulAd(){return this.storage.getItem("vast-client-last-successful-ad")}set lastSuccessfulAd(e){this.storage.setItem("vast-client-last-successful-ad",e)}get totalCalls(){return this.storage.getItem("vast-client-total-calls")}set totalCalls(e){this.storage.setItem("vast-client-total-calls",e)}get totalCallsTimeout(){return this.storage.getItem("vast-client-total-calls-timeout")}set totalCallsTimeout(e){this.storage.setItem("vast-client-total-calls-timeout",e)}hasRemainingAds(){return this.vastParser.remainingAds.length>0}getNextAds(e){return this.vastParser.getRemainingAds(e)}parseVAST(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.fetcher.setOptions(t),this.vastParser.parseVAST(e,t)}get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=Date.now();return t.hasOwnProperty("resolveAll")||(t.resolveAll=!1),this.totalCallsTimeout{if(this.cappingFreeLunch>=this.totalCalls)return a(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(this.totalCalls,"/").concat(this.cappingFreeLunch)));const s=r-this.lastSuccessfulAd;if(s<0)this.lastSuccessfulAd=0;else if(s(t.previousUrl=e,t.isRootVAST=!0,t.url=e,this.vastParser.parse(r,t).then((e=>{const t=this.vastParser.buildVASTResponse(e);i(t)}))))).catch((e=>a(e)))}))}}class z extends S{constructor(e,t,r){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];super(),this.ad=t,this.creative=r,this.variation=i,this.muted=a,this.impressed=!1,this.skippable=!1,this.trackingEvents={},this.lastPercentage=0,this._alreadyTriggeredQuartiles={},this.emitAlwaysEvents=["creativeView","start","firstQuartile","midpoint","thirdQuartile","complete","resume","pause","rewind","skip","closeLinear","close"];for(const e in this.creative.trackingEvents){const t=this.creative.trackingEvents[e];this.trackingEvents[e]=t.slice(0)}!function(e){return"linear"===e.type}(this.creative)?this._initVariationTracking():this._initLinearTracking(),e&&this.on("start",(()=>{e.lastSuccessfulAd=Date.now()}))}_initLinearTracking(){this.linear=!0,this.skipDelay=this.creative.skipDelay,this.setDuration(this.creative.duration),this.clickThroughURLTemplate=this.creative.videoClickThroughURLTemplate,this.clickTrackingURLTemplates=this.creative.videoClickTrackingURLTemplates}_initVariationTracking(){if(this.linear=!1,this.skipDelay=-1,this.variation){for(const e in this.variation.trackingEvents){const t=this.variation.trackingEvents[e];this.trackingEvents[e]?this.trackingEvents[e]=this.trackingEvents[e].concat(t.slice(0)):this.trackingEvents[e]=t.slice(0)}"nonLinearAd"===this.variation.adType?(this.clickThroughURLTemplate=this.variation.nonlinearClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.nonlinearClickTrackingURLTemplates,this.setDuration(this.variation.minSuggestedDuration)):function(e){return"companionAd"===e.adType}(this.variation)&&(this.clickThroughURLTemplate=this.variation.companionClickThroughURLTemplate,this.clickTrackingURLTemplates=this.variation.companionClickTrackingURLTemplates)}}setDuration(e){u.isValidTimeValue(e)?(this.assetDuration=e,this.quartiles={firstQuartile:Math.round(25*this.assetDuration)/100,midpoint:Math.round(50*this.assetDuration)/100,thirdQuartile:Math.round(75*this.assetDuration)/100}):this.emit("TRACKER-error",{message:"the duration provided is not valid. duration: ".concat(e)})}setProgress(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!u.isValidTimeValue(e)||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given setProgress parameter has the wrong type. progress: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))});const i=this.skipDelay||-1;if(-1===i||this.skippable||(i>e?this.emit("skip-countdown",i-e):(this.skippable=!0,this.emit("skip-countdown",0))),this.assetDuration>0){const i=Math.round(e/this.assetDuration*100),a=[];if(e>0){a.push("start");for(let e=this.lastPercentage;e{this.track(e,{macros:t,once:r})})),e1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.muted!==e&&this.track(e?"mute":"unmute",{macros:t}),this.muted=e):this.emit("TRACKER-error",{message:"One given setMuted parameter has the wrong type. muted: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))})}setPaused(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.paused!==e&&this.track(e?"pause":"resume",{macros:t}),this.paused=e):this.emit("TRACKER-error",{message:"One given setPaused parameter has the wrong type. paused: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))})}setFullscreen(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.fullscreen!==e&&this.track(e?"fullscreen":"exitFullscreen",{macros:t}),this.fullscreen=e):this.emit("TRACKER-error",{message:"One given setFullScreen parameter has the wrong type. fullscreen: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))})}setExpand(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"boolean"==typeof e&&"object"==typeof t?(this.expanded!==e&&(this.track(e?"expand":"collapse",{macros:t}),this.track(e?"playerExpand":"playerCollapse",{macros:t})),this.expanded=e):this.emit("TRACKER-error",{message:"One given setExpand parameter has the wrong type. expanded: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))})}setSkipDelay(e){u.isValidTimeValue(e)?this.skipDelay=e:this.emit("TRACKER-error",{message:"setSkipDelay parameter does not have a valid value. duration: ".concat(e)})}trackImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.impressed||(this.impressed=!0,this.trackURLs(this.ad.impressionURLTemplates,e),this.track("creativeView",{macros:e})):this.emit("TRACKER-error",{message:"trackImpression parameter has the wrong type. macros: ".concat(e)})}trackViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewable,e)})):this.emit("TRACKER-error",{message:"trackViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackNotViewableImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.notViewable,e)})):this.emit("TRACKER-error",{message:"trackNotViewableImpression given macros has the wrong type. macros: ".concat(e)})}trackUndeterminedImpression(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.ad.viewableImpression.forEach((t=>{this.trackURLs(t.viewUndetermined,e)})):this.emit("TRACKER-error",{message:"trackUndeterminedImpression given macros has the wrong type. macros: ".concat(e)})}error(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"object"==typeof e&&"boolean"==typeof t?this.trackURLs(this.ad.errorURLTemplates,e,{isCustomCode:t}):this.emit("TRACKER-error",{message:"One given error parameter has the wrong type. macros: ".concat(u.formatMacrosValues(e),", isCustomCode: ").concat(t)})}errorWithCode(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"string"==typeof e&&"boolean"==typeof t?(this.error({ERRORCODE:e},t),console.log("The method errorWithCode is deprecated, please use vast tracker error method instead")):this.emit("TRACKER-error",{message:"One given errorWithCode parameter has the wrong type. errorCode: ".concat(e,", isCustomCode: ").concat(t)})}complete(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("complete",{macros:e}):this.emit("TRACKER-error",{message:"complete given macros has the wrong type. macros: ".concat(e)})}notUsed(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?(this.track("notUsed",{macros:e}),this.trackingEvents=[]):this.emit("TRACKER-error",{message:"notUsed given macros has the wrong type. macros: ".concat(e)})}otherAdInteraction(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("otherAdInteraction",{macros:e}):this.emit("TRACKER-error",{message:"otherAdInteraction given macros has the wrong type. macros: ".concat(e)})}acceptInvitation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("acceptInvitation",{macros:e}):this.emit("TRACKER-error",{message:"acceptInvitation given macros has the wrong type. macros: ".concat(e)})}adExpand(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adExpand",{macros:e}):this.emit("TRACKER-error",{message:"adExpand given macros has the wrong type. macros: ".concat(e)})}adCollapse(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("adCollapse",{macros:e}):this.emit("TRACKER-error",{message:"adCollapse given macros has the wrong type. macros: ".concat(e)})}minimize(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("minimize",{macros:e}):this.emit("TRACKER-error",{message:"minimize given macros has the wrong type. macros: ".concat(e)})}verificationNotExecuted(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given verificationNotExecuted parameter has to wrong type. vendor: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))});if(!this.ad||!this.ad.adVerifications||!this.ad.adVerifications.length)throw new Error("No adVerifications provided");if(!e)throw new Error("No vendor provided, unable to find associated verificationNotExecuted");const r=this.ad.adVerifications.find((t=>t.vendor===e));if(!r)throw new Error("No associated verification element found for vendor: ".concat(e));const i=r.trackingEvents;if(i&&i.verificationNotExecuted){const e=i.verificationNotExecuted;this.trackURLs(e,t),this.emit("verificationNotExecuted",{trackingURLTemplates:e})}}overlayViewDuration(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"string"==typeof e&&"object"==typeof t?(t.ADPLAYHEAD=e,this.track("overlayViewDuration",{macros:t})):this.emit("TRACKER-error",{message:"One given overlayViewDuration parameters has the wrong type. formattedDuration: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))})}close(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track(this.linear?"closeLinear":"close",{macros:e}):this.emit("TRACKER-error",{message:"close given macros has the wrong type. macros: ".concat(e)})}skip(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("skip",{macros:e}):this.emit("TRACKER-error",{message:"skip given macros has the wrong type. macros: ".concat(e)})}load(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"object"==typeof e?this.track("loaded",{macros:e}):this.emit("TRACKER-error",{message:"load given macros has the wrong type. macros: ".concat(e)})}click(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!==e&&"string"!=typeof e||"object"!=typeof t)return void this.emit("TRACKER-error",{message:"One given click parameter has the wrong type. fallbackClickThroughURL: ".concat(e,", macros: ").concat(u.formatMacrosValues(t))});this.clickTrackingURLTemplates&&this.clickTrackingURLTemplates.length&&this.trackURLs(this.clickTrackingURLTemplates,t);const r=this.clickThroughURLTemplate||e,i={...t};if(r){this.progress&&(i.ADPLAYHEAD=this.progressFormatted());const e=u.resolveURLTemplates([r],i)[0];this.emit("clickthrough",e)}}track(e){let{macros:t={},once:r=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("object"!=typeof t)return void this.emit("TRACKER-error",{message:"track given macros has the wrong type. macros: ".concat(t)});"closeLinear"===e&&!this.trackingEvents[e]&&this.trackingEvents.close&&(e="close");const i=this.trackingEvents[e],a=this.emitAlwaysEvents.indexOf(e)>-1;i?(this.emit(e,{trackingURLTemplates:i}),this.trackURLs(i,t)):a&&this.emit(e,null),r&&(delete this.trackingEvents[e],a&&this.emitAlwaysEvents.splice(this.emitAlwaysEvents.indexOf(e),1))}trackURLs(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{validUrls:a,invalidUrls:s}=u.filterUrlTemplates(e);s.length&&this.emit("TRACKER-error",{message:"Provided urls are malformed. url: ".concat(s)});const n={...r};this.linear&&(this.creative&&this.creative.mediaFiles&&this.creative.mediaFiles[0]&&this.creative.mediaFiles[0].fileURL&&(n.ASSETURI=this.creative.mediaFiles[0].fileURL),this.progress&&(n.ADPLAYHEAD=this.progressFormatted())),null!==(t=this.creative)&&void 0!==t&&null!==(t=t.universalAdIds)&&void 0!==t&&t.length&&(n.UNIVERSALADID=this.creative.universalAdIds.map((e=>e.idRegistry.concat(" ",e.value))).join(",")),this.ad&&(this.ad.sequence&&(n.PODSEQUENCE=this.ad.sequence),this.ad.adType&&(n.ADTYPE=this.ad.adType),this.ad.adServingId&&(n.ADSERVINGID=this.ad.adServingId),this.ad.categories&&this.ad.categories.length&&(n.ADCATEGORIES=this.ad.categories.map((e=>e.value)).join(",")),this.ad.blockedAdCategories&&this.ad.blockedAdCategories.length&&(n.BLOCKEDADCATEGORIES=this.ad.blockedAdCategories.map((e=>e.value)).join(","))),u.track(a,n,i)}convertToTimecode(e){if(!u.isValidTimeValue(e))return"";const t=1e3*e,r=Math.floor(t/36e5),i=Math.floor(t/6e4%60),a=Math.floor(t/1e3%60),s=Math.floor(t%1e3);return"".concat(u.addLeadingZeros(r,2),":").concat(u.addLeadingZeros(i,2),":").concat(u.addLeadingZeros(a,2),".").concat(u.addLeadingZeros(s,3))}progressFormatted(){return this.convertToTimecode(this.progress)}}export{_ as VASTClient,P as VASTParser,z as VASTTracker,p as parseDuration}; From d6420de113cfd8180cc943e0079e9f2c20374436 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zacharie=20Ta=C3=AFfour?= Date: Tue, 26 Nov 2024 16:28:12 +0100 Subject: [PATCH 5/5] 6.0.2 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6ae5a989..fc06d17e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@dailymotion/vast-client", - "version": "6.0.1", + "version": "6.0.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@dailymotion/vast-client", - "version": "6.0.1", + "version": "6.0.2", "license": "MIT", "dependencies": { "@xmldom/xmldom": "^0.8.3" diff --git a/package.json b/package.json index e4712e1d..6f60abc8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@dailymotion/vast-client", "author": "Dailymotion (https://developer.dailymotion.com/)", - "version": "6.0.1", + "version": "6.0.2", "description": "JavaScript VAST Client", "keywords": [ "vast",