!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t=t||self).MusicKit={})}(this,(function(t){"use strict";var n=void 0!==typeof self?self:this,extendStatics=function(t,n){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var l in n)n.hasOwnProperty(l)&&(t[l]=n[l])})(t,n)};
/*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */function __extends(t,n){function __(){this.constructor=t}extendStatics(t,n),t.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}var __assign=function(){return(__assign=Object.assign||function(t){for(var n,l=1,d=arguments.length;l<d;l++)for(var p in n=arguments[l])Object.prototype.hasOwnProperty.call(n,p)&&(t[p]=n[p]);return t}).apply(this,arguments)};function __decorate(t,n,l,d){var p,h=arguments.length,f=h<3?n:null===d?d=Object.getOwnPropertyDescriptor(n,l):d;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)f=Reflect.decorate(t,n,l,d);else for(var y=t.length-1;y>=0;y--)(p=t[y])&&(f=(h<3?p(f):h>3?p(n,l,f):p(n,l))||f);return h>3&&f&&Object.defineProperty(n,l,f),f}function __metadata(t,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,n)}function __awaiter(t,n,l,d){return new(l||(l=Promise))((function(p,h){function fulfilled(t){try{step(d.next(t))}catch(e){h(e)}}function rejected(t){try{step(d.throw(t))}catch(e){h(e)}}function step(t){var n;t.done?p(t.value):(n=t.value,n instanceof l?n:new l((function(t){t(n)}))).then(fulfilled,rejected)}step((d=d.apply(t,n||[])).next())}))}function __generator(t,n){var l,d,p,h,f={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return h={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(h[Symbol.iterator]=function(){return this}),h;function verb(h){return function(y){return function(h){if(l)throw new TypeError("Generator is already executing.");for(;f;)try{if(l=1,d&&(p=2&h[0]?d.return:h[0]?d.throw||((p=d.return)&&p.call(d),0):d.next)&&!(p=p.call(d,h[1])).done)return p;switch(d=0,p&&(h=[2&h[0],p.value]),h[0]){case 0:case 1:p=h;break;case 4:return f.label++,{value:h[1],done:!1};case 5:f.label++,d=h[1],h=[0];continue;case 7:h=f.ops.pop(),f.trys.pop();continue;default:if(!(p=f.trys,(p=p.length>0&&p[p.length-1])||6!==h[0]&&2!==h[0])){f=0;continue}if(3===h[0]&&(!p||h[1]>p[0]&&h[1]<p[3])){f.label=h[1];break}if(6===h[0]&&f.label<p[1]){f.label=p[1],p=h;break}if(p&&f.label<p[2]){f.label=p[2],f.ops.push(h);break}p[2]&&f.ops.pop(),f.trys.pop();continue}h=n.call(t,f)}catch(e){h=[6,e],d=0}finally{l=p=0}if(5&h[0])throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}([h,y])}}}function __read(t,n){var l="function"==typeof Symbol&&t[Symbol.iterator];if(!l)return t;var d,p,h=l.call(t),f=[];try{for(;(void 0===n||n-- >0)&&!(d=h.next()).done;)f.push(d.value)}catch(ba){p={error:ba}}finally{try{d&&!d.done&&(l=h.return)&&l.call(h)}finally{if(p)throw p.error}}return f}function __spread(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(__read(arguments[n]));return t}function formatArtworkURL(t,n,l){return n=n||t.height||100,l=l||t.width||100,window.devicePixelRatio>=1.5&&(l*=2,n*=2),t.url.replace("{h}",""+n).replace("{w}",""+l).replace("{f}","jpeg")}var l="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n?n:"undefined"!=typeof self?self:{};function unwrapExports(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function createCommonjsModule(t,n){return t(n={exports:{}},n.exports),n.exports}var d=createCommonjsModule((function(t){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)})),p=createCommonjsModule((function(t){var n=t.exports={version:"2.6.11"};"number"==typeof __e&&(__e=n)})),h=(p.version,function(t){return"object"==typeof t?null!==t:"function"==typeof t}),_anObject=function(t){if(!h(t))throw TypeError(t+" is not an object!");return t},_fails=function(t){try{return!!t()}catch(e){return!0}},f=!_fails((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})),y=d.document,v=h(y)&&h(y.createElement),g=!f&&!_fails((function(){return 7!=Object.defineProperty((t="div",v?y.createElement(t):{}),"a",{get:function(){return 7}}).a;var t})),_=Object.defineProperty,m={f:f?Object.defineProperty:function(t,n,l){if(_anObject(t),n=function(t,n){if(!h(t))return t;var l,d;if(n&&"function"==typeof(l=t.toString)&&!h(d=l.call(t)))return d;if("function"==typeof(l=t.valueOf)&&!h(d=l.call(t)))return d;if(!n&&"function"==typeof(l=t.toString)&&!h(d=l.call(t)))return d;throw TypeError("Can't convert object to primitive value")}(n,!0),_anObject(l),g)try{return _(t,n,l)}catch(e){}if("get"in l||"set"in l)throw TypeError("Accessors not supported!");return"value"in l&&(t[n]=l.value),t}},b=f?function(t,n,l){return m.f(t,n,function(t,n){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:n}}(1,l))}:function(t,n,l){return t[n]=l,t},P={}.hasOwnProperty,_has=function(t,n){return P.call(t,n)},k=0,T=Math.random(),_uid=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++k+T).toString(36))},S=createCommonjsModule((function(t){var n=d["__core-js_shared__"]||(d["__core-js_shared__"]={});(t.exports=function(t,l){return n[t]||(n[t]=void 0!==l?l:{})})("versions",[]).push({version:p.version,mode:"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})})),A=S("native-function-to-string",Function.toString),w=createCommonjsModule((function(t){var n=_uid("src"),l=(""+A).split("toString");p.inspectSource=function(t){return A.call(t)},(t.exports=function(t,p,h,f){var y="function"==typeof h;y&&(_has(h,"name")||b(h,"name",p)),t[p]!==h&&(y&&(_has(h,n)||b(h,n,t[p]?""+t[p]:l.join(String(p)))),t===d?t[p]=h:f?t[p]?t[p]=h:b(t,p,h):(delete t[p],b(t,p,h)))})(Function.prototype,"toString",(function(){return"function"==typeof this&&this[n]||A.call(this)}))})),_ctx=function(t,n,l){if(function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!")}(t),void 0===n)return t;switch(l){case 1:return function(l){return t.call(n,l)};case 2:return function(l,d){return t.call(n,l,d)};case 3:return function(l,d,p){return t.call(n,l,d,p)}}return function(){return t.apply(n,arguments)}},$export=function(t,n,l){var h,f,y,v,g=t&$export.F,_=t&$export.G,m=t&$export.S,P=t&$export.P,k=t&$export.B,T=_?d:m?d[n]||(d[n]={}):(d[n]||{}).prototype,S=_?p:p[n]||(p[n]={}),A=S.prototype||(S.prototype={});for(h in _&&(l=n),l)y=((f=!g&&T&&void 0!==T[h])?T:l)[h],v=k&&f?_ctx(y,d):P&&"function"==typeof y?_ctx(Function.call,y):y,T&&w(T,h,y,t&$export.U),S[h]!=y&&b(S,h,v),P&&A[h]!=y&&(A[h]=y)};d.core=p,$export.F=1,$export.G=2,$export.S=4,$export.P=8,$export.B=16,$export.W=32,$export.U=64,$export.R=128;var I,E,R=$export,O={}.toString,C=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==function(t){return O.call(t).slice(8,-1)}(t)?t.split(""):Object(t)},_defined=function(t){if(null==t)throw TypeError("Can't call method on  "+t);return t},_toIobject=function(t){return C(_defined(t))},M=Math.ceil,D=Math.floor,_toInteger=function(t){return isNaN(t=+t)?0:(t>0?D:M)(t)},L=Math.min,N=Math.max,U=Math.min,B=S("keys"),j=(I=!1,function(t,n,l){var d,p,h=_toIobject(t),f=(d=h.length)>0?L(_toInteger(d),9007199254740991):0,y=function(t,n){return(t=_toInteger(t))<0?N(t+n,0):U(t,n)}(l,f);if(I&&n!=n){for(;f>y;)if((p=h[y++])!=p)return!0}else for(;f>y;y++)if((I||y in h)&&h[y]===n)return I||y||0;return!I&&-1}),F=B[E="IE_PROTO"]||(B[E]=_uid(E)),K="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),V=Object.keys||function(t){return function(t,n){var l,d=_toIobject(t),p=0,h=[];for(l in d)l!=F&&_has(d,l)&&h.push(l);for(;n.length>p;)_has(d,l=n[p++])&&(~j(h,l)||h.push(l));return h}(t,K)},$={f:Object.getOwnPropertySymbols},H={f:{}.propertyIsEnumerable},_toObject=function(t){return Object(_defined(t))},z=Object.assign,W=!z||_fails((function(){var t={},n={},l=Symbol(),d="abcdefghijklmnopqrst";return t[l]=7,d.split("").forEach((function(t){n[t]=t})),7!=z({},t)[l]||Object.keys(z({},n)).join("")!=d}))?function(t,n){for(var l=_toObject(t),d=arguments.length,p=1,h=$.f,y=H.f;d>p;)for(var v,g=C(arguments[p++]),_=h?V(g).concat(h(g)):V(g),m=_.length,b=0;m>b;)v=_[b++],f&&!y.call(g,v)||(l[v]=g[v]);return l}:z;R(R.S+R.F,"Object",{assign:W});p.Object.assign;var Y="URLSearchParams"in self,q="Symbol"in self&&"iterator"in Symbol,G="FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(e){return!1}}(),Q="FormData"in self,J="ArrayBuffer"in self;if(J)var X=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Z=ArrayBuffer.isView||function(t){return t&&X.indexOf(Object.prototype.toString.call(t))>-1};function normalizeName(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function normalizeValue(t){return"string"!=typeof t&&(t=String(t)),t}function iteratorFor(t){var n={next:function(){var n=t.shift();return{done:void 0===n,value:n}}};return q&&(n[Symbol.iterator]=function(){return n}),n}function Headers$1(t){this.map={},t instanceof Headers$1?t.forEach((function(t,n){this.append(n,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(n){this.append(n,t[n])}),this)}function consumed(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function fileReaderReady(t){return new Promise((function(n,l){t.onload=function(){n(t.result)},t.onerror=function(){l(t.error)}}))}function readBlobAsArrayBuffer(t){var n=new FileReader,l=fileReaderReady(n);return n.readAsArrayBuffer(t),l}function bufferClone(t){if(t.slice)return t.slice(0);var n=new Uint8Array(t.byteLength);return n.set(new Uint8Array(t)),n.buffer}function Body(){return this.bodyUsed=!1,this._initBody=function(t){var n;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:G&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:Q&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:Y&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():J&&G&&((n=t)&&DataView.prototype.isPrototypeOf(n))?(this._bodyArrayBuffer=bufferClone(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):J&&(ArrayBuffer.prototype.isPrototypeOf(t)||Z(t))?this._bodyArrayBuffer=bufferClone(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):Y&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},G&&(this.blob=function(){var t=consumed(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?consumed(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(readBlobAsArrayBuffer)}),this.text=function(){var t,n,l,d=consumed(this);if(d)return d;if(this._bodyBlob)return t=this._bodyBlob,n=new FileReader,l=fileReaderReady(n),n.readAsText(t),l;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var n=new Uint8Array(t),l=new Array(n.length),d=0;d<n.length;d++)l[d]=String.fromCharCode(n[d]);return l.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},Q&&(this.formData=function(){return this.text().then(decode)}),this.json=function(){return this.text().then(JSON.parse)},this}Headers$1.prototype.append=function(t,n){t=normalizeName(t),n=normalizeValue(n);var l=this.map[t];this.map[t]=l?l+", "+n:n},Headers$1.prototype.delete=function(t){delete this.map[normalizeName(t)]},Headers$1.prototype.get=function(t){return t=normalizeName(t),this.has(t)?this.map[t]:null},Headers$1.prototype.has=function(t){return this.map.hasOwnProperty(normalizeName(t))},Headers$1.prototype.set=function(t,n){this.map[normalizeName(t)]=normalizeValue(n)},Headers$1.prototype.forEach=function(t,n){for(var l in this.map)this.map.hasOwnProperty(l)&&t.call(n,this.map[l],l,this)},Headers$1.prototype.keys=function(){var t=[];return this.forEach((function(n,l){t.push(l)})),iteratorFor(t)},Headers$1.prototype.values=function(){var t=[];return this.forEach((function(n){t.push(n)})),iteratorFor(t)},Headers$1.prototype.entries=function(){var t=[];return this.forEach((function(n,l){t.push([l,n])})),iteratorFor(t)},q&&(Headers$1.prototype[Symbol.iterator]=Headers$1.prototype.entries);var ee=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function Request(t,n){var l,d,p=(n=n||{}).body;if(t instanceof Request){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,n.headers||(this.headers=new Headers$1(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,p||null==t._bodyInit||(p=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=n.credentials||this.credentials||"same-origin",!n.headers&&this.headers||(this.headers=new Headers$1(n.headers)),this.method=(l=n.method||this.method||"GET",d=l.toUpperCase(),ee.indexOf(d)>-1?d:l),this.mode=n.mode||this.mode||null,this.signal=n.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&p)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(p)}function decode(t){var n=new FormData;return t.trim().split("&").forEach((function(t){if(t){var l=t.split("="),d=l.shift().replace(/\+/g," "),p=l.join("=").replace(/\+/g," ");n.append(decodeURIComponent(d),decodeURIComponent(p))}})),n}function Response(t,n){n||(n={}),this.type="default",this.status=void 0===n.status?200:n.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in n?n.statusText:"OK",this.headers=new Headers$1(n.headers),this.url=n.url||"",this._initBody(t)}Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit})},Body.call(Request.prototype),Body.call(Response.prototype),Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers$1(this.headers),url:this.url})},Response.error=function(){var t=new Response(null,{status:0,statusText:""});return t.type="error",t};var te=[301,302,303,307,308];Response.redirect=function(t,n){if(-1===te.indexOf(n))throw new RangeError("Invalid status code");return new Response(null,{status:n,headers:{location:t}})};var re=self.DOMException;try{new re}catch(Gs){(re=function(t,n){this.message=t,this.name=n;var l=Error(t);this.stack=l.stack}).prototype=Object.create(Error.prototype),re.prototype.constructor=re}function fetch$1(t,n){return new Promise((function(l,d){var p=new Request(t,n);if(p.signal&&p.signal.aborted)return d(new re("Aborted","AbortError"));var h=new XMLHttpRequest;function abortXhr(){h.abort()}h.onload=function(){var t,n,d={status:h.status,statusText:h.statusText,headers:(t=h.getAllResponseHeaders()||"",n=new Headers$1,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var l=t.split(":"),d=l.shift().trim();if(d){var p=l.join(":").trim();n.append(d,p)}})),n)};d.url="responseURL"in h?h.responseURL:d.headers.get("X-Request-URL");var p="response"in h?h.response:h.responseText;l(new Response(p,d))},h.onerror=function(){d(new TypeError("Network request failed"))},h.ontimeout=function(){d(new TypeError("Network request failed"))},h.onabort=function(){d(new re("Aborted","AbortError"))},h.open(p.method,p.url,!0),"include"===p.credentials?h.withCredentials=!0:"omit"===p.credentials&&(h.withCredentials=!1),"responseType"in h&&G&&(h.responseType="blob"),p.headers.forEach((function(t,n){h.setRequestHeader(n,t)})),p.signal&&(p.signal.addEventListener("abort",abortXhr),h.onreadystatechange=function(){4===h.readyState&&p.signal.removeEventListener("abort",abortXhr)}),h.send(void 0===p._bodyInit?null:p._bodyInit)}))}fetch$1.polyfill=!0,self.fetch||(self.fetch=fetch$1,self.Headers=Headers$1,self.Request=Request,self.Response=Response)
/*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */;var ie=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var l in n)n.hasOwnProperty(l)&&(t[l]=n[l])};function __extends$1(t,n){function __(){this.constructor=t}ie(t,n),t.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}var ne=Object.assign||function(t){for(var n,l=1,d=arguments.length;l<d;l++)for(var p in n=arguments[l])Object.prototype.hasOwnProperty.call(n,p)&&(t[p]=n[p]);return t};function __awaiter$1(t,n,l,d){return new(l||(l=Promise))((function(p,h){function fulfilled(t){try{step(d.next(t))}catch(e){h(e)}}function rejected(t){try{step(d.throw(t))}catch(e){h(e)}}function step(t){t.done?p(t.value):new l((function(n){n(t.value)})).then(fulfilled,rejected)}step((d=d.apply(t,n||[])).next())}))}function __generator$1(t,n){var l,d,p,h,f={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return h={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(h[Symbol.iterator]=function(){return this}),h;function verb(h){return function(y){return function(h){if(l)throw new TypeError("Generator is already executing.");for(;f;)try{if(l=1,d&&(p=d[2&h[0]?"return":h[0]?"throw":"next"])&&!(p=p.call(d,h[1])).done)return p;switch(d=0,p&&(h=[0,p.value]),h[0]){case 0:case 1:p=h;break;case 4:return f.label++,{value:h[1],done:!1};case 5:f.label++,d=h[1],h=[0];continue;case 7:h=f.ops.pop(),f.trys.pop();continue;default:if(!(p=f.trys,(p=p.length>0&&p[p.length-1])||6!==h[0]&&2!==h[0])){f=0;continue}if(3===h[0]&&(!p||h[1]>p[0]&&h[1]<p[3])){f.label=h[1];break}if(6===h[0]&&f.label<p[1]){f.label=p[1],p=h;break}if(p&&f.label<p[2]){f.label=p[2],f.ops.push(h);break}p[2]&&f.ops.pop(),f.trys.pop();continue}h=n.call(t,f)}catch(e){h=[6,e],d=0}finally{l=p=0}if(5&h[0])throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}([h,y])}}}function __read$1(t,n){var l="function"==typeof Symbol&&t[Symbol.iterator];if(!l)return t;var d,p,h=l.call(t),f=[];try{for(;(void 0===n||n-- >0)&&!(d=h.next()).done;)f.push(d.value)}catch(ba){p={error:ba}}finally{try{d&&!d.done&&(l=h.return)&&l.call(h)}finally{if(p)throw p.error}}return f}function __spread$1(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(__read$1(arguments[n]));return t}var oe="undefined"!=typeof FastBoot?FastBoot.require("buffer").Buffer:"undefined"!=typeof process&&null!==process.versions&&null!==process.versions.node?Buffer:window.Buffer;function isObject(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function generateUUID(){for(var t=strRandomizer()+strRandomizer();t.length<16;)t+=strRandomizer();return t.slice(0,16)}function strRandomizer(){return Math.random().toString(16).substring(2)}var ae=memoize((function(t){return/^[a|i|l|p]{1}\.[a-zA-Z0-9]+$/.test(t)}));function isNodeEnvironment(t){var isDefined=function(t){return null!=t};return 0===arguments.length&&"undefined"!=typeof process&&(t=process),isDefined(t)&&isDefined(t.versions)&&isDefined(t.versions.node)||"undefined"!=typeof FastBoot}var se=memoize(isNodeEnvironment()?function(t){return oe.from(t,"base64").toString("binary")}:function(t){return window.atob(t)});memoize(isNodeEnvironment()?function(t){return oe.from(t).toString("base64")}:function(t){return window.btoa(t)});function memoize(t){return function(){for(var n=[],l=0;l<arguments.length;l++)n[l]=arguments[l];for(var d="",p=n.length;p--;){var h=n[p];d+=h===Object(h)?JSON.stringify(h):h,t._memoized||(t._memoized={})}return d in t._memoized?t._memoized[d]:t._memoized[d]=t.apply(void 0,n)}}function addQueryParams(t,n){var l=urlEncodeParameters(n);return""===l?t:(-1===t.indexOf("?")&&(t+="?"),t=t.endsWith("?")?""+t+l:t+"&"+l)}function urlEncodeParameters(t){return t?Object.keys(t).reduce((function(n,l){var d=t[l];return isObject(d)?Object.keys(d).reduce((function(t,n){return t+(t?"&":"")+encodeURIComponent(l)+"["+encodeURIComponent(n)+"]="+encodeURIComponent(d[n])}),n):n+(n?"&":"")+encodeURIComponent(l)+"="+encodeURIComponent(t[l])}),""):""}function parseQueryParams(t){var n,l={};if(!t||t.startsWith("http")&&!t.includes("?"))return{};try{l=(null!==(n=t.split("?")[1])&&void 0!==n?n:t).split("&").reduce((function(t,n){var l=__read$1(n.split("="),2),d=l[0],p=l[1];return t[decodeURIComponent(d)]=decodeURIComponent(p),t}),{})}catch(e){return{}}return l}var ue=memoize((function(t){var n=se(t);return ce(n)}));function ensureArray(t){return void 0===t&&(t=[]),Array.isArray(t)?t:[t]}var ce=memoize((function(t){for(var n=t.length,l=new ArrayBuffer(n),d=new Uint8Array(l),p=0;p<n;p++)d[p]=t.charCodeAt(p);return d})),le=memoize((function(t){for(var n=t.length,l=new ArrayBuffer(2*n),d=new Uint16Array(l),p=0;p<n;p++)d[p]=t.charCodeAt(p);return d})),de=memoize((function(t){for(var n,l,d,p,h,f,y,v=0,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_="";v<t.length;)p=(n=t[v++])>>2,h=(3&n)<<4|(l=v<t.length?t[v++]:Number.NaN)>>4,f=(15&l)<<2|(d=v<t.length?t[v++]:Number.NaN)>>6,y=63&d,isNaN(l)?f=y=64:isNaN(d)&&(y=64),_+=g.charAt(p)+g.charAt(h)+g.charAt(f)+g.charAt(y);return _})),pe=Object.prototype.hasOwnProperty;function get(t,n){return n.split(".").reduce((function(t,n){if(void 0!==t)return t[n]}),t)}function transform(t,n,l){return void 0===l&&(l=!1),l&&(t=Object.keys(t).reduce((function(n,l){return n[t[l]]=l,n}),{})),Object.keys(t).reduce((function(l,d){var p,h=t[d];return(p="function"==typeof h?h():get(n,h))&&function(t,n,l){n.split(".").reduce((function(n,d,p,h){var f=p===h.length-1,y=n.hasOwnProperty(d),v=n[d]instanceof Object,g=null===n[d];if(!f&&y&&(!v||g))throw new TypeError("Value at "+h.slice(0,p+1).join(".")+" in keypath is not an Object.");return f?(n[d]=l,t):y?n[d]:n[d]={}}),t)}(l,d,p),l}),{})}function transformKeys(t,n){return Object.keys(t).reduce((function(l,d){return l[n(d)]=t[d],l}),{})}var he=function(){function Notifications(t,n){var l=this;void 0===t&&(t=[]),this._eventRegistry={},t.forEach((function(t){l._eventRegistry[t]=[]})),n&&n.namespace&&(this.dispatchNamespace="com.apple."+n.namespace),this.shouldStorageDispatch&&window.addEventListener("storage",this._handleGlobalStorageEvent)}return Object.defineProperty(Notifications.prototype,"shouldStorageDispatch",{get:function(){return"undefined"!=typeof window&&"undefined"!=typeof sessionStorage&&this.dispatchNamespace},enumerable:!0,configurable:!0}),Notifications.prototype.addEventListener=function(t,n){Array.isArray(this._eventRegistry[t])&&this._eventRegistry[t].push(n)},Notifications.prototype.dispatchEvent=function(t,n){Array.isArray(this._eventRegistry[t])&&this._eventRegistry[t].forEach((function(t){return t(n)}))},Notifications.prototype.dispatchDistributedEvent=function(t,n){if(this.dispatchEvent(t,n),this.shouldStorageDispatch){var l=this.dispatchNamespace+":"+t;sessionStorage.setItem(l,JSON.stringify(n))}},Notifications.prototype.removeEventListener=function(t,n){if(Array.isArray(this._eventRegistry[t])){var l=this._eventRegistry[t].indexOf(n);this._eventRegistry[t].splice(l,1)}},Notifications.prototype._handleGlobalStorageEvent=function(t){var n;if(this.dispatchNamespace&&(null===(n=t.key)||void 0===n?void 0:n.startsWith(this.dispatchNamespace+":"))){var l=t.key.substring(this.dispatchNamespace.length+1);this.dispatchEvent(l,JSON.parse(t.newValue))}},Notifications}(),isMergeableObject=function(t){return function(t){return!!t&&"object"==typeof t}(t)&&!function(t){var n=Object.prototype.toString.call(t);return"[object RegExp]"===n||"[object Date]"===n||function(t){return t.$$typeof===ye}(t)}(t)};var fe,ye="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function cloneUnlessOtherwiseSpecified(t,n){return!1!==n.clone&&n.isMergeableObject(t)?deepmerge((l=t,Array.isArray(l)?[]:{}),t,n):t;var l}function defaultArrayMerge(t,n,l){return t.concat(n).map((function(t){return cloneUnlessOtherwiseSpecified(t,l)}))}function getKeys(t){return Object.keys(t).concat(function(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(n){return t.propertyIsEnumerable(n)})):[]}(t))}function mergeObject(t,n,l){var d={};return l.isMergeableObject(t)&&getKeys(t).forEach((function(n){d[n]=cloneUnlessOtherwiseSpecified(t[n],l)})),getKeys(n).forEach((function(p){l.isMergeableObject(n[p])&&t[p]?d[p]=function(t,n){if(!n.customMerge)return deepmerge;var l=n.customMerge(t);return"function"==typeof l?l:deepmerge}(p,l)(t[p],n[p],l):d[p]=cloneUnlessOtherwiseSpecified(n[p],l)})),d}function deepmerge(t,n,l){(l=l||{}).arrayMerge=l.arrayMerge||defaultArrayMerge,l.isMergeableObject=l.isMergeableObject||isMergeableObject;var d=Array.isArray(n);return d===Array.isArray(t)?d?l.arrayMerge(t,n,l):mergeObject(t,n,l):cloneUnlessOtherwiseSpecified(n,l)}deepmerge.all=function(t,n){if(!Array.isArray(t))throw new Error("first argument should be an array");return t.reduce((function(t,l){return deepmerge(t,l,n)}),{})},function(t){t.dataRecordDidDelete="dataRecordDidDelete",t.dataRecordWillDelete="dataRecordWillDelete",t.dataRecordDidMaterialize="dataRecordDidMaterialize",t.dataRecordDidPopulate="dataRecordDidPopulate",t.dataRecordWillPopulate="dataRecordWillPopulate"}(fe||(fe={}));var isDataRecord=function(t){return!(!t||"function"!=typeof t.hasAttributes||"function"!=typeof t.hasRelationships||"function"!=typeof t.hasViews||"function"!=typeof t.serialize)},ve=function(){function DataRecord(t,n,l){void 0===l&&(l={}),this.type=t,this.id=n,this._mjs={attributes:[],relationships:[],views:[]},this._meta={},this._mjs=ne(ne({},this._mjs),l)}return DataRecord.prototype.hasProperties=function(t){return!t||(t.attributes||t.relationships||t.views?!(t.attributes&&!this.hasAttributes(t.attributes))&&(!(t.relationships&&!this.hasRelationships(t.relationships))&&!(t.views&&!this.hasViews(t.views))):this.hasAttributes()||this.hasRelationships()||this.hasViews())},DataRecord.prototype.hasAttributes=function(t){return this._hasProperties(this._mjs.attributes,t)},DataRecord.prototype.hasRelationships=function(t){return this._hasProperties(this._mjs.relationships,t)},DataRecord.prototype.hasViews=function(t){return this._hasProperties(this._mjs.views,t)},DataRecord.prototype.meta=function(t){return t?this._meta[t]:this._meta},DataRecord.prototype.serialize=function(t,n){var l=this;void 0===t&&(t=!0),void 0===n&&(n={});var d={id:this.id,type:this.type};return n[this.type+"-"+this.id]?d:(n[this.type+"-"+this.id]=!0,this.hasAttributes()&&(d.attributes=this._mjs.attributes.reduce((function(t,n){return t[n]=l[n],t}),{})),this._mjs.relationships.length>0&&(d.relationships=this._serializeRelatedData(this._mjs.relationships,n)),this._mjs.views.length>0&&(d.views=this._serializeRelatedData(this._mjs.views,n)),t?{data:d}:d)},DataRecord.prototype.setProperty=function(t,n,l,d){function isMergeableObject(t){return!(!t||"object"!=typeof t||t instanceof DataRecord)}void 0===l&&(l="attributes"),void 0===d&&(d={}),this.hasOwnProperty(t)||(this._mjs[l]||(this._mjs[l]=[]),this._mjs[l].push(t));var setDescriptor=function(t){return{value:t,writable:!0,configurable:!0,enumerable:!0}};this[t]&&n&&"object"==typeof this[t]&&"object"==typeof n?"attributes"===l?Object.defineProperty(this,t,setDescriptor(deepmerge(this[t],n,{arrayMerge:function(t,n,l){return n},isMergeableObject:isMergeableObject}))):"relationships"===l&&Array.isArray(this[t])&&d.extendRelationships?Object.defineProperty(this,t,setDescriptor(deepmerge(this[t],n,{isMergeableObject:isMergeableObject}))):Object.defineProperty(this,t,setDescriptor(n)):Object.defineProperty(this,t,setDescriptor(n))},DataRecord.prototype.removeRelative=function(t,n){this[t]&&(Array.isArray(this[t])?this[t]=this[t].filter((function(t){return t.id!==n})):delete this[t])},DataRecord.prototype.setParent=function(t){var n=this._mjs.parents,l=n&&n.length>0;this._mjs.parents=l?n.concat(t):t},DataRecord.prototype._hasProperties=function(t,n){return!!t&&(n?ensureArray(n).every((function(n){return t.includes(n)})):t.length>0)},DataRecord.prototype._serializeRelatedData=function(t,n){var l=this;return void 0===n&&(n={}),t.reduce((function(t,d){var p=l[d];return Array.isArray(p)?t[d]={data:p.map((function(t){return"function"==typeof t.serialize?t.serialize(!1,n):t}))}:t[d]=p&&"function"==typeof p.serialize?p.serialize(!1,n):p,t}),{})},DataRecord}(),ge=function(t){function DataStore(n){void 0===n&&(n={});var l=t.call(this,[fe.dataRecordDidDelete,fe.dataRecordWillDelete,fe.dataRecordDidMaterialize,fe.dataRecordWillPopulate,fe.dataRecordDidPopulate])||this;return l._removeOnExpiration=!1,l._records={},l._expiryRecords=new Set,l._removeOnExpiration=!!n.removeOnExpiration,l._mapping=n.mapping,l.filter=n.filter,l}return __extends$1(DataStore,t),Object.defineProperty(DataStore.prototype,"mapping",{get:function(){return this._mapping},set:function(t){this._mapping=t},enumerable:!0,configurable:!0}),DataStore.prototype.clear=function(){this._records={},this._expiryRecords=new Set},DataStore.prototype.peek=function(t,n,l){var d=this;if(this._checkForExpiredRecords(),!this._records[t])return n?null:[];if(!n)return Object.values(this._records[t]);if(Array.isArray(n))return n.map((function(n){var p=d._records[t][n];if(p&&p.hasProperties(l))return p}));var p=this._records[t][n];return p&&p.hasProperties(l)?p:null},DataStore.prototype.populateDataRecords=function(t,n,l){var d=this;if(void 0===n&&(n={}),void 0===l&&(l={}),!t.data)return[];if(!Array.isArray(t.data))return this.populateDataRecord(t.data,n,l);var p=[];return t.data.forEach((function(t,h){var f=ne(ne({},l),{parents:l.parents?[ne(ne({},l.parents[0]),{position:h})]:[]});l.parents&&(l.parents[0].position=h);var y=d.populateDataRecord(t,n,f);p.push(y)})),p},DataStore.prototype.populateDataRecord=function(t,n,l){var d=this;void 0===n&&(n={});var p=l.filter||this.filter,h=l.mapping||this.mapping;if(!p||p(t)){if(h){var f="function"==typeof h?h(t):transform(h,t);Object.assign(t,f)}var y=this._materializeRecord(n,ne({id:t.id,type:t.type},l));return t.meta&&(y._meta=t.meta),t.attributes&&t.attributes.cachingPolicy&&t.attributes.cachingPolicy.maxAge&&(y._mjs.expiration=Date.now()+1e3*t.attributes.cachingPolicy.maxAge,this._removeOnExpiration&&this._expiryRecords.add(y)),this._populateDataAttributes(t,y),"object"==typeof t.relationships&&Object.keys(t.relationships).forEach((function(p){var f=t.relationships[p];f&&"data"in f&&(f=d.populateDataRecords(f,n,{mapping:h,parents:[{relationshipName:p,parentType:y.type,parentId:y.id}]}),y.setProperty(p,f,"relationships",l))})),"object"==typeof t.views&&Object.keys(t.views).forEach((function(l){var p=t.views[l];if(p.attributes||p.data){var f=new ve("view",l);if(d._populateDataAttributes(p,f),p.data){var v=d.populateDataRecords(p,n,h);f.setProperty("data",v,"relationships")}y.setProperty(l,f,"views")}})),y}},DataStore.prototype.query=function(t,n){this._checkForExpiredRecords();var includeRecord=function(t){return!1};return"string"==typeof t&&n?includeRecord=function(l){return get(l,t)===n}:"function"==typeof t?includeRecord=function(n){try{return t(n)}catch(e){return!1}}:"object"==typeof t&&(includeRecord=function(n){var l=Object.keys(t),d=0;return l.forEach((function(l){get(n,l)===t[l]&&d++})),l.length===d}),Object.values(this._records).reduce((function(t,n){return Object.values(n).forEach((function(n){includeRecord(n)&&t.push(n)})),t}),[])},DataStore.prototype.remove=function(t,n){var l=this;if(setTimeout(this._checkForExpiredRecords.bind(this),0),this._records.hasOwnProperty(t)){var d=this.peek(t,n);d&&(this.dispatchEvent(fe.dataRecordWillDelete,[t,n]),d._mjs.parents&&d._mjs.parents.length>0&&d._mjs.parents.forEach((function(t){var n=t.relationshipName,p=t.parentType,h=t.parentId;l.peek(p,h).removeRelative(n,d.id)})),delete this._records[t][n],this.dispatchEvent(fe.dataRecordDidDelete,[t,n]))}},DataStore.prototype.save=function(t,n){return void 0===n&&(n={}),setTimeout(this._checkForExpiredRecords.bind(this),0),this.populateDataRecords(t,this._records,n)},DataStore.prototype._populateDataAttributes=function(t,n){"object"==typeof t.attributes&&(this.dispatchEvent(fe.dataRecordWillPopulate,[n.type,n.id]),Object.keys(t.attributes).forEach((function(l){n.setProperty(l,t.attributes[l],"attributes")})),this.dispatchEvent(fe.dataRecordDidPopulate,[n.type,n.id]))},DataStore.prototype._materializeRecord=function(t,n){var l=n.type,d=n.id,p=function(t,n){var l={};for(var d in t)Object.prototype.hasOwnProperty.call(t,d)&&n.indexOf(d)<0&&(l[d]=t[d]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var p=0;for(d=Object.getOwnPropertySymbols(t);p<d.length;p++)n.indexOf(d[p])<0&&(l[d[p]]=t[d[p]])}return l}(n,["type","id"]);return t[l]=t[l]||{},t[l][d]?t[l][d].setParent(p.parents||[]):t[l][d]=new ve(l,d,p),this.dispatchEvent(fe.dataRecordDidMaterialize,[l,d]),t[l][d]},DataStore.prototype._checkForExpiredRecords=function(){var t=this,n=[];this._expiryRecords.forEach((function(l){Date.now()>l._mjs.expiration&&(n.push([l.type,l.id]),t._expiryRecords.delete(l))})),n.forEach((function(n){t.remove.apply(t,__spread$1(n))}))},DataStore}(he),_e={400:"REQUEST_ERROR",401:"UNAUTHORIZED_ERROR",403:"ACCESS_DENIED",404:"NOT_FOUND",405:"NOT_FOUND",413:"REQUEST_ERROR",414:"REQUEST_ERROR",429:"QUOTA_EXCEEDED",500:"SERVER_ERROR",501:"NOT_FOUND",503:"SERVICE_UNAVAILABLE"},me={"-1004":"DEVICE_LIMIT",1010:_e[404],2002:"AUTHORIZATION_ERROR",2034:"TOKEN_EXPIRED",3059:"DEVICE_LIMIT",3063:"SUBSCRIPTION_ERROR",3076:"CONTENT_UNAVAILABLE",3082:"CONTENT_RESTRICTED",3084:"STREAM_UPSELL",5002:_e[500],180202:"PLAYREADY_CBC_ENCRYPTION_ERROR"},be=[],Pe=new Set(["UNSUPPORTED_ERROR","CONTENT_EQUIVALENT","CONTENT_UNAVAILABLE","CONTENT_UNSUPPORTED","SERVER_ERROR","SUBSCRIPTION_ERROR"]),ke=function(t){function MKError(n,l){var d=t.call(this)||this;return d.errorCode="UNKNOWN_ERROR",n&&Pe.has(n)?(d.name=d.errorCode=n,d.message=d.description=l||n):l||"string"!=typeof n?(d.name=d.errorCode=n||"UNKNOWN_ERROR",l&&(d.message=d.description=l)):(d.name=d.errorCode="UNKNOWN_ERROR",d.message=d.description=n),be.push(d),Error.captureStackTrace&&Error.captureStackTrace(d,MKError),d}return __extends$1(MKError,t),Object.defineProperty(MKError,"errors",{get:function(){return be},enumerable:!0,configurable:!0}),MKError.playActivityError=function(t){return new this("PLAY_ACTIVITY",t)},MKError.parseError=function(t){return new this("PARSE_ERROR",t)},MKError.responseError=function(t){var n=t.status,l=t.statusText;return new this(_e[n]||"NETWORK_ERROR",l||""+n)},MKError.serverError=function(t){var n=t.status,l=t.dialog,d=t.failureType,p=t.customerMessage,h=t.errorMessage,f=t.message;l&&(f=l.message||l.customerMessage||l.errorMessage,l.message=f);var y=me[d]||me[n]||"UNKNOWN_ERROR",v=new this(y,f||p||h);return"STREAM_UPSELL"===y&&l&&l.okButtonAction&&l.okButtonAction.url&&(l.okButtonAction.url=l.okButtonAction.url.replace(/\&(?:challenge|key-system|uri|user-initiated)=[^\&]+/gim,"")),v.dialog=l,v},MKError.internalError=function(t){return new this(MKError.INTERNAL_ERROR,t)},MKError.ACCESS_DENIED=_e[403],MKError.AGE_VERIFICATION="AGE_VERIFICATION",MKError.AUTHORIZATION_ERROR=me[2002],MKError.CONFIGURATION_ERROR="CONFIGURATION_ERROR",MKError.CONTENT_EQUIVALENT="CONTENT_EQUIVALENT",MKError.CONTENT_RESTRICTED=me[3082],MKError.CONTENT_UNAVAILABLE=me[3076],MKError.CONTENT_UNSUPPORTED="CONTENT_UNSUPPORTED",MKError.DEVICE_LIMIT=me[3059],MKError.INVALID_ARGUMENTS="INVALID_ARGUMENTS",MKError.PLAYREADY_CBC_ENCRYPTION_ERROR="PLAYREADY_CBC_ENCRYPTION_ERROR",MKError.MEDIA_CERTIFICATE="MEDIA_CERTIFICATE",MKError.MEDIA_DESCRIPTOR="MEDIA_DESCRIPTOR",MKError.MEDIA_LICENSE="MEDIA_LICENSE",MKError.MEDIA_KEY="MEDIA_KEY",MKError.MEDIA_PLAYBACK="MEDIA_PLAYBACK",MKError.MEDIA_SESSION="MEDIA_SESSION",MKError.NETWORK_ERROR="NETWORK_ERROR",MKError.NOT_FOUND=me[1010],MKError.PARSE_ERROR="PARSE_ERROR",MKError.PLAY_ACTIVITY="PLAY_ACTIVITY",MKError.QUOTA_EXCEEDED=_e[429],MKError.REQUEST_ERROR=_e[400],MKError.SERVER_ERROR=me[5002],MKError.SERVICE_UNAVAILABLE=_e[503],MKError.STREAM_UPSELL=me[3084],MKError.SUBSCRIPTION_ERROR=me[3063],MKError.TOKEN_EXPIRED=me[2034],MKError.UNAUTHORIZED_ERROR=_e[401],MKError.UNKNOWN_ERROR="UNKNOWN_ERROR",MKError.UNSUPPORTED_ERROR="UNSUPPORTED_ERROR",MKError.INTERNAL_ERROR="INTERNAL_ERROR",MKError}(Error);var Te,Se,Ae,we,Ie,Ee,Re,Oe,Ce,Me,De,Le,Ne,xe,Ue=function(){function PubSub(){this.events={}}return PubSub.prototype.publish=function(t,n){var l=this.getSubscribersForType(t);void 0!==l&&l.forEach((function(l){l(t,n)}))},PubSub.prototype.subscribe=function(t,n){this.getSubscribersForType(t,!0).push(n)},PubSub.prototype.subscribeOnce=function(t,n){var l=this,onceCallback=function(t,d){l.unsubscribe(t,onceCallback),n(t,d)};this.subscribe(t,onceCallback)},PubSub.prototype.unsubscribe=function(t,n){var l=this.getSubscribersForType(t);if(void 0!==l)for(var d in l)if(l[d]===n){delete l[d];break}},PubSub.prototype.clear=function(t){void 0===t?this.events={}:delete this.events[t]},PubSub.prototype.getSubscribersForType=function(t,n){return void 0===n&&(n=!1),!this.events.hasOwnProperty(t)&&n&&(this.events[t]=[]),this.events[t]},PubSub}();!function(t){t.MUSICKIT="music_kit-integration",t.OTHER="other",t.MINI="mini",t.SONG="song",t.ALBUM="album",t.ALBUM_CLASSICAL="album-classical",t.ARTIST="artist",t.COMPILATION="compilation",t.COMPILATION_CLASSICAL="compilation-classical",t.PLAYLIST="playlist",t.PLAYLIST_CLASSICAL="playlist-classical",t.SEARCH="search",t.STATION="station"}(Te||(Te={})),function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.RADIO=1]="RADIO",t[t.PLAYLIST=2]="PLAYLIST",t[t.ALBUM=3]="ALBUM",t[t.ARTIST=4]="ARTIST"}(Se||(Se={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.STATIC=1]="STATIC",t[t.TIME_SYNCED=2]="TIME_SYNCED"}(Ae||(Ae={})),function(t){t[t.REPEAT_UNKNOWN=0]="REPEAT_UNKNOWN",t[t.REPEAT_OFF=1]="REPEAT_OFF",t[t.REPEAT_ONE=2]="REPEAT_ONE",t[t.REPEAT_ALL=3]="REPEAT_ALL"}(we||(we={})),function(t){t[t.SHUFFLE_UNKNOWN=0]="SHUFFLE_UNKNOWN",t[t.SHUFFLE_OFF=1]="SHUFFLE_OFF",t[t.SHUFFLE_ON=2]="SHUFFLE_ON"}(Ie||(Ie={})),function(t){t[t.AUTO_UNKNOWN=0]="AUTO_UNKNOWN",t[t.AUTO_OFF=1]="AUTO_OFF",t[t.AUTO_ON=2]="AUTO_ON",t[t.AUTO_ON_CONTENT_UNSUPPORTED=3]="AUTO_ON_CONTENT_UNSUPPORTED"}(Ee||(Ee={})),(Re=t.PlayActivityEndReasonType||(t.PlayActivityEndReasonType={}))[Re.NOT_APPLICABLE=0]="NOT_APPLICABLE",Re[Re.OTHER=1]="OTHER",Re[Re.TRACK_SKIPPED_FORWARDS=2]="TRACK_SKIPPED_FORWARDS",Re[Re.PLAYBACK_MANUALLY_PAUSED=3]="PLAYBACK_MANUALLY_PAUSED",Re[Re.PLAYBACK_SUSPENDED=4]="PLAYBACK_SUSPENDED",Re[Re.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM=5]="MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM",Re[Re.PLAYBACK_PAUSED_DUE_TO_INACTIVITY=6]="PLAYBACK_PAUSED_DUE_TO_INACTIVITY",Re[Re.NATURAL_END_OF_TRACK=7]="NATURAL_END_OF_TRACK",Re[Re.PLAYBACK_STOPPED_DUE_TO_SESSION_TIMEOUT=8]="PLAYBACK_STOPPED_DUE_TO_SESSION_TIMEOUT",Re[Re.TRACK_BANNED=9]="TRACK_BANNED",Re[Re.FAILED_TO_LOAD=10]="FAILED_TO_LOAD",Re[Re.PAUSED_ON_TIMEOUT=11]="PAUSED_ON_TIMEOUT",Re[Re.SCRUB_BEGIN=12]="SCRUB_BEGIN",Re[Re.SCRUB_END=13]="SCRUB_END",Re[Re.TRACK_SKIPPED_BACKWARDS=14]="TRACK_SKIPPED_BACKWARDS",Re[Re.NOT_SUPPORTED_BY_CLIENT=15]="NOT_SUPPORTED_BY_CLIENT",Re[Re.QUICK_PLAY=16]="QUICK_PLAY",Re[Re.EXITED_APPLICATION=17]="EXITED_APPLICATION",function(t){t[t.NOT_SPECIFIED=0]="NOT_SPECIFIED",t[t.CONTAINER_CHANGED=1]="CONTAINER_CHANGED"}(Oe||(Oe={})),function(t){t[t.PLAY_END=0]="PLAY_END",t[t.PLAY_START=1]="PLAY_START",t[t.LYRIC_DISPLAY=2]="LYRIC_DISPLAY"}(Ce||(Ce={})),function(t){t[t.INVALID=0]="INVALID",t[t.ITUNES_STORE_CONTENT=1]="ITUNES_STORE_CONTENT",t[t.NON_SONG_CLIP=2]="NON_SONG_CLIP",t[t.AD=3]="AD",t[t.STREAM=4]="STREAM",t[t.AUDIO_AD=5]="AUDIO_AD",t[t.VIDEO_AD=6]="VIDEO_AD",t[t.TIMED_METADATA_PING=7]="TIMED_METADATA_PING",t[t.ARTIST_UPLOADED_CONTENT=8]="ARTIST_UPLOADED_CONTENT",t[t.AGGREGATE_NON_CATALOG_PLAY_TIME=9]="AGGREGATE_NON_CATALOG_PLAY_TIME",t[t.ORIGINAL_CONTENT_MOVIES=10]="ORIGINAL_CONTENT_MOVIES",t[t.ORIGINAL_CONTENT_SHOWS=11]="ORIGINAL_CONTENT_SHOWS"}(Me||(Me={})),function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"}(De||(De={})),function(t){t[t.AUTO=0]="AUTO",t[t.MANUAL=1]="MANUAL"}(Le||(Le={})),function(t){t[t.WEBPLAYER=8]="WEBPLAYER",t[t.MUSICKIT=10]="MUSICKIT",t[t.THIRD_PARTY_TV=18]="THIRD_PARTY_TV"}(Ne||(Ne={})),function(t){t[t.EPISODE=1]="EPISODE",t[t.SHOUTCAST=2]="SHOUTCAST"}(xe||(xe={}));
/*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */
var extendStatics$2=function(t,n){return(extendStatics$2=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var l in n)n.hasOwnProperty(l)&&(t[l]=n[l])})(t,n)};function __extends$2(t,n){function __(){this.constructor=t}extendStatics$2(t,n),t.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}var Be,__assign$2=function(){return(__assign$2=Object.assign||function(t){for(var n,l=1,d=arguments.length;l<d;l++)for(var p in n=arguments[l])Object.prototype.hasOwnProperty.call(n,p)&&(t[p]=n[p]);return t}).apply(this,arguments)};function __awaiter$2(t,n,l,d){return new(l||(l=Promise))((function(p,h){function fulfilled(t){try{step(d.next(t))}catch(e){h(e)}}function rejected(t){try{step(d.throw(t))}catch(e){h(e)}}function step(t){t.done?p(t.value):new l((function(n){n(t.value)})).then(fulfilled,rejected)}step((d=d.apply(t,n||[])).next())}))}function __generator$2(t,n){var l,d,p,h,f={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return h={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(h[Symbol.iterator]=function(){return this}),h;function verb(h){return function(y){return function(h){if(l)throw new TypeError("Generator is already executing.");for(;f;)try{if(l=1,d&&(p=2&h[0]?d.return:h[0]?d.throw||((p=d.return)&&p.call(d),0):d.next)&&!(p=p.call(d,h[1])).done)return p;switch(d=0,p&&(h=[2&h[0],p.value]),h[0]){case 0:case 1:p=h;break;case 4:return f.label++,{value:h[1],done:!1};case 5:f.label++,d=h[1],h=[0];continue;case 7:h=f.ops.pop(),f.trys.pop();continue;default:if(!(p=f.trys,(p=p.length>0&&p[p.length-1])||6!==h[0]&&2!==h[0])){f=0;continue}if(3===h[0]&&(!p||h[1]>p[0]&&h[1]<p[3])){f.label=h[1];break}if(6===h[0]&&f.label<p[1]){f.label=p[1],p=h;break}if(p&&f.label<p[2]){f.label=p[2],f.ops.push(h);break}p[2]&&f.ops.pop(),f.trys.pop();continue}h=n.call(t,f)}catch(e){h=[6,e],d=0}finally{l=p=0}if(5&h[0])throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}([h,y])}}}function __values$1(t){var n="function"==typeof Symbol&&t[Symbol.iterator],l=0;return n?n.call(t):{next:function(){return t&&l>=t.length&&(t=void 0),{value:t&&t[l++],done:!t}}}}function __read$2(t,n){var l="function"==typeof Symbol&&t[Symbol.iterator];if(!l)return t;var d,p,h=l.call(t),f=[];try{for(;(void 0===n||n-- >0)&&!(d=h.next()).done;)f.push(d.value)}catch(ba){p={error:ba}}finally{try{d&&!d.done&&(l=h.return)&&l.call(h)}finally{if(p)throw p.error}}return f}!function(t){t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped"}(Be||(Be={}));var je={type:"xstate.init"};function e(t){return void 0===t?[]:[].concat(t)}function r(t){return{type:"xstate.assign",assignment:t}}function i(t,n){return"string"==typeof(t="string"==typeof t&&n&&n[t]?n[t]:t)?{type:t}:"function"==typeof t?{type:t.name,exec:t}:t}function o(t){return function(n){return t===n}}function a(t){return"string"==typeof t?{type:t}:t}function u(t,n){return{value:t,context:n,actions:[],changed:!1,matches:o(t)}}function c(t,n){void 0===n&&(n={});var l={config:t,_options:n,initialState:{value:t.initial,actions:e(t.states[t.initial].entry).map((function(t){return i(t,n.actions)})),context:t.context,matches:o(t.initial)},transition:function(n,d){var p,h,f="string"==typeof n?{value:n,context:t.context}:n,y=f.value,v=f.context,g=a(d),_=t.states[y];if(_.on){var m=e(_.on[g.type]),x=function(n){if(void 0===n)return{value:u(y,v)};var d="string"==typeof n?{target:n}:n,p=d.target,h=void 0===p?y:p,f=d.actions,m=void 0===f?[]:f,b=d.cond,P=v;if((void 0===b?function(){return!0}:b)(v,g)){var k=t.states[h],T=!1,S=[].concat(_.exit,m,k.entry).filter((function(t){return t})).map((function(t){return i(t,l._options.actions)})).filter((function(t){if("xstate.assign"===t.type){T=!0;var n=Object.assign({},P);return"function"==typeof t.assignment?n=t.assignment(P,g):Object.keys(t.assignment).forEach((function(l){n[l]="function"==typeof t.assignment[l]?t.assignment[l](P,g):t.assignment[l]})),P=n,!1}return!0}));return{value:{value:h,context:P,actions:S,changed:h!==y||S.length>0||T,matches:o(h)}}}};try{for(var b=function(t){var n="function"==typeof Symbol&&t[Symbol.iterator],l=0;return n?n.call(t):{next:function(){return t&&l>=t.length&&(t=void 0),{value:t&&t[l++],done:!t}}}}(m),P=b.next();!P.done;P=b.next()){var k=x(P.value);if("object"==typeof k)return k.value}}catch(t){p={error:t}}finally{try{P&&!P.done&&(h=b.return)&&h.call(b)}finally{if(p)throw p.error}}}return u(y,v)}};return l}var s=function(t,n){return t.actions.forEach((function(l){var d=l.exec;return d&&d(t.context,n)}))};function f$3(t){var n=t.initialState,l=Be.NotStarted,d=new Set,p={_machine:t,send:function(p){l===Be.Running&&(n=t.transition(n,p),s(n,a(p)),d.forEach((function(t){return t(n)})))},subscribe:function(t){return d.add(t),t(n),{unsubscribe:function(){return d.delete(t)}}},start:function(){return l=Be.Running,s(n,je),p},stop:function(){return l=Be.Stopped,d.clear(),p},get state(){return n},get status(){return l}};return p}var createInvocableResolver=function(t){return function(n){return null==n||t(n)?n:n()}},Fe=createInvocableResolver((function(t){return"string"==typeof t})),Ke=createInvocableResolver((function(t){return"boolean"==typeof t})),Ve=/(?:st|ra)\.([0-9]+)/,$e=/st\.([0-9]+)/,He=function(){function PlayActivitySender(t){var n,l,d,p;this.mode=Le.AUTO,this._isQA=!1,this._logInfo=!1,this._preferDSID=!1,this._accessToken=t.accessToken,this._clientId=t.clientId,this._eventType=t.eventType,this._fetch=null!==(n=t.fetch)&&void 0!==n?n:fetch,this._fetchOptions=null!==(l=t.fetchOptions)&&void 0!==l?l:{},this._headersClass=null!==(d=t.headersClass)&&void 0!==d?d:Headers,this._isQA=null!==(p=t.isQA)&&void 0!==p&&p,this._logInfo=t.logInfo||this._isQA,this._musicUserToken=t.musicUserToken,this._preferDSID=t.preferDSID,this._sourceType=t.sourceType,this._traceTag=t.traceTag}return Object.defineProperty(PlayActivitySender.prototype,"accessToken",{get:function(){return Fe(this._accessToken)},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivitySender.prototype,"musicUserToken",{get:function(){return Fe(this._musicUserToken)},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivitySender.prototype,"url",{get:function(){return this._isQA?"https://universal-activity-service.itunes.apple.com/qa/play":"https://universal-activity-service.itunes.apple.com/play"},enumerable:!0,configurable:!0}),PlayActivitySender.prototype.send=function(t){return __awaiter$2(this,void 0,void 0,(function(){var n,l;return __generator$2(this,(function(d){switch(d.label){case 0:if(0===(n={client_id:this._clientId,event_type:this._eventType,data:ensureArray(t)}).data.length)throw new Error("send() called without any data");return l=this._generateFetchOptions({method:"POST",body:JSON.stringify(n),headers:this.headers()}),[4,this._fetch(this.url,l)];case 1:return[4,d.sent().text()];case 2:return d.sent(),this._logInfo&&console.info("play activity:",13===this._sourceType?JSON.stringify(n):n),[2,n]}}))}))},PlayActivitySender.prototype.baseHeaders=function(){var t,n,l=null!==(n=null===(t=this._fetchOptions)||void 0===t?void 0:t.headers)&&void 0!==n?n:{};return l instanceof this._headersClass?new this._headersClass(Array.from(l.entries())):new this._headersClass(l)},PlayActivitySender.prototype.headers=function(){var t=this._preferDSID?"X-Dsid":"media-user-token",n=this.baseHeaders();return n.set("Authorization","Bearer "+this.accessToken),n.set("Content-Type","application/json"),n.set(t,""+this.musicUserToken),this._isQA&&void 0!==this._traceTag&&n.set("Data-Trace-Tag",this._traceTag),n},PlayActivitySender.prototype._generateFetchOptions=function(t){return __assign$2(__assign$2({},this._fetchOptions),t)},PlayActivitySender}(),conditionalObject=function(t,n,l){var d;return t?((d={})[n]=l,d):{}},buildObject=function(t,n){return conditionalObject(void 0!==n,t,n)};var ze,fullAppId=function(t,n){return void 0===(null==n?void 0:n.name)?"MusicKitApp/1.0":void 0!==t?t:function(t){return t.toLowerCase().replace(/[-_]+/g," ").replace(/[^\w\s]/g,"").replace(/\b./g,(function(t){return t.toUpperCase()})).replace(/\s/g,"")}(n.name)+"/"+((null==n?void 0:n.version)||"1.0")},os=function(t){var n,l,d,p,h=t.toLowerCase(),f="Unidentified OS",y=/mobile/.test(h);return y&&/android|adr/.test(h)?(f="Android",p=h.match(/(?:android|adr)\ ((\d+[._])+\d+)/)):y&&/iphone|ipad|ipod/.test(h)?(f="iOS",p=h.match(/os\ ((\d+[._])+\d+)\ like\ mac\ os\ x/)):/tizen/.test(h)?(f="Tizen",p=h.match(/tizen (.*)/)):/web0s|webos/.test(h)?(f="WebOS",p=h.match(/[web0s|webos] (.*)/)):!y&&/cros/.test(h)?f="ChromeOS":!y&&/macintosh/.test(h)?(f="macOS",p=h.match(/os\ x\ ((\d+[._])+\d+)\b/)):!y&&/linux/.test(h)?f="Linux":!y&&/windows/.test(h)&&(f="Windows",p=h.match(/windows ([^\)]*)/)),f+"/"+(null!==(d=null===(l=null===(n=null==p?void 0:p[1])||void 0===n?void 0:n.replace)||void 0===l?void 0:l.call(n,/_/g,"."))&&void 0!==d?d:"0.0")},model=function(t){return"model/"+((null==t?void 0:t.platform)||"Unavailable")},build=function(t){var n=null==t?void 0:t.build;return void 0===n||""===n?"build/0.0.0":"build/"+n},We={platform:"",userAgent:""},Ye=function(){function PlayActivityBase(t,n,l,d){var p,h,f;this._accessToken=t,this._musicUserToken=n,this.storefrontId=l,this.privateEnabled=!1,this.siriInitiated=!1,this.clientId="JSCLIENT",this.eventType="JSPLAY",this.internalBuild=!1,this.preferDSID=!1,this.sourceType=Ne.MUSICKIT,this._utcOffset=(new Date).getTimezoneOffset(),this._userIsSubscribed=!0,d&&(this._appInfo=d.app,this._navigator=d.navigator,this._userAgent=d.userAgent,d.hasOwnProperty("utcOffset")&&isNaN(d.utcOffset)?this._utcOffsetInSeconds=-1:d.hasOwnProperty("utcOffset")&&(this._utcOffset=d.utcOffset),this.clientId=d.clientId||"JSCLIENT",this._deviceName=d.deviceName,this.guid=d.guid,this.preferDSID=null!==(p=d.preferDSID)&&void 0!==p&&p,this.sourceType=d.sourceType&&"number"==typeof d.sourceType?d.sourceType:Ne.MUSICKIT,this._userIsSubscribed=null===(h=d.userIsSubscribed)||void 0===h||h),this.buildVersion=function(t,n,l,d){return[fullAppId(t,n),os(d),model(l),build(n)].join(" ")}(this._appId,this._appInfo,this.navigator,this.userAgent),this.sender=new He({accessToken:this._accessToken,clientId:this.clientId,eventType:this.eventType,fetch:null==d?void 0:d.fetch,fetchOptions:null==d?void 0:d.fetchOptions,headersClass:null===(f=null==d?void 0:d.fetch)||void 0===f?void 0:f.Headers,isQA:null==d?void 0:d.isQA,logInfo:null==d?void 0:d.logInfo,musicUserToken:this._musicUserToken,preferDSID:this.preferDSID,sourceType:this.sourceType,traceTag:null==d?void 0:d.traceTag})}return Object.defineProperty(PlayActivityBase.prototype,"accessToken",{get:function(){return Fe(this._accessToken)},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivityBase.prototype,"appID",{get:function(){return void 0===this._appId&&(this._appId=fullAppId(this._appId,this._appInfo)),this._appId},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivityBase.prototype,"musicUserToken",{get:function(){return Fe(this._musicUserToken)},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivityBase.prototype,"navigator",{get:function(){var t;return null!==(t=this._navigator)&&void 0!==t?t:"undefined"==typeof navigator?We:navigator},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivityBase.prototype,"userAgent",{get:function(){var t;return null!==(t=this._userAgent)&&void 0!==t?t:this.navigator.userAgent},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivityBase.prototype,"userIsSubscribed",{get:function(){return Ke(this._userIsSubscribed)},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivityBase.prototype,"utcOffsetInSeconds",{get:function(){if(void 0===this._utcOffsetInSeconds&&void 0!==this._utcOffset&&!isNaN(this._utcOffset)){var t=60*this._utcOffset;this._utcOffsetInSeconds=t<=0?Math.abs(t):-t}return void 0===this._utcOffsetInSeconds||isNaN(this._utcOffsetInSeconds)?-1:this._utcOffsetInSeconds},enumerable:!0,configurable:!0}),PlayActivityBase.prototype.send=function(t){return __awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(n){return[2,this.sender.send(t)]}))}))},PlayActivityBase.prototype.buildDescriptorForPlayParams=function(t,n,l,d,p){var h="stream"===t.format?Me.STREAM:Me.ITUNES_STORE_CONTENT;return __assign$2(__assign$2(__assign$2({},t),{container:l,duration:null!=d?d:0,eventType:n,itemType:h}),p)},PlayActivityBase.prototype.buildForPlayParams=function(t,n,l,d,p,h){return void 0===d&&(d=0),void 0===p&&(p={}),void 0===h&&(h=!1),this.build(this.buildDescriptorForPlayParams(t,n,l,d,p),h)},PlayActivityBase.prototype.generateBaseActivityData=function(){return __assign$2(__assign$2(__assign$2({"build-version":this.buildVersion,"container-type":Se.UNKNOWN,"developer-token":this.accessToken,"internal-build":this.internalBuild,offline:!1,"persistent-id":generateUUID(),"private-enabled":this.privateEnabled,"sb-enabled":this.userIsSubscribed,"siri-initiated":this.siriInitiated,"source-type":this.sourceType,"store-front":this.storefrontId,"user-agent":this.userAgent,"utc-offset-in-seconds":this.utcOffsetInSeconds},conditionalObject(!this.preferDSID,"user-token",this.musicUserToken)),buildObject("device-name",this._deviceName)),buildObject("guid",this.guid))},PlayActivityBase}(),pipe=function(t){for(var n=[],l=1;l<arguments.length;l++)n[l-1]=arguments[l];return n.reduce((function(t,n){return n(t)}),t)},qe=["uploadedVideo","uploadedAudio","uploaded-videos","uploaded-audios"],isAUC=function(t){return void 0!==t&&qe.includes(t)},isLiveStream=function(t){return function(t){return t.itemType===Me.STREAM}(t)&&!function(t){return t.descriptor.streamingKind===xe.EPISODE}(t)},updatedDataByEventType=function(t,n){switch(n["event-type"]){case Ce.PLAY_START:return function(t){var n={};return isLiveStream(t)&&(n["start-position-in-milliseconds"]=0),!1===t.previous&&t.isAlexa?n["event-reason-hint-type"]=Oe.NOT_SPECIFIED:n["event-reason-hint-type"]=t.containerChanged?Oe.CONTAINER_CHANGED:Oe.NOT_SPECIFIED,n}(t);case Ce.PLAY_END:return function(t,n){var l=t.descriptor,d=l.endPositionInMilliseconds,p=l.startPositionInMilliseconds,h=t.previous;if(h&&void 0===h.position)return{};var f=n["media-duration-in-milliseconds"],y=n["start-position-in-milliseconds"],v=y>f,g=h&&void 0!==h.position?Math.round(1e3*h.position):0;return __assign$2(__assign$2({"end-position-in-milliseconds":d||y,"end-reason-type":t.endReasonType},buildObject("media-duration-in-milliseconds",v?y:void 0)),{"start-position-in-milliseconds":p||g||0})}(t,n);default:return{}}},byEventType=function(t){var n=t.state,l=t.data;return{state:n,data:__assign$2(__assign$2({},l),updatedDataByEventType(n,l))}},byItemType=function(t){var n=t.data,l=t.state,d=l.itemType,p=__assign$2({},n);return isLiveStream(l)&&(p["media-duration-in-milliseconds"]=0),d===Me.AGGREGATE_NON_CATALOG_PLAY_TIME&&(p["start-position-in-milliseconds"]=0,delete p.ids,delete p["container-ids"],delete p["container-type"],delete p["reco-data"],delete p["feature-name"],p["play-mode"]&&(p["play-mode"]={"auto-play-mode":Ee.AUTO_UNKNOWN,"repeat-play-mode":we.REPEAT_UNKNOWN,"shuffle-play-mode":Ie.SHUFFLE_UNKNOWN})),{state:l,data:p}},buildContainerIds=function(t,n){switch(t){case Se.ALBUM:return function(t){var n={};return n["container-ids"]=ae(t.id)?{"cloud-album-id":t.id}:{"album-adam-id":t.id},n}(n);case Se.PLAYLIST:return function(t){var n={};return t.isLibrary&&(t.catalogId||t.globalId)?(n["container-ids"]={"global-playlist-id":t.catalogId||t.globalId},void 0!==t.id&&""!==t.id&&(n["container-ids"]["universal-library-id"]=t.id)):n["container-ids"]=ae(t.id)?{"universal-library-id":t.id}:{"global-playlist-id":t.id},void 0!==t.versionHash&&""!==t.versionHash&&(n["container-ids"]["playlist-version-hash"]=t.versionHash),n}(n);case Se.RADIO:return function(t){var n={};return n["container-ids"]={"station-id":t.id},$e.test(t.id)&&(n["container-ids"]["station-personalized-id"]=parseInt(t.id.replace($e,"$1"),10)),void 0!==t.stationHash&&""!==t.stationHash&&(n["container-ids"]["station-hash"]=t.stationHash),n}(n);default:return{}}},buildDataByType=function(t){var n=function(t){var n=t.type;if("number"==typeof n)return n;switch(n){case"album":case"albums":case"library-albums":return Se.ALBUM;case"artist":case"artists":case"library-artists":return Se.ARTIST;case"playlist":case"playlists":case"library-playlists":return Se.PLAYLIST;case"radio":case"radioStation":case"station":case"stations":return Se.RADIO;default:return Se.UNKNOWN}}(t);return 0===n?{}:__assign$2({"container-type":n},buildContainerIds(n,t))},updatedDataFromContainer=function(t){var n=t.descriptor.container;return void 0===n?{}:__assign$2({"feature-name":""+(n.name||Te.MUSICKIT)},buildDataByType(n))},buildDataFromContainer=function(t){var n=t.data,l=t.state;return{state:l,data:__assign$2(__assign$2({},n),updatedDataFromContainer(l))}},Ge=t.PlayActivityEndReasonType,Qe={exit:Ge.EXITED_APPLICATION,next:Ge.TRACK_SKIPPED_FORWARDS,pause:Ge.PLAYBACK_MANUALLY_PAUSED,playbackfinished:Ge.NATURAL_END_OF_TRACK,playbackstopped:Ge.PLAYBACK_MANUALLY_PAUSED,previous:Ge.TRACK_SKIPPED_BACKWARDS,scrub_begin:Ge.SCRUB_BEGIN,scrub_end:Ge.SCRUB_END,stop:Ge.NATURAL_END_OF_TRACK},convertEventString=function(t,n){var l=function(t){return t.toLowerCase()}(t);return __assign$2(__assign$2({},function(t){return{eventType:"play"===t||"playbackstarted"===t?Ce.PLAY_START:Ce.PLAY_END}}(l)),buildObject("endReasonType",function(t,n){return null!=n?n:Qe[t]}(l,n)))},defaultCatalogId=function(t){var n=t.catalogId,l=t.container;return n||l&&l.catalogId},defaultMediaType=function(t){if(void 0!==t.mediaType)return t.mediaType;var n=t.kind;return n&&/video/i.test(n)?De.VIDEO:De.AUDIO},defaultPrevious=function(t,n){var l=n;if(!1!==l&&t.eventType===Ce.PLAY_END&&void 0===n)throw new Error("Cannot build() for PLAY_END descriptors without previous descriptors");return l},defaultItemType=function(t){var n=t.itemType,l=t.kind;return"stream"===t.format?Me.STREAM:isAUC(l)?Me.ARTIST_UPLOADED_CONTENT:void 0!==n?n:Me.ITUNES_STORE_CONTENT},initialBuildData=function(n,l,d,p){var h=function(t){if(void 0===t)throw new Error("build() called without a play activity descriptor");return"string"!=typeof t.eventType?t:__assign$2(__assign$2({},t),convertEventString(t.eventType,t.endReasonType))}(l),f=function(t,n,l){return{catalogId:defaultCatalogId(t),cloudId:t.cloudId,containerChanged:!1,descriptor:t,endReasonType:t.endReasonType,isAlexa:l,itemType:defaultItemType(t),mediaType:defaultMediaType(t),previous:defaultPrevious(t,n)}}(h,d,p),y=h.eventType,v=void 0===y?Ce.PLAY_START:y,g=function(n){var l=n.descriptor,d={},p=__assign$2({},n),h=l.container,f=l.eventType,y=void 0===f?Ce.PLAY_START:f,v=l.id,g=l.isLibrary,_=l.purchasedId,m=l.reporting;if("-1"!==v&&(void 0===m||m))Ve.test(v)||h&&"radioStation"===h.kind?d["radio-adam-id"]=parseInt(v.replace(Ve,"$1"),10):isAUC(l.kind)?d["auc-adam-id"]=l.id:g&&p.catalogId?(d["subscription-adam-id"]=p.catalogId,void 0!==v&&""!==v&&(p.cloudId=v)):g||ae(v)?p.cloudId=v:d["subscription-adam-id"]=v;else switch(y){case Ce.PLAY_END:p.endReasonType=t.PlayActivityEndReasonType.NOT_APPLICABLE,p.itemType=Me.AGGREGATE_NON_CATALOG_PLAY_TIME;break;case Ce.PLAY_START:"-1"===v?p.itemType=Me.INVALID:void 0!==v&&""!==v&&(p.cloudId=v)}return void 0!==p.cloudId&&(d["cloud-id"]=p.cloudId),void 0!==_&&(d["purchased-adam-id"]=_),Object.keys(d).length>0?{ids:d,newState:p}:{newState:p,ids:void 0}}(f),_=g.ids;return(f=g.newState).containerChanged=function(t,n){var l=t.container,d=n.previous;return void 0!==l&&(void 0===l.type&&void 0!==l.kind&&(l.type=l.kind),void 0===d||!1===d||void 0===d.container||d.container.id!==l.id)}(h,f),{data:__assign$2(__assign$2(__assign$2(__assign$2(__assign$2(__assign$2(__assign$2({},n),function(t){var n=t.duration,l=void 0===n?0:n,d=t.position,p=void 0===d?0:d,h=t.timestamp,f=t.startPositionInMilliseconds;return{"media-duration-in-milliseconds":Math.round(1e3*l),"milliseconds-since-play":void 0!==h?Date.now()-h:0,"start-position-in-milliseconds":f||Math.round(1e3*p)}}(f.descriptor)),function(t){var n,l,d,p=t.playMode;return void 0===p?{}:{"play-mode":{"auto-play-mode":null!==(n=p.autoPlayMode)&&void 0!==n?n:0,"repeat-play-mode":null!==(l=p.repeatPlayMode)&&void 0!==l?l:0,"shuffle-play-mode":null!==(d=p.shufflePlayMode)&&void 0!==d?d:0}}}(f.descriptor)),buildObject("guid",f.descriptor.guid)),buildObject("ids",_)),buildObject("reco-data",f.descriptor.recoData)),{"event-type":v,"media-type":f.mediaType,type:f.itemType}),state:f}},buildPlayActivityData=function(t,n,l,d){if(void 0===d&&(d=!1),void 0===n)throw new Error("called without a play activity descriptor");return pipe(initialBuildData(t,n,l,d),byEventType,buildDataFromContainer,byItemType)},dataFromLyrics=function(t){var n=t.state.descriptor.lyricDescriptor,l=t.data.ids;return void 0===n?{}:__assign$2(__assign$2({"display-type":n.displayType,"end-position-in-milliseconds":n.duration},buildObject("lyric-language",n.language)),{ids:__assign$2(__assign$2({},l),{"lyric-id":n.id})})},forLyrics=function(t){var n=t.state,l=t.data;return{state:n,data:__assign$2(__assign$2({},l),dataFromLyrics({state:n,data:l}))}},buildPlayActivityData$1=function(t,n,l){if(void 0===n)throw new Error("called without a play activity descriptor");return pipe(buildPlayActivityData(t,n,l,!1),(d={"event-type":Ce.LYRIC_DISPLAY,"feature-name":"now_playing","media-duration-in-milliseconds":0,"media-type":De.AUDIO,"start-position-in-milliseconds":0},function(t){var n=t.state,l=t.data;return{state:n,data:__assign$2(__assign$2({},l),d)}}),function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return function(n){var l,d,p=n.state,h=n.data,f=__assign$2({},h);try{for(var y=__values$1(t),v=y.next();!v.done;v=y.next()){delete f[v.value]}}catch(g){l={error:g}}finally{try{v&&!v.done&&(d=y.return)&&d.call(y)}finally{if(l)throw l.error}}return{state:p,data:f}}}("character-display-count","event-reason-hint-type","reco-data"),forLyrics);var d},Je=Date.now(),Xe=isNodeEnvironment()?function(){var t=__read$1(process.hrtime(),2),n=t[0],l=t[1];return Math.floor(1e3*n+1e-6*l)}:function(){var t,n;return null!==(n=null===(t=null===performance||void 0===performance?void 0:performance.now)||void 0===t?void 0:t.call(performance))&&void 0!==n?n:Date.now()-Je};!function(t){function LyricsPlayActivity(n,l,d,p){var h=t.call(this,n,l,d,p)||this;return h._machine=f$3(c({id:"lpaf",initial:"idle",context:{initialShowTime:-1,duration:-1},states:{idle:{entry:r((function(t){return __assign$2(__assign$2({},t),{initialShowTime:void 0,duration:Xe()-t.initialShowTime})})),on:{play:"playing"}},playing:{entry:r((function(t){return __assign$2(__assign$2({},t),{initialShowTime:Xe()})})),on:{stop:"idle"}}}})).start(),h}__extends$2(LyricsPlayActivity,t),LyricsPlayActivity.prototype.exit=function(){return __awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(t){return[2]}))}))},LyricsPlayActivity.prototype.play=function(t){return __awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(n){if(this.stateMatches("playing"))throw Error("lyrics are already being displayed. Did you forget to stop them?");return this._previousDescriptor=t,this._machine.send({type:"play"}),[2]}))}))},LyricsPlayActivity.prototype.stop=function(){return __awaiter$2(this,void 0,void 0,(function(){var t,n;return __generator$2(this,(function(l){switch(l.label){case 0:if(this.stateMatches("idle"))throw Error("lyrics are not being displayed. Did you forget to display them?");if(void 0===this._previousDescriptor)throw Error("something went wrong: client can send a stop but there is no previous descriptor");this._machine.send({type:"stop"}),(t=JSON.parse(JSON.stringify(this._previousDescriptor))).lyricDescriptor=__assign$2(__assign$2({},t.lyricDescriptor),{duration:this._machine.state.context.duration}),n=this.build(t,this._previousDescriptor),l.label=1;case 1:return l.trys.push([1,,3,4]),[4,this.send(n)];case 2:return l.sent(),[3,4];case 3:return this._previousDescriptor=t,[7];case 4:return[2]}}))}))},LyricsPlayActivity.prototype.stateMatches=function(t){return this._machine.state.matches(t)},LyricsPlayActivity.prototype.build=function(t,n){return buildPlayActivityData$1(this.generateBaseActivityData(),t,n).data}}(Ye);!function(t){t[t.ALEXA=13]="ALEXA"}(ze||(ze={}));!function(){function PlayActivity(t,n,l){this.accessToken=t,this.storefrontId=n,this.baseVersion=1,this.clientId="JSCLIENT",this.eventType="play",this.sourceType=ze.ALEXA,this.topic="xp_amp_podcasts_play",this.utcOffset=(new Date).getTimezoneOffset(),this._isQA=!1,this._logInfo=!1,this._appInfo=l.app,this._fetch=l.fetch,this._fetchOptions=l.fetchOptions,l.fetch&&l.fetch.Headers&&(this._headersClass=l.fetch.Headers),this._isQA=l.isQA||!1,this._logInfo=l.logInfo||this._isQA||!1,this._osInfo=l.os,this._userAgent=l.userAgent,void 0!==l.baseVersion&&(this.baseVersion=l.baseVersion),void 0!==l.clientId&&(this.clientId=l.clientId),this.guid=l.guid,this.ipAddress=l.ip,this.sourceType=l.sourceType||ze.ALEXA,this.utcOffset=l.utcOffset}Object.defineProperty(PlayActivity.prototype,"appName",{get:function(){return this._appInfo&&void 0!==this._appInfo.name?this._appInfo.name:"MusicKitApp"},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"appVersion",{get:function(){return this._appInfo&&void 0!==this._appInfo.version?this._appInfo.version:"1.0"},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"fetch",{get:function(){return this._fetch},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"Headers",{get:function(){return this._headersClass},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"logInfo",{get:function(){return this._logInfo},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"os",{get:function(){return this._osInfo&&void 0!==this._osInfo.name?this._osInfo.name:"Unidentified OS"},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"osVersion",{get:function(){return this._osInfo&&void 0!==this._osInfo.version?this._osInfo.version:"0.0"},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"url",{get:function(){return(this._isQA?"https://amp-mt-ingestion-service.itunes.apple.com/report/2":"https://xp.apple.com/report/2")+"/"+this.topic},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"userAgent",{get:function(){return this._userAgent},enumerable:!0,configurable:!0}),PlayActivity.prototype.buildForPlayParams=function(t,n,l,d,p){if(void 0===d&&(d=0),void 0===p&&(p={}),"play"!==n)throw new Error("buildForPlayParams() only valid on play event");var h={app:this.appName,appVersion:this.appVersion,baseVersion:this.baseVersion,clientId:this.clientId,ip:this.ipAddress,os:this.os,osVersion:this.osVersion,storeFront:this.storefrontId,timezoneOffset:this.utcOffset,topic:this.topic,userAgent:this.userAgent},f=t.actionType,y=t.durationInMilliseconds,v=t.eventTime,g=void 0===v?Date.now():v,_=t.eventVersion,m=void 0===_?"1":_,b=t.feedUrl,P=t.guid,k=t.id,T=t.itemType,S=t.mediaKind,A=t.playbackSpeed,w=t.playEndPosition,I=t.playId,E=t.playStartPosition,R=t.playStartTime,O=t.postTime,C="audio"===S||"video"===S?S:"unknown",M={actionType:f,contentGUID:P,contentId:k,contentLength:y/1e3,eventTime:g||Date.now(),eventType:n,eventVersion:m,itemType:T,language:l.language,mediaType:C,playbackSpeed:A,playDuration:d,playEndPosition:w,playId:I,playStartPosition:E,playStartTime:R,podcastFeedURL:b,podcastId:l.id,podcastState:l.state,postTime:O||g||Date.now()};return __assign$2(__assign$2(__assign$2({},h),M),p)},PlayActivity.prototype.send=function(t){return __awaiter$2(this,void 0,void 0,(function(){var n,l,d,p;return __generator$2(this,(function(h){switch(h.label){case 0:if(n=new this.Headers({Authorization:"Bearer "+this.accessToken,"Content-Type":"application/json"}),l=t.postTime,delete t.postTime,0===(d={postTime:l,events:ensureArray(t)}).events.length)throw new Error("send() called without any data");return p=__assign$2({method:"POST",body:JSON.stringify(d),headers:n},void 0!==this._fetchOptions&&this._fetchOptions),[4,this.fetch(this.url,p)];case 1:return[4,h.sent().text()];case 2:return h.sent(),this._logInfo&&console.info("play activity:",this.sourceType===ze.ALEXA?JSON.stringify(d):d),[2,d]}}))}))}}();var Ze=function(){function GenericStorage(t){void 0===t&&(t={}),this._data=t}return GenericStorage.prototype.clear=function(){this._data={}},GenericStorage.prototype.getItem=function(t){return this._data[t]},GenericStorage.prototype.removeItem=function(t){delete this._data[t]},GenericStorage.prototype.setItem=function(t,n){this._data[t]=n},GenericStorage}();function getCookie(t,n){void 0===t&&(t=""),void 0===n&&(n=document.cookie);var l=n.match(new RegExp("(?:^|;\\s*)"+t+"=([^;]*)"));if(l)return l[1]}function setCookie(t,n,l,d,p,h){void 0===l&&(l=""),void 0===d&&(d=14);var f=new Date;p=null!=p?p:window;var y=(h=null!=h?h:/\./.test(p.location.hostname)?p.location.hostname:"").length>0?"domain="+h+"; ":"";f.setTime(f.getTime()+24*d*60*60*1e3),p.document.cookie=t+"="+n+"; expires="+f.toUTCString()+"; "+y+"path="+l}var et,createCookieJar=function(t){switch(void 0===t&&(t="browser"),t){case"browser":return{get:getCookie,set:setCookie};case"memory":return void 0===n&&(n={}),{get:function(t){if(void 0!==t)return n[t]},set:function(t,l){n[t]=l}};default:return t}var n},empty=function(t,n){return write(t,n,[],"/",0)},read=function(t,n){var l=t.get(n);return void 0===l||""===l?[]:ensureArray(JSON.parse(atob(l)))},write=function(t,n,l,d,p,h){return t.set(n,btoa(JSON.stringify(l)),d,p,h)},update=function(t,n,l,d,p,h){return write(t,n,function(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(__read$2(arguments[n]));return t}
/*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */(read(t,n),[l]),d,p,h)},tt=Le.AUTO,rt=function(){function PlayActivityBatchableSender(t,n){this.sender=t,this.jar=n,this.mode=tt}return PlayActivityBatchableSender.prototype.flush=function(){return __awaiter$2(this,void 0,void 0,(function(){var t,n,l;return __generator$2(this,(function(d){switch(d.label){case 0:if(void 0===(t=read(this.jar,"amupaee"))||0===t.length)return[2];d.label=1;case 1:return d.trys.push([1,3,,4]),[4,this.sender.send(t)];case 2:return d.sent(),empty(this.jar,"amupaee"),[3,4];case 3:throw n=d.sent(),l=n.message,new Error("flush: "+l);case 4:return[2]}}))}))},PlayActivityBatchableSender.prototype.send=function(n){return __awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(l){return this.mode!==tt||!Array.isArray(n)&&n["end-reason-type"]===t.PlayActivityEndReasonType.EXITED_APPLICATION?(update(this.jar,"amupaee",n,"/"),[2]):[2,this.sender.send(n)]}))}))},PlayActivityBatchableSender}(),it=function(){function Timeline(){this._events={},this._keys=[]}return Object.defineProperty(Timeline.prototype,"events",{get:function(){return this._events},enumerable:!0,configurable:!0}),Object.defineProperty(Timeline.prototype,"first",{get:function(){return this.at(0)},enumerable:!0,configurable:!0}),Object.defineProperty(Timeline.prototype,"keys",{get:function(){return this._keys},enumerable:!0,configurable:!0}),Object.defineProperty(Timeline.prototype,"last",{get:function(){return this.at(this.length-1)},enumerable:!0,configurable:!0}),Object.defineProperty(Timeline.prototype,"length",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Object.defineProperty(Timeline.prototype,"second",{get:function(){return this.at(1)},enumerable:!0,configurable:!0}),Timeline.prototype.at=function(t){if(t>this.length-1)throw new Error("Invalid timeline index");var n=this._keys[t];return this._events[n]},Timeline.prototype.before=function(t){if("number"!=typeof t){var n=[];for(var l in this._events)this._events.hasOwnProperty(l)&&n.push(this._events[l]);t=this._keys[n.indexOf(t)]}var d=this._keys.indexOf(t);if(-1===d)throw new Error("Key not found");if(d>0)return this._events[this._keys[d-1]]},Timeline.prototype.drain=function(){var t=this,n=this._keys.map((function(n){return t._events[n]}));return this.reset(),n},Timeline.prototype.reset=function(){this._events={},this._keys=[]},Timeline.prototype.pop=function(){return __awaiter$2(this,void 0,void 0,(function(){var t,n;return __generator$2(this,(function(l){return void 0===(t=this._keys.pop())?[2,Promise.reject("TIMELINE IS EMPTY")]:(n=this._events[t],delete this._events[t],[2,Promise.resolve(n)])}))}))},Timeline.prototype.add=function(t,n){return __awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(l){return[2,this.push(t,n)]}))}))},Timeline.prototype.push=function(t,n){return void 0===n&&(n=Date.now()),__awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(l){for(;-1!==this._keys.indexOf(n);)n++;return this._events[n]=t,this._keys.push(n),[2,Promise.resolve(n)]}))}))},Timeline.prototype.shift=function(){return __awaiter$2(this,void 0,void 0,(function(){var t,n;return __generator$2(this,(function(l){return void 0===(t=this._keys.shift())?[2,Promise.reject("TIMELINE IS EMPTY")]:(n=this._events[t],delete this._events[t],[2,Promise.resolve(n)])}))}))},Timeline.prototype.unshift=function(t,n){return void 0===n&&(n=Date.now()),__awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(l){for(;-1!==this._keys.indexOf(n);)n++;return this._events[n]=t,this._keys.unshift(n),[2,Promise.resolve(n)]}))}))},Timeline}(),nt=function(){function Nonsole(){}return Nonsole.prototype.log=function(){},Nonsole}(),ot="undefined"==typeof localStorage?void 0:localStorage,readLevel=function(t,n){var l,d;return parseInt(null!==(d=null===(l=null==ot?void 0:ot.getItem)||void 0===l?void 0:l.call(ot,t))&&void 0!==d?d:""+n,10)},at=readLevel("mk-debug",5),st=function(){function Logger(t){this._level=at,this._configKey="mk-debug","string"==typeof t?(this._configKey=t,this._level=readLevel(this._configKey,at)):this._level=null!=t?t:at,this._console=this._availableConsole()}return Object.defineProperty(Logger.prototype,"enabled",{get:function(){return this.level<5},set:function(t){this.level=t?1:5},enumerable:!0,configurable:!0}),Object.defineProperty(Logger.prototype,"level",{get:function(){return this._level},set:function(t){this._level=t,this._console=this._availableConsole()},enumerable:!0,configurable:!0}),Logger.prototype.debug=function(t){for(var n=[],l=1;l<arguments.length;l++)n[l-1]=arguments[l];this._perform.apply(this,__spread$1(["debug"],arguments))},Logger.prototype.error=function(t){for(var n=[],l=1;l<arguments.length;l++)n[l-1]=arguments[l];this._perform.apply(this,__spread$1(["error"],arguments))},Logger.prototype.log=function(t){for(var n=[],l=1;l<arguments.length;l++)n[l-1]=arguments[l];this._perform.apply(this,__spread$1(["log"],arguments))},Logger.prototype.trace=function(t){for(var n=[],l=1;l<arguments.length;l++)n[l-1]=arguments[l];this._perform.apply(this,__spread$1(["trace"],arguments))},Logger.prototype.warn=function(t){for(var n=[],l=1;l<arguments.length;l++)n[l-1]=arguments[l];this._perform.apply(this,__spread$1(["warn"],arguments))},Logger.prototype._availableConsole=function(){return console&&this.level<5?console:new nt},Logger.prototype._perform=function(t){for(var n,l=[],d=1;d<arguments.length;d++)l[d-1]=arguments[d];if("silent"!==t){var p=["trace","debug","info","warn","error"].splice(this.level),h="log"===t?"debug":t;-1!==p.indexOf(h)&&("function"!=typeof this._console[t]&&(t="log"),(n=this._console)[t].apply(n,__spread$1(l)))}},Logger}(),ut=new st,fieldGetter=function(t,n){return function(l){return n in l?l[n]:l[t]}},ct=fieldGetter("eventType","event-type"),lt=fieldGetter("endReasonType","end-reason-type"),createMPAFMachine=function(){return c({id:"mpaf",initial:"idle",context:{},states:{error:{},idle:{on:{play:"playing",scrubBegin:{target:"scrubbing",actions:r((function(t){return __assign$2(__assign$2({},t),{stateBeforeScrub:"idle"})}))},scrubEnd:{target:"error",actions:["clearStateBeforeScrub","setScrubEndError"]}}},playing:{on:{scrubBegin:{target:"scrubbing",actions:r((function(t){return __assign$2(__assign$2({},t),{stateBeforeScrub:"playing"})}))},stop:"idle",scrubEnd:{target:"error",actions:["clearStateBeforeScrub","setScrubEndError"]}}},scrubbing:{on:{scrubEnd:[{target:"idle",cond:function(t){return"idle"===t.stateBeforeScrub},actions:["clearStateBeforeScrub"]},{target:"playing",actions:["clearStateBeforeScrub"]}]}}}},{actions:{clearStateBeforeScrub:r((function(t){t.stateBeforeScrub;return function(t,n){var l={};for(var d in t)Object.prototype.hasOwnProperty.call(t,d)&&n.indexOf(d)<0&&(l[d]=t[d]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var p=0;for(d=Object.getOwnPropertySymbols(t);p<d.length;p++)n.indexOf(d[p])<0&&Object.prototype.propertyIsEnumerable.call(t,d[p])&&(l[d[p]]=t[d[p]])}return l}(t,["stateBeforeScrub"])})),setScrubEndError:r((function(t){return __assign$2(__assign$2({},t),{errorMessage:"The scrub() method was called with the SCRUB_END action without a previous SCRUB_START descriptor"})}))}})},dt=function(){function MPAFStateMachine(){this.machine=createMPAFMachine(),this.machineService=f$3(this.machine).start()}return MPAFStateMachine.prototype.canSendEvent=function(t){var n;return null!==(n=this.machine.transition(this.machineService.state,t).changed)&&void 0!==n&&n},MPAFStateMachine.prototype.matches=function(t){return this.machineService.state.matches(t)},MPAFStateMachine.prototype.send=function(n){var l=function(n){var l=ct(n),d=lt(n);switch(l){case Ce.PLAY_START:return"play";case Ce.PLAY_END:switch(d){case t.PlayActivityEndReasonType.SCRUB_BEGIN:return"scrubBegin";case t.PlayActivityEndReasonType.SCRUB_END:return"scrubEnd";case t.PlayActivityEndReasonType.EXITED_APPLICATION:return!1;default:return"stop"}default:return"stop"}}(n);if(!1!==l&&(this.canSendEvent({type:l})&&this.machineService.send({type:l}),this.matches("error")))throw new Error(this.machineService.state.context.errorMessage)},MPAFStateMachine}(),pt=function(t){function StatelessPlayActivity(n,l,d,p){return t.call(this,n,l,d,p)||this}return __extends$2(StatelessPlayActivity,t),StatelessPlayActivity.prototype.build=function(t,n){return buildPlayActivityData(this.generateBaseActivityData(),t,n,"JSCLIENT"!==this.clientId).data},StatelessPlayActivity}(Ye),ht=function(){function PlayActivity(t,n,l,d){this.timeline=new it,this._paf=new pt(t,n,l,d),this._cookieJar=createCookieJar(null==d?void 0:d.cookieJar),this.sender=new rt(this._paf.sender,this._cookieJar),this._machine=new dt}return Object.defineProperty(PlayActivity.prototype,"mode",{get:function(){return this.sender.mode},set:function(t){this.sender.mode=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlayActivity.prototype,"privateEnabled",{get:function(){return this._paf.privateEnabled},set:function(t){this._paf.privateEnabled=t},enumerable:!0,configurable:!0}),PlayActivity.prototype.activate=function(n){return void 0===n&&(n=!1),__awaiter$2(this,void 0,void 0,(function(){var l,d;return __generator$2(this,(function(p){switch(p.label){case 0:if(!n)return[3,4];p.label=1;case 1:return p.trys.push([1,3,,4]),[4,this.flush()];case 2:return p.sent(),[3,4];case 3:if(l=p.sent(),!function(t){switch(typeof t){case"string":return t;case"object":return t.message?"string"!=typeof t.message?"":t.message:"";default:return""}}(l).includes("send() called without any data"))throw l;return[3,4];case 4:return(d=this.timeline.last)&&d.endReasonType===t.PlayActivityEndReasonType.EXITED_APPLICATION?[2,this.timeline.pop()]:[2]}}))}))},PlayActivity.prototype.exit=function(n){return void 0===n&&(n=0),__awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(l){return[2,this.stop(n,t.PlayActivityEndReasonType.EXITED_APPLICATION)]}))}))},PlayActivity.prototype.pause=function(n){return void 0===n&&(n=0),__awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(l){return[2,this.stop(n,t.PlayActivityEndReasonType.PLAYBACK_MANUALLY_PAUSED)]}))}))},PlayActivity.prototype.play=function(n,l){return void 0===l&&(l=0),__awaiter$2(this,void 0,void 0,(function(){var d,p,h,f;return __generator$2(this,(function(y){switch(y.label){case 0:return d=this.timeline.length>0,void 0===n?d?((p=this._previousDescriptor()).eventType===Ce.PLAY_END&&delete p.endReasonType,h=__assign$2(__assign$2({},p),{eventType:Ce.PLAY_START,timestamp:Date.now()}),[2,this._addToTimeline(h)]):[2]:d?(p=this._previousDescriptor(),this._machine.matches("playing")?(h=__assign$2(__assign$2({},p),{eventType:Ce.PLAY_END,endReasonType:t.PlayActivityEndReasonType.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM,timestamp:Date.now(),position:l}),[4,this._addToTimeline(h)]):[3,2]):[3,2];case 1:y.sent(),l=0,y.label=2;case 2:return f=__assign$2(__assign$2({},n),{eventType:Ce.PLAY_START,timestamp:Date.now(),position:l}),[2,this._addToTimeline(f)]}}))}))},PlayActivity.prototype.scrub=function(n,l){return void 0===n&&(n=0),void 0===l&&(l=t.PlayActivityEndReasonType.SCRUB_BEGIN),__awaiter$2(this,void 0,void 0,(function(){var t,d;return __generator$2(this,(function(p){return t=this._previousDescriptor(),d=__assign$2(__assign$2({},t),{eventType:Ce.PLAY_END,endReasonType:l,timestamp:Date.now(),position:n}),[2,this._addToTimeline(d)]}))}))},PlayActivity.prototype.skip=function(n,l,d){return void 0===l&&(l=t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS),void 0===d&&(d=0),__awaiter$2(this,void 0,void 0,(function(){return __generator$2(this,(function(t){switch(t.label){case 0:return[4,this.stop(d,l)];case 1:return t.sent(),[2,this.play(n)]}}))}))},PlayActivity.prototype.stop=function(n,l){return void 0===n&&(n=0),void 0===l&&(l=t.PlayActivityEndReasonType.NATURAL_END_OF_TRACK),__awaiter$2(this,void 0,void 0,(function(){var d,p;return __generator$2(this,(function(h){switch(h.label){case 0:return(d=this._previousDescriptor()).endReasonType!==t.PlayActivityEndReasonType.EXITED_APPLICATION?[3,2]:[4,this.timeline.pop()];case 1:h.sent(),empty(this._cookieJar,"amupaee"),d=this._previousDescriptor(),h.label=2;case 2:return this._machine.matches("playing")?(p=__assign$2(__assign$2({},d),{eventType:Ce.PLAY_END,timestamp:Date.now(),endReasonType:l,position:n}),[2,this._addToTimeline(p)]):[2,Promise.reject(new Error("A play stop() method was called without a previous play() descriptor"))]}}))}))},PlayActivity.prototype.build=function(t,n){if(void 0===t&&void 0===n&&ut.warn("You are calling build() from a stateful PAF client. Please, use a stateless client or exit(), pause(), play(), scrub(), skip() or stop() instead."),void 0===t){if(0===this.timeline.length)throw new Error("build() called without a play activity descriptor");t=this.timeline.last}if(void 0===n){if(void 0===(n=this.timeline.before(t))&&t.eventType===Ce.PLAY_END)throw new Error("Cannot build() for PLAY_END descriptors without previous descriptors");n=null!=n&&n}return this._paf.build(t,n)},PlayActivity.prototype.addForPlayParams=function(t,n,l,d,p){void 0===d&&(d=0),void 0===p&&(p={});var h=this.buildDescriptorForPlayParams(t,n,l,d,p);return this._addToTimeline(h)},PlayActivity.prototype.buildDescriptorForPlayParams=function(t,n,l,d,p){void 0===d&&(d=0),void 0===p&&(p={});var h="stream"===t.format?Me.STREAM:Me.ITUNES_STORE_CONTENT;return __assign$2(__assign$2(__assign$2({},t),{container:l,duration:d,eventType:n,itemType:h}),p)},PlayActivity.prototype.flush=function(){return this.sender.flush()},PlayActivity.prototype._addToTimeline=function(t){return __awaiter$2(this,void 0,void 0,(function(){var n,l;return __generator$2(this,(function(d){switch(d.label){case 0:return n=this.timeline.length>0&&this.timeline.last,[4,this.timeline.add(t)];case 1:return d.sent(),l=this.build(t,n),[4,this.send(l)];case 2:return d.sent(),[2]}}))}))},PlayActivity.prototype._previousDescriptor=function(){var t=this.timeline.last;if(void 0===t)throw new Error("A method was called without a previous descriptor");return __assign$2({},t)},PlayActivity.prototype.buildForPlayParams=function(t,n,l,d,p,h){return void 0===d&&(d=0),void 0===p&&(p={}),void 0===h&&(h=!1),ut.warn("You are using buildsForPlayParams from a stateful PlayActivity. Please, use StatelessPlayActivity instead"),this._paf.buildForPlayParams(t,n,l,d,p,h)},PlayActivity.prototype.send=function(t){var n=this,l=ensureArray(t);return l.forEach((function(t){return n._machine.send(t)})),this.sender.send(l)},PlayActivity}(),ft=/max-age=(\d+)/i;!function(t){t.FAIRPLAY="com.apple.fps",t.PLAYREADY="com.microsoft.playready",t.WIDEVINE="com.widevine.alpha"}(et||(et={}));var yt=["musicVideo","song","radioStation"];yt.push("podcast-episodes","uploaded-audios","uploadedAudio","uploaded-videos","uploadedVideo");var vt=function(){function MKDialog(t,n){void 0===n&&(n=""),this._message=t,this._explanation=n,this.id="musickit-dialog",this.scrimId=this.id+"-scrim",this.styleId=this.id+"-style",this._okButtonString="OK",[this.id,this.scrimId,this.styleId].forEach((function(t){try{var n=document.getElementById(t);n.parentElement.removeChild(n)}catch(Mt){}})),this._appendStyle("\n#musickit-dialog {\n  --mk-dialog-background: rgba(255, 255, 255, 1);\n  --mk-dialog-text: rgba(0, 0, 0, 0.95);\n  --mk-dialog-border: rgba(0, 0, 0, 0.07);\n  --mk-dialog-scrim: rgba(255, 255, 255, 0.8);\n  --mk-dialog-primary: rgba(0, 122, 255, 1);\n}\n\n@media (prefers-color-scheme: dark) {\n  #musickit-dialog {\n      --mk-dialog-background: rgba(30, 30, 30, 1);\n      --mk-dialog-text: rgba(255, 255, 255, 0.85);\n      --mk-dialog-border: rgba(255, 255, 255, 0.1);\n      --mk-dialog-scrim: rgba(38, 38, 38, 0.8);\n      --mk-dialog-primary: rgba(8, 132, 255, 1);\n  }\n}\n\n#musickit-dialog-scrim {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  width: 100%;\n  height: 100%;\n  background: rgba(0, 0, 0, 0.35);\n}\n\n#musickit-dialog * {\n  -webkit-tap-highlight-color: transparent;\n  -webkit-touch-callout: none;\n  -ms-touch-action: none;\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n  font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, sans-serif;\n  font-size: 15px;\n  line-height: 20px;\n}\n\n#musickit-dialog *:focus { outline: 0; }\n\n#musickit-dialog {\n  display: -webkit-box;\n  display: -moz-box;\n  display: -ms-flexbox;\n  display: -webkit-flex;\n  display: flex;\n  -webkit-flex-direction: column;\n  -moz-flex-direction: column;\n  flex-direction: column;\n  -webkit-justify-content: space-between;\n  -moz-justify-content: space-between;\n  justify-content: space-between;\n  min-width: 277px;\n  max-width: 290px;\n  min-height: 109px;\n  background: var(--mk-dialog-background);\n  box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.18);\n  border-radius: 10px;\n  color: var(--mk-dialog-text);\n  position: fixed;\n  top: 50%;\n  left: 50%;\n  margin-left: -142px;\n  margin-top: -67px;\n  z-index: 9999999999999999999999999;\n}\n\n#musickit-dialog #mk-dialog-body {\n  display: -webkit-box;\n  display: -moz-box;\n  display: -ms-flexbox;\n  display: -webkit-flex;\n  display: flex;\n  -webkit-flex-direction: column;\n  -moz-flex-direction: column;\n  flex-direction: column;\n  flex-grow: 1;\n  -webkit-justify-content: space-evenly;\n  -moz-justify-content: space-evenly;\n  justify-content: space-evenly;\n  -webkit-align-items: stretch;\n  align-items: stretch;\n  padding: 10px 20px;\n  min-height: 74px;\n  text-align: center;\n}\n\n#musickit-dialog .mk-dialog h5 {\n  font-weight: 500;\n  line-height: 20px;\n  margin: 7px 0 0 0;\n  padding: 0;\n}\n\n#musickit-dialog .mk-dialog p {\n  margin: 0 0 7px 0;\n  padding: 0;\n  paddin-top: 3px;\n  line-height: 18px;\n  font-size: 13px;\n  font-weight: 300;\n}\n\n#musickit-dialog #mk-dialog-actions {\n  border-top: 1px solid var(--mk-dialog-border);\n  display: -webkit-box;\n  display: -moz-box;\n  display: -ms-flexbox;\n  display: -webkit-flex;\n  display: flex;\n  -webkit-flex-direction: row;\n  -moz-flex-direction: colrowumn;\n  flex-direction: row;\n  max-height: 41px;\n  min-height: 34px;\n  -webkit-justify-self: flex-end;\n  -moz-justify-self: flex-end;\n  justify-self: flex-end;\n}\n\n#musickit-dialog #mk-dialog-actions button {\n  flex-grow: 1;\n  border: 0;\n  background: none;\n  color: var(--mk-dialog-primary);\n  padding: 0;\n  margin: 0;\n  min-height: 34px;\n  height: 41px;\n  text-align: center;\n}\n\n#musickit-dialog #mk-dialog-actions *:nth-child(2) {\n  border-left: 1px solid var(--mk-dialog-border);\n  font-weight: 500;\n}\n")}return MKDialog.presentError=function(t){var n=t.dialog;void 0!==n?MKDialog.serverDialog(n).present():new MKDialog(t.message).present()},MKDialog.serverDialog=function(t){var n=new this(t.message,t.explanation);return t.okButtonAction&&t.okButtonAction.url&&(n._okButtonActionURL=t.okButtonAction.url),t.okButtonString&&(n._okButtonString=t.okButtonString),t.cancelButtonString&&(n._cancelButtonString=t.cancelButtonString),n},MKDialog.clientDialog=function(t){var n=new this(t.message,t.explanation);return t.okButtonAction&&(n._okButtonAction=t.okButtonAction),t.cancelButtonAction&&(n._cancelButtonAction=t.cancelButtonAction),t.okButtonString&&(n._okButtonString=t.okButtonString),t.cancelButtonString&&(n._cancelButtonString=t.cancelButtonString),n},Object.defineProperty(MKDialog.prototype,"actions",{get:function(){return this.cancelButton?'<div id="mk-dialog-actions">'+this.cancelButton+this.okButton+"</div>":'<div id="mk-dialog-actions">'+this.okButton+"</div>"},enumerable:!0,configurable:!0}),Object.defineProperty(MKDialog.prototype,"cancelButton",{get:function(){if("string"==typeof this._cancelButtonString)return'<button type="button">'+this._cancelButtonString+"</button>"},set:function(t){this._cancelButtonString=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKDialog.prototype,"explanation",{get:function(){return'<p id="mk-dialog-explanation">'+this._explanation+"</p>"},enumerable:!0,configurable:!0}),Object.defineProperty(MKDialog.prototype,"hasOKButtonAction",{get:function(){return!!this._okButtonActionURL||!!this._okButtonAction},enumerable:!0,configurable:!0}),Object.defineProperty(MKDialog.prototype,"message",{get:function(){return'<h5 id="mk-dialog-title">'+this._message+"</h5>"},enumerable:!0,configurable:!0}),Object.defineProperty(MKDialog.prototype,"okButton",{get:function(){return this.hasOKButtonAction&&this._okButtonActionURL?'<button type="button" data-ok-action-url=\''+this._okButtonActionURL+"'>"+this._okButtonString+"</button>":'<button type="button">'+this._okButtonString+"</button>"},enumerable:!0,configurable:!0}),MKDialog.prototype.present=function(){var t=this,n=document.createDocumentFragment(),l=document.createElement("div");l.id=this.scrimId,n.appendChild(l);var d=document.createElement("div");d.id=this.id,d.classList.add("mk-dialog"),d.setAttribute("role","alertDialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-labeledby","mk-dialog-title"),d.setAttribute("aria-describedby","mk-dialog-explanation");var p='\n      <div id="mk-dialog-body">\n        '+this.message+"\n        "+this.explanation+"\n      </div>";p="\n      "+p+"\n      "+this.actions+"\n    ",d.innerHTML=p,n.appendChild(d),document.body.appendChild(n),document.querySelector("#"+d.id+" #mk-dialog-actions *:first-child").focus(),setTimeout((function(){document.querySelector("#"+d.id+" #mk-dialog-actions *:first-child").addEventListener("click",(function(){t._cancelButtonAction&&t._cancelButtonAction(),d.parentElement.removeChild(d),l.parentElement.removeChild(l)})),t.hasOKButtonAction&&(t._okButtonActionURL?document.querySelector("#"+d.id+" #mk-dialog-actions *:last-child").addEventListener("click",(function(t){window.open(t.target.dataset.okActionUrl,"_blank"),d.parentElement.removeChild(d),l.parentElement.removeChild(l)})):t._okButtonAction&&document.querySelector("#"+d.id+" #mk-dialog-actions *:last-child").addEventListener("click",(function(n){t._okButtonAction(),d.parentElement.removeChild(d),l.parentElement.removeChild(l)})))}))},MKDialog.prototype._appendStyle=function(t){var n=document.createElement("style");n.id=this.styleId,n.styleSheet?n.styleSheet.cssText=t:n.innerHTML=t,document.body.appendChild(n)},MKDialog}(),gt=(isNodeEnvironment(),function(){function Browser(t){void 0===t&&(t=window.navigator.userAgent);var n=t.toLowerCase();this.isEdge=/\sedge\//.test(n),this.isChrome=!this.isEdge&&/chrome/.test(n),this.isSafari=!this.isEdge&&!this.isChrome&&/safari/.test(n),this.isFirefox=!this.isEdge&&!this.isChrome&&!this.isSafari&&/firefox/.test(n),this.isIE=!this.isEdge&&!this.isChrome&&!this.isSafari&&!this.isFirefox&&/trident|msie/.test(n),this.isMobile=/mobile/.test(n),this.isAndroid=this.isMobile&&/android/.test(n),this.isiOS=this.isMobile&&/iphone|ipad|ipod/.test(n),this.isWebView=/(webview|(iphone|ipod|ipad)(?!.*safari\/)|android.*(wv|\.0\.0\.0)|\bfb[\w_]+\/(?:messenger)?|\binstagram|\btwitter)/.test(n),this.isEdge?this.engineVersion=n.match(/(?:edge).(\d+)/):(this.version=n.match(/(?:chrome|version|firefox|msie|rv).(\d+)\.(\d+)/),this.engineVersion=n.match(/(?:applewebkit|gecko|trident).(\d+)/)),this.version&&(this.majorVersion=parseInt(this.version[1],10),this.minorVersion=parseInt(this.version[2],10)),this.engineVersion&&(this.engineMajorVersion=parseInt(this.engineVersion[1],10))}return Browser.supportsEs6=function(){if("undefined"==typeof Symbol)return!1;try{new Function('"use strict";class Foo {}')(),new Function('"use strict";var bar = (x) => x+1')()}catch(e){return!1}return!0},Browser}()),_t=isNodeEnvironment(),mt=gt,bt=new gt,Pt=new st,kt=document.createElement("video"),Tt=[],St=[];function deferPlayback(){fillAvailableElements("audio",St),fillAvailableElements("video",Tt),Pt.debug("dom-helpers: defer playback called.  There are "+Tt.length+" available video elements and "+St.length+" available audio elements.")}function fillAvailableElements(t,n){for(var l=10-n.length;l>0;){var d=document.createElement(t);d.load(),n.push(d),l--}}
/*! *****************************************************************************
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain a copy of the
    License at http://www.apache.org/licenses/LICENSE-2.0

    THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
    WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
    MERCHANTABLITY OR NON-INFRINGEMENT.

    See the Apache Version 2.0 License for specific language governing permissions
    and limitations under the License.
    ***************************************************************************** */var extendStatics$3=function(t,n){return(extendStatics$3=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var l in n)n.hasOwnProperty(l)&&(t[l]=n[l])})(t,n)};function __extends$3(t,n){function __(){this.constructor=t}extendStatics$3(t,n),t.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}var __assign$3=function(){return(__assign$3=Object.assign||function(t){for(var n,l=1,d=arguments.length;l<d;l++)for(var p in n=arguments[l])Object.prototype.hasOwnProperty.call(n,p)&&(t[p]=n[p]);return t}).apply(this,arguments)};function __metadata$1(t,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,n)}function __awaiter$3(t,n,l,d){return new(l||(l=Promise))((function(p,h){function fulfilled(t){try{step(d.next(t))}catch(e){h(e)}}function rejected(t){try{step(d.throw(t))}catch(e){h(e)}}function step(t){t.done?p(t.value):new l((function(n){n(t.value)})).then(fulfilled,rejected)}step((d=d.apply(t,n||[])).next())}))}function __generator$3(t,n){var l,d,p,h,f={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return h={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(h[Symbol.iterator]=function(){return this}),h;function verb(h){return function(y){return function(h){if(l)throw new TypeError("Generator is already executing.");for(;f;)try{if(l=1,d&&(p=2&h[0]?d.return:h[0]?d.throw||((p=d.return)&&p.call(d),0):d.next)&&!(p=p.call(d,h[1])).done)return p;switch(d=0,p&&(h=[2&h[0],p.value]),h[0]){case 0:case 1:p=h;break;case 4:return f.label++,{value:h[1],done:!1};case 5:f.label++,d=h[1],h=[0];continue;case 7:h=f.ops.pop(),f.trys.pop();continue;default:if(!(p=f.trys,(p=p.length>0&&p[p.length-1])||6!==h[0]&&2!==h[0])){f=0;continue}if(3===h[0]&&(!p||h[1]>p[0]&&h[1]<p[3])){f.label=h[1];break}if(6===h[0]&&f.label<p[1]){f.label=p[1],p=h;break}if(p&&f.label<p[2]){f.label=p[2],f.ops.push(h);break}p[2]&&f.ops.pop(),f.trys.pop();continue}h=n.call(t,f)}catch(e){h=[6,e],d=0}finally{l=p=0}if(5&h[0])throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}([h,y])}}}function __read$3(t,n){var l="function"==typeof Symbol&&t[Symbol.iterator];if(!l)return t;var d,p,h=l.call(t),f=[];try{for(;(void 0===n||n-- >0)&&!(d=h.next()).done;)f.push(d.value)}catch(ba){p={error:ba}}finally{try{d&&!d.done&&(l=h.return)&&l.call(h)}finally{if(p)throw p.error}}return f}var At={AFG:"143610",AGO:"143564",AIA:"143538",ALB:"143575",AND:"143611",ARE:"143481",ARG:"143505",ARM:"143524",ATG:"143540",AUS:"143460",AUT:"143445",AZE:"143568",BEL:"143446",BEN:"143576",BFA:"143578",BGD:"143490",BGR:"143526",BHR:"143559",BHS:"143539",BIH:"143612",BLR:"143565",BLZ:"143555",BMU:"143542",BOL:"143556",BRA:"143503",BRB:"143541",BRN:"143560",BTN:"143577",BWA:"143525",CAF:"143623",CAN:"143455",CHE:"143459",CHL:"143483",CHN:"143465",CIV:"143527",CMR:"143574",COD:"143613",COG:"143582",COL:"143501",CPV:"143580",CRI:"143495",CYM:"143544",CYP:"143557",CZE:"143489",DEU:"143443",DMA:"143545",DNK:"143458",DOM:"143508",DZA:"143563",ECU:"143509",EGY:"143516",ESP:"143454",EST:"143518",ETH:"143569",FIN:"143447",FJI:"143583",FRA:"143442",FSM:"143591",GAB:"143614",GBR:"143444",GEO:"143615",GHA:"143573",GIN:"143616",GMB:"143584",GNB:"143585",GRC:"143448",GRD:"143546",GTM:"143504",GUY:"143553",HKG:"143463",HND:"143510",HRV:"143494",HUN:"143482",IDN:"143476",IND:"143467",IRL:"143449",IRQ:"143617",ISL:"143558",ISR:"143491",ITA:"143450",JAM:"143511",JOR:"143528",JPN:"143462",KAZ:"143517",KEN:"143529",KGZ:"143586",KHM:"143579",KNA:"143548",KOR:"143466",KWT:"143493",LAO:"143587",LBN:"143497",LBR:"143588",LBY:"143567",LCA:"143549",LIE:"143522",LKA:"143486",LTU:"143520",LUX:"143451",LVA:"143519",MAC:"143515",MAR:"143620",MCO:"143618",MDA:"143523",MDG:"143531",MDV:"143488",MEX:"143468",MKD:"143530",MLI:"143532",MLT:"143521",MMR:"143570",MNE:"143619",MNG:"143592",MOZ:"143593",MRT:"143590",MSR:"143547",MUS:"143533",MWI:"143589",MYS:"143473",NAM:"143594",NER:"143534",NGA:"143561",NIC:"143512",NLD:"143452",NOR:"143457",NPL:"143484",NRU:"143606",NZL:"143461",OMN:"143562",PAK:"143477",PAN:"143485",PER:"143507",PHL:"143474",PLW:"143595",PNG:"143597",POL:"143478",PRT:"143453",PRY:"143513",PSE:"143596",QAT:"143498",ROU:"143487",RUS:"143469",RWA:"143621",SAU:"143479",SEN:"143535",SGP:"143464",SLB:"143601",SLE:"143600",SLV:"143506",SRB:"143500",STP:"143598",SUR:"143554",SVK:"143496",SVN:"143499",SWE:"143456",SWZ:"143602",SYC:"143599",TCA:"143552",TCD:"143581",THA:"143475",TJK:"143603",TKM:"143604",TON:"143608",TTO:"143551",TUN:"143536",TUR:"143480",TWN:"143470",TZA:"143572",UGA:"143537",UKR:"143492",URY:"143514",USA:"143441",UZB:"143566",VCT:"143550",VEN:"143502",VGB:"143543",VNM:"143471",VUT:"143609",WSM:"143607",XKX:"143624",YEM:"143571",ZAF:"143472",ZMB:"143622",ZWE:"143605"},wt=function(){function DeveloperToken(t){if(this.token=t,!t||!/^[a-z0-9\-\_]{16,}\.[a-z0-9\-\_]{16,}\.[a-z0-9\-\_]{16,}/i.test(t))throw new Error("Invalid token.");var n=__read$1(t.split("."),2),l=n[0],d=n[1],p=this._decode(d),h=p.exp,f=p.iss;if(this.expiration=1e3*h,this.isExpired)throw new Error("Initialized with an expired token.");this.teamId=f;var y=this._decode(l).kid;this.keyId=y}return Object.defineProperty(DeveloperToken.prototype,"isExpired",{get:function(){return this.expiration<Date.now()},enumerable:!0,configurable:!0}),DeveloperToken.prototype._decode=function(t){return JSON.parse(se(t))},DeveloperToken}(),It={AW:"ABW",AF:"AFG",AO:"AGO",AI:"AIA",AX:"ALA",AL:"ALB",AD:"AND",AE:"ARE",AR:"ARG",AM:"ARM",AS:"ASM",AQ:"ATA",TF:"ATF",AG:"ATG",AU:"AUS",AT:"AUT",AZ:"AZE",BI:"BDI",BE:"BEL",BJ:"BEN",BQ:"BES",BF:"BFA",BD:"BGD",BG:"BGR",BH:"BHR",BS:"BHS",BA:"BIH",BL:"BLM",BY:"BLR",BZ:"BLZ",BM:"BMU",BO:"BOL",BR:"BRA",BB:"BRB",BN:"BRN",BT:"BTN",BV:"BVT",BW:"BWA",CF:"CAF",CA:"CAN",CC:"CCK",CH:"CHE",CL:"CHL",CN:"CHN",CI:"CIV",CM:"CMR",CD:"COD",CG:"COG",CK:"COK",CO:"COL",KM:"COM",CV:"CPV",CR:"CRI",CU:"CUB",CW:"CUW",CX:"CXR",KY:"CYM",CY:"CYP",CZ:"CZE",DE:"DEU",DJ:"DJI",DM:"DMA",DK:"DNK",DO:"DOM",DZ:"DZA",EC:"ECU",EG:"EGY",ER:"ERI",EH:"ESH",ES:"ESP",EE:"EST",ET:"ETH",FI:"FIN",FJ:"FJI",FK:"FLK",FR:"FRA",FO:"FRO",FM:"FSM",GA:"GAB",GB:"GBR",GE:"GEO",GG:"GGY",GH:"GHA",GI:"GIB",GN:"GIN",GP:"GLP",GM:"GMB",GW:"GNB",GQ:"GNQ",GR:"GRC",GD:"GRD",GL:"GRL",GT:"GTM",GF:"GUF",GU:"GUM",GY:"GUY",HK:"HKG",HM:"HMD",HN:"HND",HR:"HRV",HT:"HTI",HU:"HUN",ID:"IDN",IM:"IMN",IN:"IND",IO:"IOT",IE:"IRL",IR:"IRN",IQ:"IRQ",IS:"ISL",IL:"ISR",IT:"ITA",JM:"JAM",JE:"JEY",JO:"JOR",JP:"JPN",KZ:"KAZ",KE:"KEN",KG:"KGZ",KH:"KHM",KI:"KIR",KN:"KNA",KR:"KOR",KW:"KWT",LA:"LAO",LB:"LBN",LR:"LBR",LY:"LBY",LC:"LCA",LI:"LIE",LK:"LKA",LS:"LSO",LT:"LTU",LU:"LUX",LV:"LVA",MO:"MAC",MF:"MAF",MA:"MAR",MC:"MCO",MD:"MDA",MG:"MDG",MV:"MDV",MX:"MEX",MH:"MHL",MK:"MKD",ML:"MLI",MT:"MLT",MM:"MMR",ME:"MNE",MN:"MNG",MP:"MNP",MZ:"MOZ",MR:"MRT",MS:"MSR",MQ:"MTQ",MU:"MUS",MW:"MWI",MY:"MYS",YT:"MYT",NA:"NAM",NC:"NCL",NE:"NER",NF:"NFK",NG:"NGA",NI:"NIC",NU:"NIU",NL:"NLD",NO:"NOR",NP:"NPL",NR:"NRU",NZ:"NZL",OM:"OMN",PK:"PAK",PA:"PAN",PN:"PCN",PE:"PER",PH:"PHL",PW:"PLW",PG:"PNG",PL:"POL",PR:"PRI",KP:"PRK",PT:"PRT",PY:"PRY",PS:"PSE",PF:"PYF",QA:"QAT",RE:"REU",RO:"ROU",RU:"RUS",RW:"RWA",SA:"SAU",SD:"SDN",SN:"SEN",SG:"SGP",GS:"SGS",SH:"SHN",SJ:"SJM",SB:"SLB",SL:"SLE",SV:"SLV",SM:"SMR",SO:"SOM",PM:"SPM",RS:"SRB",SS:"SSD",ST:"STP",SR:"SUR",SK:"SVK",SI:"SVN",SE:"SWE",SZ:"SWZ",SX:"SXM",SC:"SYC",SY:"SYR",TC:"TCA",TD:"TCD",TG:"TGO",TH:"THA",TJ:"TJK",TK:"TKL",TM:"TKM",TL:"TLS",TO:"TON",TT:"TTO",TN:"TUN",TR:"TUR",TV:"TUV",TW:"TWN",TZ:"TZA",UG:"UGA",UA:"UKR",UM:"UMI",UY:"URY",US:"USA",UZ:"UZB",VA:"VAT",VC:"VCT",VE:"VEN",VG:"VGB",VI:"VIR",VN:"VNM",VU:"VUT",WF:"WLF",WS:"WSM",XK:"XKX",YE:"YEM",ZA:"ZAF",ZM:"ZMB",ZW:"ZWE"};var Et={af:48,sq:1,ar:34,eu:1,bg:49,be:1,ca:42,zh:19,"zh-tw":18,"zh-cn":19,"zh-hk":45,"zh-sg":19,hr:41,cs:22,da:11,nl:10,"nl-be":65,en:1,"en-us":1,"en-eg":26,"en-au":27,"en-gb":2,"en-ca":6,"en-nz":27,"en-ie":26,"en-za":26,"en-jm":26,"en-bz":26,"en-tt":26,"en-001":26,et:30,fo:1,fa:59,fi:12,fr:3,"fr-ca":5,gd:2,de:4,"de-ch":57,el:23,he:36,hi:50,hu:21,is:31,id:37,it:7,ja:9,ko:13,lv:33,lt:32,mk:1,mt:1,no:14,nb:14,nn:14,pl:20,"pt-br":15,pt:24,rm:1,ro:39,ru:16,sr:1,sk:40,sl:52,es:8,"es-mx":28,"es-419":44,sv:17,th:35,ts:1,tn:1,tr:25,uk:29,ur:55,ve:1,vi:43,xh:1,yi:1,zu:56,ms:38,iw:36,lo:46,tl:47,kk:51,ta:53,te:54,bn:58,ga:60,ht:61,la:62,pa:63,sa:64};function getLanguages(){if("undefined"==typeof navigator)return[];if(navigator.languages)return navigator.languages;var t=navigator.language||navigator.userLanguage;return t?[t]:[]}var Rt=new RegExp("^https://([a-z0-9]+-)?"+"js-cdn.music.apple.com/musickit/v2/".replace(/[\.\/]/g,"\\$&"),"i"),Ot=/^([a-z]+:)?\/\//;function findScript(t){return isNodeEnvironment()||!t?null:document.querySelector('script[src*="'+t+'"]')}function determineCdnBasePrefix(){var t,n;try{for(var l=function(t){var n="function"==typeof Symbol&&t[Symbol.iterator],l=0;return n?n.call(t):{next:function(){return t&&l>=t.length&&(t=void 0),{value:t&&t[l++],done:!t}}}}("undefined"!=typeof document&&document.querySelectorAll?Array.from(document.querySelectorAll("script[src]")):[]),d=l.next();!d.done;d=l.next()){var p=d.value,h=Rt.exec(p.src);if(h)return h[1]||""}}catch(f){t={error:f}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}return""}function determineCdnBaseHost(){return isNodeEnvironment()?"":"//"+determineCdnBasePrefix()+"js-cdn.music.apple.com"}function getHlsJsCdnConfig(){var t={hls:"",rtc:""};if(isNodeEnvironment())return t;var n=determineCdnBaseHost(),l="1.530.15";return"undefined"!=typeof localStorage&&(l=localStorage.getItem("mk-hlsjs-version")||l),t.hls="https:"+n+"/hls.js/"+l+"/hls.js/hls.js",t.rtc="https:"+n+"/hls.js/"+l+"/rtc.js/rtc.min.js",t}function loadScript(t,n){return new Promise((function(l,d){if(isNodeEnvironment()&&d("Dynamic script loading is unsupported in Node environments."),findScript(t))return l();var p,h=document.createElement("script");(n&&Object.keys(n).forEach((function(t){h.setAttribute(t,n[t])})),h.onload=function(){l()},h.onerror=function(t){d(t)},Ot.test(t))?p=t:p=""+function(t,n){if(void 0===n&&(n=window),isNodeEnvironment())return"";if(n.localStorage.mkCDNBaseURLOverride)return n.localStorage.mkCDNBaseURLOverride;var l=findScript(t);return l?l.getAttribute("src").replace(new RegExp(t+"$"),""):determineCdnBaseHost()+"/musickit/v2/"}(t)+t;h.src=p,document.head.appendChild(h)}))}var Ct,Mt,Dt,Lt=new st("sk-debug"),Nt=function(){function AuthBridgeBase(){this._targetOrigin="*"}return AuthBridgeBase.prototype.init=function(t,n){var l;this._receiveWindow=t,this._sendWindow=n,this.handleMessage=this.handleMessage.bind(this),null===(l=this._receiveWindow)||void 0===l||l.addEventListener("message",this.handleMessage)},AuthBridgeBase.prototype.sendMessage=function(t,n){var l={action:"mediakit:"+t,data:n};this._sendWindow&&this._sendWindow.postMessage(JSON.stringify(l),this._targetOrigin)},AuthBridgeBase.prototype.handleMessage=function(t){if(this._isOriginAllowed(t.origin)){var n;try{n=JSON.parse(t.data)}catch(e){}if(n&&this._isNamespacedData(n)){"*"===this._targetOrigin&&(this._targetOrigin=t.origin),Lt.debug("auth-bridge: handleMessage",n);var l=n.action.replace("mediakit:","");this[l]?this[l](n.data):Lt.debug("auth-bridge: unsupported method",l)}}},AuthBridgeBase.prototype._isOriginAllowed=function(t){if(!t)return!1;var n=__read$3(t.split("://"),2),l=n[0],d=n[1],p="";return d&&(p=d.split(":")[0]),"https"===l&&!!p&&p.endsWith(".apple.com")},AuthBridgeBase.prototype._isNamespacedData=function(t){return t.action&&-1!==t.action.indexOf("mediakit:")},AuthBridgeBase}(),xt=function(t){function AuthBridgeApp(){var n=t.call(this)||this;return n.whenFrameInited=new Promise((function(t){return n._frameInitResolve=t})),n.whenAuthCompleted=new Promise((function(t){return n._authUpdateResolve=t})),n.frame=document.createElement("iframe"),n.frame.src=n._getIframeSrc(),n.frame.style.display="none",document.body.appendChild(n.frame),n.init(window,n.frame.contentWindow),n}return __extends$3(AuthBridgeApp,t),AuthBridgeApp.prototype.requestAuthUpdate=function(){var t=this;this.whenFrameInited.then((function(){return t.sendMessage("requestAuthUpdate")}))},AuthBridgeApp.prototype.setCookieItem=function(t,n){var l=this;this.whenFrameInited.then((function(){return l.sendMessage("setCookieItem",{name:t,value:n})}))},AuthBridgeApp.prototype.clearAuth=function(){var t=this;this.whenFrameInited.then((function(){return t.sendMessage("clearAuth")}))},AuthBridgeApp.prototype.frameInit=function(){var t;null===(t=this._frameInitResolve)||void 0===t||t.call(this),this.requestAuthUpdate()},AuthBridgeApp.prototype.updateAuth=function(t){if(null==t?void 0:t.cookies){var n=t.cookies;Object.keys(n).forEach((function(t){var l,d,p,h=null!==(l=n[t])&&void 0!==l?l:"";h?setCookie(t,h,"/",7):setCookie(t,"","/",0,d,p)}))}this._authUpdateResolve&&(this._authUpdateResolve(),this._authUpdateResolve=void 0)},AuthBridgeApp.prototype.authClearedFromOtherFrame=function(){Lt.warn("Override auth-bridge/app's authClearedFromOtherFrame to trigger app-specific sign out behavior")},AuthBridgeApp.prototype._getIframeSrc=function(){return"https://"+determineCdnBasePrefix()+"mediaauth.apple.com/auth-bridge/"},AuthBridgeApp}(Nt),Ut=new Set(["apps","books","music","podcasts","tv"]),Bt=/\.apple\.com$/;function getCommerceHostname(t,n){!n&&"undefined"!=typeof location&&location.hostname&&(n=location);var l=t+".itunes.apple.com";if(!n||!localStorage.getItem("mk-auth-bridge-commerce"))return l;var d=function(t){if(t&&Bt.test(t)){var n=t.split("."),l=n[n.length-3],d=l;if(l&&l.includes("-")){var p=l.split("-");l=p[p.length-1]}if(Ut.has(l))return d}}(n.hostname);return d&&(l=t+"."+d+".apple.com"),l}function buildQueryParams(t){return void 0===t&&(t={app:Ct.APP,p:Ct.P}),void 0===t.app&&(t.app=Ct.APP),void 0===t.p&&(t.p=Ct.P),Object.keys(t).map((function(n){return encodeURIComponent(n)+"="+encodeURIComponent(t[n])})).join("&")}!function(t){t.APP="music",t.P="subscribe"}(Ct||(Ct={}));var jt,Ft=((Mt={})[2]="com.apple.onboarding.tvapp",Mt[0]="com.apple.onboarding.applemusic",Mt),Kt=((Dt={})[2]="pltvcid",Dt[0]="pldfltcid",Dt),Vt={"com.apple.onboarding.tvapp":5,"com.apple.onboarding.applemusic":3};!function(t){t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"}(jt||(jt={}));var $t,Ht=function(){function Dispatch(t){var n=this;void 0===t&&(t={}),this._registry={},this._sequence=0,this.handle=function(t){t.data&&"2.0"===t.data.jsonrpc&&("*"!==n.origin&&n.origin!==t.origin||(t.data.method&&n.destination?n.handleRequest(t.data).then((function(t){n.send(n.destination,t)})):(t.data.hasOwnProperty("result")||t.data.error)&&n.handleResponse(t.data)))},this.destination=t.destination,this.methods=t.methods||{},this.origin=t.origin||"*",t.source&&(this.source=t.source)}return Object.defineProperty(Dispatch.prototype,"source",{get:function(){return this._source},set:function(t){if(!t&&this._source)return this._source.removeEventListener("message",this.handle),void(this._source=void 0);t.addEventListener("message",this.handle),this._source=t},enumerable:!0,configurable:!0}),Dispatch.prototype.apply=function(t,n){var l=this;if(!this.destination)throw new Error("No destination");var d=this._sequence++,p=new Promise((function(t,n){l._registry[d]={resolve:t,reject:n}}));return this.send(this.destination,{jsonrpc:"2.0",id:d,method:t,params:n}),p},Dispatch.prototype.call=function(t){for(var n=[],l=1;l<arguments.length;l++)n[l-1]=arguments[l];return this.apply(t,n)},Dispatch.prototype.handleRequest=function(t){return __awaiter$1(this,void 0,void 0,(function(){var n,l,d,p;return __generator$1(this,(function(h){switch(h.label){case 0:if(n={jsonrpc:"2.0",id:t.id},!(l=this.methods[t.method]))return[2,Object.assign(n,{error:{code:jt.MethodNotFound,message:"Method not found"}})];h.label=1;case 1:return h.trys.push([1,3,,4]),[4,l.apply(null,ensureArray(t.params))];case 2:return d=h.sent(),[2,Object.assign(n,{result:d})];case 3:return p=h.sent(),[2,Object.assign(n,{error:{code:p.code||jt.InternalError,message:p.message}})];case 4:return[2]}}))}))},Dispatch.prototype.handleResponse=function(t){var n=this._registry[t.id];delete this._registry[t.id],n&&(t.error?n.reject(Object.assign(Error(),t.error)):n.resolve(t.result))},Dispatch.prototype.send=function(t,n){t.postMessage(n,t.window===t?this.origin:void 0)},Dispatch}();function validateToken(t){var n;if("string"!=typeof t)return!1;var l=t.match(/[a-zA-Z0-9=\/+]{32,}==$/);return null!==(n=l&&l.length>0)&&void 0!==n&&n}!function(t){t[t.UNAVAILABLE=-1]="UNAVAILABLE",t[t.NOT_DETERMINED=0]="NOT_DETERMINED",t[t.DENIED=1]="DENIED",t[t.RESTRICTED=2]="RESTRICTED",t[t.AUTHORIZED=3]="AUTHORIZED"}($t||($t={}));var zt,Wt="https://"+getCommerceHostname("buy")+"/commerce/account/authenticateMusicKitRequest",Yt="https://authorize.music.apple.com",qt=/^https?:\/\/(.+\.)*(apple\.com|apps\.mzstatic\.com)(\/[\w\d]+)*$/;!function(t){t[t.AUTHORIZE=0]="AUTHORIZE",t[t.SUBSCRIBE=1]="SUBSCRIBE"}(zt||(zt={}));var Gt,Qt=function(){function ServiceSetupView(t,n){void 0===n&&(n={}),this.developerToken=t,this.authenticateMethod="GET",this.target="apple-music-service-view",this.deeplinkParameters=n&&n.deeplinkParameters||{},this.iconURL=n&&n.iconURL,this.authenticateMethod=n&&n.authenticateMethod||"GET",this.isServiceView&&window.opener!==window&&(this.dispatch=new Ht({destination:window.opener,origin:"*",source:window}))}return Object.defineProperty(ServiceSetupView.prototype,"isServiceView",{get:function(){return/(authorize\.(.+\.)*apple\.com)/i.test(window.location.hostname)||window&&window.name===this.target||!1},enumerable:!0,configurable:!0}),ServiceSetupView.prototype.focus=function(){this._window&&window.focus&&this._window.focus()},ServiceSetupView.prototype.load=function(t){return void 0===t&&(t={action:zt.AUTHORIZE}),__awaiter$3(this,void 0,void 0,(function(){return __generator$3(this,(function(n){return t.action===zt.SUBSCRIBE?[2,this._subscribeAction(t.parameters)]:[2,this._authorizeAction(t.parameters)]}))}))},ServiceSetupView.prototype.present=function(t,n){void 0===t&&(t="");var l=this._calculateClientDimensions(),d=l.height,p=l.left,h=l.top,f=l.width,y={height:650,menubar:"no",resizable:"no",scrollbars:"no",status:"no",toolbar:"no",width:650},v=__assign$3(__assign$3(__assign$3({},y),{left:f/2-y.width/2+p,top:d/2-y.height/2+h}),n),g=Object.keys(v).map((function(t){return t+"="+v[t]})).join(",");return/trident|msie/i.test(navigator.userAgent)?(this._window=window.open(window.location.href,this.target,g)||void 0,this._window.location.href=t):this._window=window.open(t,this.target,g)||void 0,/\bedge\b/i.test(navigator.userAgent)&&(this._window.opener=self),this.focus(),this._window},ServiceSetupView.prototype._authorizeAction=function(t){return void 0===t&&(t={}),__awaiter$3(this,void 0,void 0,(function(){var n,l,d=this;return __generator$3(this,(function(p){return"GET"===this.authenticateMethod?l=Yt+"/woa?"+buildQueryParams({a:btoa(this._thirdPartyInfo())}):(n=this._buildFormElement(Wt),document.body.appendChild(n)),[2,new Promise((function(p,h){var f=d.present(l);d.dispatch=new Ht({methods:{authorize:function(t,n,l){validateToken(t)?p({restricted:n&&"1"===n,userToken:t,cid:l}):h($t.NOT_DETERMINED)},close:function(){},decline:function(){h($t.DENIED)},switchUserId:function(){h($t.NOT_DETERMINED)},thirdPartyInfo:function(){return d._thirdPartyInfo(d.developerToken,__assign$3(__assign$3({},d.deeplinkParameters),t))},unavailable:function(){h($t.UNAVAILABLE)}},origin:Yt,source:window,destination:f}),n&&n.submit()}))]}))}))},ServiceSetupView.prototype._buildFormElement=function(t,n,l){void 0===n&&(n=this.target),void 0===l&&(l=this.developerToken);var d=document.createElement("form");d.setAttribute("method","post"),d.setAttribute("action",t),d.setAttribute("target",n),d.style.display="none";var p=document.createElement("input");p.setAttribute("name","jwtToken"),p.setAttribute("value",l),d.appendChild(p);var h=document.createElement("input");h.setAttribute("name","isWebPlayer"),h.setAttribute("value","true"),d.appendChild(h);var f=document.createElement("input");return f.setAttribute("name","LogoURL"),f.setAttribute("value",""),d.appendChild(f),d},ServiceSetupView.prototype._calculateClientDimensions=function(t){return void 0===t&&(t=window),{height:t.innerHeight?t.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height,left:t.screenLeft?t.screenLeft:screen.availLeft||screen.left,top:t.screenTop?t.screenTop:screen.availTop||screen.top,width:t.innerWidth?t.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width}},ServiceSetupView.prototype._subscribeAction=function(t){return void 0===t&&(t={}),__awaiter$3(this,void 0,void 0,(function(){var n=this;return __generator$3(this,(function(l){return Object.assign(t,this.deeplinkParameters),[2,new Promise((function(l,d){var p="https://authorize.music.apple.com/upsell?"+buildQueryParams(t);n.present(p),window.addEventListener("message",(function(t){var n=t.data,p=t.origin,h=(t.source,"string"==typeof n?JSON.parse(n):n),f=(h.closeWindow,h.launchClient);p&&!qt.test(p)||(f?0===f.supported?d("Unable to subscribe on this platform."):l(f):d("Subscribe action error."))}))}))]}))}))},ServiceSetupView.prototype._thirdPartyInfo=function(t,n){var l;void 0===t&&(t=this.developerToken);var d=this.iconURL,p=window.location.host||document.referrer,h=function(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(__read$3(arguments[n]));return t}([].slice.call(document.querySelectorAll('link[rel="apple-music-app-icon"]')),[].slice.call(document.querySelectorAll('link[rel="apple-touch-icon-precomposed"]')),[].slice.call(document.querySelectorAll('link[rel="apple-touch-icon"]')));if(h&&h[0]&&h[0].href){var f=h.find((function(t){return!!t.sizes&&"120x120"===t.sizes.value}));d=null!==(l=null==f?void 0:f.href)&&void 0!==l?l:h[0].href}return JSON.stringify({thirdPartyIconURL:d,thirdPartyName:p,thirdPartyParameters:n,thirdPartyToken:t})},ServiceSetupView}();function fetchStorefronts(t,n){return void 0===n&&(n="https://api.music.apple.com/v1"),__awaiter$3(this,void 0,void 0,(function(){var l,d;return __generator$3(this,(function(p){switch(p.label){case 0:return l=new Headers({Authorization:"Bearer "+t}),[4,fetch(n+"/storefronts",{headers:l})];case 1:return[4,p.sent().json()];case 2:return(d=p.sent()).errors?[2,Promise.reject(d.errors)]:[2,d.data]}}))}))}!function(t){t.ID="us",t.LANGUAGE_TAG="en-gb"}(Gt||(Gt={}));var Jt,Xt,Zt=function(){function Storefront(t,n,l){this.id=t,this.attributes=n,this.type="storefronts",this.href=l||"/v1/"+this.type+"/"+t}return Storefront.inferFromLanguages=function(t,n){return void 0===n&&(n=getLanguages()),__awaiter$3(this,void 0,void 0,(function(){var l,d,p,h,f,y;return __generator$3(this,(function(v){switch(v.label){case 0:return[4,fetchStorefronts(t)];case 1:return l=v.sent(),d=l.map((function(t){return t.id})),p=n[0]||"en-US",h=__read$3(p.toLowerCase().split(/-|_/),2),h[0],f=h[1],y=d.includes(f)?f:"us",[2,l.find((function(t){return t.id===y}))]}}))}))},Storefront}();!function(t){t.DEFAULT_CID="pldfltcid",t.TV_CID="pltvcid",t.RESTRICTIONS_ENABLED="itre",t.STOREFRONT_COUNTRY_CODE="itua",t.USER_TOKEN="media-user-token"}(Jt||(Jt={})),function(t){t.authorizationStatusDidChange="authorizationStatusDidChange",t.authorizationStatusWillChange="authorizationStatusWillChange",t.eligibleForSubscribeView="eligibleForSubscribeView",t.needsGDPRDidChange="needsGDPRDidChange",t.storefrontCountryCodeDidChange="storefrontCountryCodeDidChange",t.storefrontIdentifierDidChange="storefrontIdentifierDidChange",t.userTokenDidChange="userTokenDidChange"}(Xt||(Xt={}));Jt.DEFAULT_CID;var er,tr="https://"+getCommerceHostname("buy"),rr="https://"+getCommerceHostname("play")+"/WebObjects/MZPlay.woa/wa",ir=function(t){function StoreKit(n,l){var d=t.call(this,[Xt.authorizationStatusDidChange,Xt.authorizationStatusWillChange,Xt.eligibleForSubscribeView,Xt.needsGDPRDidChange,Xt.storefrontCountryCodeDidChange,Xt.userTokenDidChange,Xt.storefrontIdentifierDidChange])||this;d.developerToken=n,d.apiBase="https://api.music.apple.com/v1",d.iTunesBuyBase=tr,d.persist="localstorage",d.playBase=rr,d.prefix="music",d.realm=0,d.storage=window.localStorage,d._authorizationStatus=$t.NOT_DETERMINED,d._dispatchedSubscribeView=!1,d._me=null,d._cids={},d._gdprVersion=-1,d._needsGDPR=void 0,d._dynamicUserToken=getCookie(Jt.USER_TOKEN),l&&(l.apiBase&&(d.apiBase=l.apiBase),l.deeplink&&(d.deeplinkParameters=l.deeplink),l.persist&&(d.persist=l.persist),l.prefix&&(d.prefix=l.prefix),void 0!==l.realm&&(d.realm=l.realm),d.bundleId=Ft[d.realm]),d.cidNamespace=Kt[d.realm],d._developerToken=new wt(n),d._serviceSetupView=new Qt(n,{authenticateMethod:l&&l.authenticateMethod,iconURL:l&&l.iconURL,deeplinkParameters:d.deeplinkParameters}),d.storagePrefix=(d.prefix+"."+d._developerToken.teamId).toLocaleLowerCase();var p=d._getStorageItem(Jt.USER_TOKEN);return d.userToken=p||void 0,d.developerToken&&d.userTokenIsValid&&(d._restrictedEnabled=d.restrictedEnabled,d.shouldDisplayPrivacyLink(d.bundleId).catch((function(){}))),d._storefrontCountryCode=d.storefrontCountryCode,d.whenAuthCompleted=Promise.resolve(),isNodeEnvironment()||(d._processLocationHash(window.location.hash),"cookie"===d.persist&&"undefined"!=typeof localStorage&&localStorage.getItem("mk-auth-bridge")&&(d.authBridgeApp=new xt,d.authBridgeApp.authClearedFromOtherFrame=d.revokeUserToken.bind(d),d.whenAuthCompleted=d.authBridgeApp.whenAuthCompleted.then((function(){d.userToken=d._getStorageItem(Jt.USER_TOKEN)||void 0})))),d}var n;return __extends$3(StoreKit,t),Object.defineProperty(StoreKit.prototype,"authorizationStatus",{get:function(){return this._authorizationStatus},set:function(t){this._authorizationStatus!==t&&(this._getIsActiveSubscription.updateCache(void 0),this.dispatchEvent(Xt.authorizationStatusWillChange,{authorizationStatus:this._authorizationStatus,newAuthorizationStatus:t}),this._authorizationStatus=t,this.dispatchEvent(Xt.authorizationStatusDidChange,{authorizationStatus:t}))},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"cid",{get:function(){if(!this._cids[this.cidNamespace]){var t=this._getStorageItem(this.cidNamespace);this._cids[this.cidNamespace]=t||void 0}return this._cids[this.cidNamespace]},set:function(t){t?this._setStorageItem(this.cidNamespace,t):this._removeStorageItem(this.cidNamespace),this._cids[this.cidNamespace]=t},enumerable:!0,configurable:!0}),StoreKit.prototype.eligibleForSubscribeView=function(){return __awaiter$3(this,void 0,void 0,(function(){var t;return __generator$3(this,(function(n){switch(n.label){case 0:return[4,this.hasMusicSubscription()];case 1:return t=n.sent(),[2,(!this.hasAuthorized||this.hasAuthorized&&!t)&&!this._dispatchedSubscribeView]}}))}))},Object.defineProperty(StoreKit.prototype,"hasAuthorized",{get:function(){return this.authorizationStatus>$t.DENIED},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"logoutURL",{get:function(){return this.iTunesBuyBase+"/account/web/logout"},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"parentalControls",{get:function(){return this._parentalControls},set:function(t){this._parentalControls=t,t&&(0===this.realm?this.restrictedEnabled=t.musicParentalControlsEnabled:2===this.realm&&t.videoContentRestrictions&&(this.authorizationStatus=$t.RESTRICTED))},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"_pldfltcid",{get:function(){return this._cids[Jt.DEFAULT_CID]},set:function(t){this._cids[Jt.DEFAULT_CID]=t},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"privacyAcknowledgements",{get:function(){return this._privacyAcknowledgements},set:function(t){if(this._privacyAcknowledgements=t,!t)return this._gdprVersion=-1,void(this._needsGDPR=void 0);this.bundleId&&(this._gdprVersion=t[this.bundleId]||0,this._needsGDPR=this._gdprVersion<(Vt[this.bundleId]||0),this._needsGDPR&&this.dispatchEvent(Xt.needsGDPRDidChange,{GDPRVersion:this._gdprVersion,needsGDPR:this._needsGDPR}))},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"restrictedEnabled",{get:function(){if(this.userToken&&"boolean"!=typeof this._restrictedEnabled){var t=this._getStorageItem(Jt.RESTRICTIONS_ENABLED);if(t)this._restrictedEnabled="0"!==t;else if(this._storefrontCountryCode){this._restrictedEnabled=-1!==["br","ch","gt","hu","id","in","it","kr","la","lt","my","ru","sg","tr"].indexOf(this._storefrontCountryCode)||void 0}}return this._restrictedEnabled},set:function(t){this.userToken&&void 0!==t&&this._setStorageItem(Jt.RESTRICTIONS_ENABLED,t?"1":"0"),this._restrictedEnabled=t,t&&(this.authorizationStatus=$t.RESTRICTED)},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"storefrontCountryCode",{get:function(){if(!this._storefrontCountryCode){var t=this._getStorageItem(Jt.STOREFRONT_COUNTRY_CODE);this._storefrontCountryCode=(null==t?void 0:t.toLowerCase())||Gt.ID}return this._storefrontCountryCode},set:function(t){t&&this.userToken?this._setStorageItem(Jt.STOREFRONT_COUNTRY_CODE,t):this._removeStorageItem(Jt.STOREFRONT_COUNTRY_CODE),this._storefrontCountryCode=t,this.dispatchEvent(Xt.storefrontCountryCodeDidChange,{storefrontCountryCode:t})},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"storefrontIdentifier",{get:function(){return this._storefrontIdentifier},set:function(t){this._storefrontIdentifier=t,this.dispatchEvent(Xt.storefrontIdentifierDidChange,{storefrontIdentifier:t})},enumerable:!0,configurable:!0}),StoreKit.prototype.runTokenValidations=function(t,n){void 0===n&&(n=!0),t&&validateToken(t)?(n&&this._setStorageItem(Jt.USER_TOKEN,t),this.authorizationStatus=this.restrictedEnabled?$t.RESTRICTED:$t.AUTHORIZED):(this._removeStorageItem(Jt.USER_TOKEN),this.authorizationStatus=$t.NOT_DETERMINED)},StoreKit.prototype.wrapDynamicUserTokenForChanges=function(t,n){var l=this;if(void 0===n&&(n=Fe(t)),"function"!=typeof t)return t;var d=n;return function(){var n=Fe(t);return d!==n&&(d=n,l.runTokenValidations(n,!1),l.dispatchEvent(Xt.userTokenDidChange,{userToken:n})),n||""}},Object.defineProperty(StoreKit.prototype,"dynamicUserToken",{get:function(){return this._dynamicUserToken},set:function(t){var n=Fe(t);this._dynamicUserToken=this.wrapDynamicUserTokenForChanges(t,n),this.runTokenValidations(n,"function"!=typeof t),this.dispatchEvent(Xt.userTokenDidChange,{userToken:n})},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"userToken",{get:function(){return Fe(this.dynamicUserToken)},set:function(t){var n;this.dynamicUserToken=t,null===(n=this.authBridgeApp)||void 0===n||n.requestAuthUpdate()},enumerable:!0,configurable:!0}),Object.defineProperty(StoreKit.prototype,"userTokenIsValid",{get:function(){return validateToken(this.userToken)},enumerable:!0,configurable:!0}),StoreKit.prototype.deeplinkURL=function(t){return void 0===t&&(t={}),"https://finance-app.itunes.apple.com/deeplink?"+buildQueryParams(t=__assign$3(__assign$3({},this.deeplinkParameters||{}),t))},StoreKit.prototype.itunesDeeplinkURL=function(t){return void 0===t&&(t={p:"browse"}),"https://itunes.apple.com/deeplink?"+buildQueryParams(t=__assign$3(__assign$3({},this.deeplinkParameters||{}),t))},StoreKit.prototype.pldfltcid=function(){return __awaiter$3(this,void 0,void 0,(function(){return __generator$3(this,(function(t){switch(t.label){case 0:if(this._cids[Jt.DEFAULT_CID])return[3,4];t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.infoRefresh()];case 2:return t.sent(),[3,4];case 3:return t.sent(),[2,void 0];case 4:return[2,this._cids[Jt.DEFAULT_CID]]}}))}))},StoreKit.prototype.renewUserToken=function(){return __awaiter$3(this,void 0,void 0,(function(){var t,n,l;return __generator$3(this,(function(d){switch(d.label){case 0:return this.userToken?(t=new Headers({Authorization:"Bearer "+this.developerToken,Accept:"application/json","Content-Type":"application/json","X-Apple-Music-User-Token":""+this.userToken}),[4,fetch(this.playBase+"/renewMusicToken",{method:"POST",headers:t})]):[2,this.requestUserToken()];case 1:return 401!==(n=d.sent()).status?[3,3]:[4,this.revokeUserToken()];case 2:return d.sent(),[2,Promise.reject(new Error("Renew token"))];case 3:return[4,n.json()];case 4:return(l=d.sent())["music-token"]&&(this.userToken=l["music-token"]),[2,this.userToken]}}))}))},StoreKit.prototype.requestStorefrontCountryCode=function(){return __awaiter$3(this,void 0,void 0,(function(){var t,n,l,d,p;return __generator$3(this,(function(h){switch(h.label){case 0:return this.authorizationStatus<=$t.DENIED?[2,Promise.reject("Not authorized: "+this.authorizationStatus)]:(t=new Headers({Authorization:"Bearer "+this.developerToken,"Music-User-Token":this.userToken||""}),[4,fetch(this.apiBase+"/me/storefront",{headers:t})]);case 1:return(n=h.sent())&&!n.ok?(this._reset(),[2,Promise.reject("Storefront Country Code error.")]):[4,n.json()];case 2:return(l=h.sent()).errors?[2,Promise.reject(l.errors)]:(d=__read$3(l.data,1),(p=d[0])&&p.id?(this.storefrontCountryCode=p.id,[2,this.storefrontCountryCode]):[2,Promise.reject("Storefront Country Code error.")])}}))}))},StoreKit.prototype.requestStorefrontIdentifier=function(){return __awaiter$3(this,void 0,void 0,(function(){var t;return __generator$3(this,(function(n){switch(n.label){case 0:return this.storefrontIdentifier?[3,2]:[4,Zt.inferFromLanguages(this.developerToken)];case 1:t=n.sent(),this.storefrontIdentifier=t.id,n.label=2;case 2:return[2,this.storefrontIdentifier]}}))}))},StoreKit.prototype.requestUserToken=function(){return __awaiter$3(this,void 0,void 0,(function(){var t,n;return __generator$3(this,(function(l){switch(l.label){case 0:if(this._serviceSetupView.isServiceView)return[2,this.userToken||""];l.label=1;case 1:return l.trys.push([1,3,,4]),[4,this._serviceSetupView.load({action:zt.AUTHORIZE})];case 2:return t=l.sent(),this.cid=t.cid,this.userToken=t.userToken,this.restrictedEnabled=t.restricted,[3,4];case 3:return n=l.sent(),this._reset(),this.authorizationStatus=n,[2,Promise.reject(n)];case 4:return[2,this.userToken]}}))}))},StoreKit.prototype.revokeUserToken=function(){var t;return __awaiter$3(this,void 0,void 0,(function(){return __generator$3(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this._webPlayerLogout()];case 1:return n.sent(),[3,3];case 2:return n.sent(),[3,3];case 3:return null===(t=this.authBridgeApp)||void 0===t||t.clearAuth(),this.dispatchEvent(Xt.authorizationStatusWillChange,{authorizationStatus:this.authorizationStatus,newAuthorizationStatus:$t.NOT_DETERMINED}),this._reset(),this.dispatchEvent(Xt.authorizationStatusDidChange,{authorizationStatus:this.authorizationStatus}),this.dispatchEvent(Xt.userTokenDidChange,{userToken:this.userToken}),[2]}}))}))},StoreKit.prototype.setCids=function(t){var n=this;this._cids=__assign$3(__assign$3({},this._cids),t),Object.keys(this._cids).forEach((function(t){n._setStorageItem(t,n._cids[t])}))},StoreKit.prototype.shouldDisplayPrivacyLink=function(t){return __awaiter$3(this,void 0,void 0,(function(){return __generator$3(this,(function(n){switch(n.label){case 0:return t||(t=this.bundleId),void 0!==this._needsGDPR?[2,this._needsGDPR]:[4,this.me()];case 1:return n.sent(),[2,this._needsGDPR]}}))}))},StoreKit.prototype.hasMusicSubscription=function(){return __awaiter$3(this,void 0,void 0,(function(){return __generator$3(this,(function(t){return this.hasAuthorized?[2,this._getIsActiveSubscription()]:[2,!1]}))}))},StoreKit.prototype._getIsActiveSubscription=function(){var t;return __awaiter$3(this,void 0,void 0,(function(){var n;return __generator$3(this,(function(l){switch(l.label){case 0:return[4,this.me()];case 1:return n=l.sent(),[2,!!(null===(t=n.subscription)||void 0===t?void 0:t.active)]}}))}))},StoreKit.prototype.resetSubscribeViewEligibility=function(){this._dispatchedSubscribeView=!1},StoreKit.prototype.presentSubscribeViewForEligibleUsers=function(t,n){return void 0===t&&(t={}),void 0===n&&(n=!0),__awaiter$3(this,void 0,void 0,(function(){var l,d;return __generator$3(this,(function(p){switch(p.label){case 0:return[4,this.eligibleForSubscribeView()];case 1:if(l=p.sent(),this._serviceSetupView.isServiceView||!l)return[2];if(!n)return this.dispatchEvent(Xt.eligibleForSubscribeView,t),this._dispatchedSubscribeView=!0,[2];p.label=2;case 2:return p.trys.push([2,4,,5]),[4,this._serviceSetupView.load({action:zt.SUBSCRIBE})];case 3:return d=p.sent(),this._dispatchedSubscribeView=!0,[2,d];case 4:return p.sent(),[2,this.revokeUserToken()];case 5:return[2]}}))}))},StoreKit.prototype.infoRefresh=function(){return __awaiter$3(this,void 0,void 0,(function(){var t,n;return __generator$3(this,(function(l){switch(l.label){case 0:if(this.authorizationStatus<=$t.DENIED)return[2,Promise.reject("Not authorized: "+this.authorizationStatus)];if(2!==this.realm)return[3,5];t=new Headers({Authorization:"Bearer "+this.developerToken,"Music-User-Token":this.userToken||""}),l.label=1;case 1:return l.trys.push([1,4,,5]),[4,fetch(this.iTunesBuyBase+"/account/web/infoRefresh",{credentials:"include",headers:t})];case 2:return[4,l.sent().json()];case 3:return n=l.sent(),this.setCids(n),[3,5];case 4:return l.sent(),[3,5];case 5:return[2]}}))}))},StoreKit.prototype.me=function(){var t=this;return this.authorizationStatus<=$t.DENIED?Promise.reject("Not authorized: "+this.authorizationStatus):(this._me||(this._me=new Promise((function(n,l){return __awaiter$3(t,void 0,void 0,(function(){var t,d,p,h,f,y,v;return __generator$3(this,(function(g){switch(g.label){case 0:return t=new Headers({Authorization:"Bearer "+this.developerToken,"Music-User-Token":this.userToken||""}),[4,fetch(this.apiBase+"/me/account?meta=subscription",{headers:t})];case 1:return(d=g.sent())&&!d.ok?(2!==this.realm&&this._reset(),[2,l("Account error.")]):[4,d.json()];case 2:if((p=g.sent()).errors)return[2,l(p.errors)];if(h=p.data,!(f=p.meta)||!f.subscription)return[2,l("Account error.")];this.storefrontCountryCode=f.subscription.storefront,y={subscription:f.subscription},h&&h.length&&(y.attributes=h[0].attributes),g.label=3;case 3:return g.trys.push([3,13,,14]),[4,fetch(this.iTunesBuyBase+"/account/web/info",{credentials:"include",headers:t})];case 4:return[4,g.sent().json()];case 5:if(p=g.sent(),this.parentalControls=p.parentalControlsData,this.privacyAcknowledgements=p.privacyAcknowledgement,!function(t){if("object"!=typeof t)throw new TypeError("Source is not an Object");for(var n in t)if(pe.call(t,n))return!1;return!0}(this.privacyAcknowledgements||{}))return[3,12];g.label=6;case 6:return g.trys.push([6,8,,9]),[4,this.infoRefresh()];case 7:return g.sent(),[3,9];case 8:return g.sent(),n(y),[3,9];case 9:return[4,fetch(this.iTunesBuyBase+"/account/web/info",{credentials:"include",headers:t})];case 10:return[4,g.sent().json()];case 11:p=g.sent(),this.parentalControls=p.parentalControlsData,this.privacyAcknowledgements=p.privacyAcknowledgement,g.label=12;case 12:return y.info=p,[3,14];case 13:return v=g.sent(),console.warn("Failed to fetch privacyAcknowledgements",v),[3,14];case 14:return[2,n(y)]}}))}))})).then((function(n){var l;return t._getIsActiveSubscription.updateCache((null===(l=n.subscription)||void 0===l?void 0:l.active)||!1),t._me=null,n})).catch((function(n){return t._me=null,Promise.reject(n)}))),this._me)},StoreKit.prototype.musicSubscriptionOffers=function(t,n){return void 0===n&&(n=getLanguages()),__awaiter$3(this,void 0,void 0,(function(){var l,d,p,h,f,y,v;return __generator$3(this,(function(g){switch(g.label){case 0:return this.hasAuthorized?[4,this.me()]:[3,2];case 1:return d=g.sent(),l=d.info.storeFrontISO3A,[3,5];case 2:return t?[3,4]:[4,Zt.inferFromLanguages(this.developerToken,n)];case 3:p=g.sent(),t=null==p?void 0:p.id,g.label=4;case 4:l=t&&It[t.toUpperCase()]||"USA",g.label=5;case 5:return h=function(t){void 0===t&&(t="en-US");var n=Et[t.toLowerCase()];if(n)return n;if(t.includes("-")){var l=t.split("-")[0],d=Et[l.toLowerCase()];if(d)return d}return Et["en-us"]}(n[0]),f=At[l],h&&f?(y=new Headers({"X-Apple-Store-Front":f+"-"+h+",8"}),"undefined"!=typeof localStorage&&localStorage.getItem("mk-auth-bridge")&&this.userToken&&(y.set("Authorization","Bearer "+this.developerToken),y.set("Music-User-Token",this.userToken)),[4,fetch(this.iTunesBuyBase+"/commerce/web/subscription/offers/music",{headers:y})]):[2,[]];case 6:return(v=g.sent()).ok?[4,v.json()]:[2,Promise.reject(v.status)];case 7:return[2,g.sent().offers]}}))}))},StoreKit.prototype._getStorageItem=function(t){if(t)return"cookie"===this.persist?getCookie(t):"localstorage"===this.persist?this.storage.getItem(this.storagePrefix+"."+t):void 0},StoreKit.prototype._processLocationHash=function(t){var n=/^\#([a-zA-Z0-9+\/]{200,}={0,2})$/;if(n.test(t)){var l=t.replace(n,"$1");try{var d=JSON.parse(atob(l)),p=d.itre,h=d.musicUserToken,f=d.cid;this.restrictedEnabled=p&&"1"===p,this.userToken=h,this.cid=f}catch(Dt){}history.replaceState(null,document.title," ")}},StoreKit.prototype._removeStorageItem=function(t){return"cookie"===this.persist?setCookie(t,"","/",0):"localstorage"===this.persist?this.storage.removeItem(this.storagePrefix+"."+t):void 0},StoreKit.prototype._reset=function(t){var n=this;void 0===t&&(t=$t.NOT_DETERMINED),this._authorizationStatus=t,this._cids={},this._dispatchedSubscribeView=!1,this._restrictedEnabled=void 0,this._storefrontCountryCode=void 0,this._getIsActiveSubscription.updateCache(void 0),Object.keys(Kt).forEach((function(t){n._removeStorageItem(Kt[t])})),this._removeStorageItem(Jt.RESTRICTIONS_ENABLED),this._removeStorageItem(Jt.USER_TOKEN),this._removeStorageItem(Jt.STOREFRONT_COUNTRY_CODE),this._dynamicUserToken=void 0,this._me=null,this.privacyAcknowledgements=void 0},StoreKit.prototype._setStorageItem=function(t,n){var l;return"cookie"===this.persist?(null===(l=this.authBridgeApp)||void 0===l||l.setCookieItem(t,n),setCookie(t,n,"/",180)):"localstorage"===this.persist?this.storage.setItem(this.storagePrefix+"."+t,n):void 0},StoreKit.prototype._webPlayerLogout=function(){return __awaiter$3(this,void 0,void 0,(function(){var t,n;return __generator$3(this,(function(l){switch(l.label){case 0:return(t=new Headers({Authorization:"Bearer "+this.developerToken,Accept:"application/json","Content-Type":"application/json","X-Apple-Music-User-Token":""+this.userToken})).delete("X-Apple-Music-User-Token"),t.append("Music-User-Token",this.userToken||""),[4,fetch(this.logoutURL,{method:"POST",headers:t,credentials:"include"})];case 1:return(n=l.sent())&&!n.ok?[2,Promise.reject(n.status)]:[2,n.json()]}}))}))},function(t,n,l,d){var p,h=arguments.length,f=h<3?n:null===d?d=Object.getOwnPropertyDescriptor(n,l):d;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)f=Reflect.decorate(t,n,l,d);else for(var y=t.length-1;y>=0;y--)(p=t[y])&&(f=(h<3?p(f):h>3?p(n,l,f):p(n,l))||f);h>3&&f&&Object.defineProperty(n,l,f)}([(n=900,void 0===n&&(n=300),function(t,l,d){if(void 0===d||"function"!=typeof d.value)throw new TypeError("Only methods can be decorated with @CachedResult, but "+l+" is not a method.");return{configurable:!0,get:function(){var t,p=d.value,h=1e3*n,f=-1;function cachedResultMethod(){for(var n=[],l=0;l<arguments.length;l++)n[l]=arguments[l];return __awaiter$1(this,void 0,void 0,(function(){var l;return __generator$1(this,(function(d){switch(d.label){case 0:return l=Date.now(),void 0===t||-1===f||f>0&&l>f+h?(f=l,[4,p.apply(this,n)]):[3,2];case 1:t=d.sent(),d.label=2;case 2:return[2,t]}}))}))}return cachedResultMethod.updateCache=function(n){f=Date.now(),t=n},cachedResultMethod.getCachedValue=function(){return t},Object.defineProperty(this,l,{value:cachedResultMethod,configurable:!0,writable:!0}),cachedResultMethod}}}),__metadata$1("design:type",Function),__metadata$1("design:paramtypes",[]),__metadata$1("design:returntype",Promise)],StoreKit.prototype,"_getIsActiveSubscription",null),StoreKit}(he),nr={configured:"musickitconfigured",loaded:"musickitloaded",audioTrackAdded:"audioTrackAdded",audioTrackChanged:"audioTrackChanged",audioTrackRemoved:"audioTrackRemoved",authorizationStatusDidChange:Xt.authorizationStatusDidChange,authorizationStatusWillChange:Xt.authorizationStatusWillChange,bufferedProgressDidChange:"bufferedProgressDidChange",capabilitiesChanged:"capabilitiesChanged",drmUnsupported:"drmUnsupported",eligibleForSubscribeView:Xt.eligibleForSubscribeView,forcedTextTrackChanged:"forcedTextTrackChanged",mediaCanPlay:"mediaCanPlay",mediaElementCreated:"mediaElementCreated",mediaItemStateDidChange:"mediaItemStateDidChange",mediaItemStateWillChange:"mediaItemStateWillChange",mediaPlaybackError:"mediaPlaybackError",mediaSkipAvailable:"mediaSkipAvailable",mediaRollEntered:"mediaRollEntered",mediaUpNext:"mediaUpNext",metadataDidChange:"metadataDidChange",needsGDPRDidChange:"needsGDPRDidChange",nowPlayingItemDidChange:"nowPlayingItemDidChange",nowPlayingItemWillChange:"nowPlayingItemWillChange",playbackBitrateDidChange:"playbackBitrateDidChange",playbackDurationDidChange:"playbackDurationDidChange",playbackProgressDidChange:"playbackProgressDidChange",playbackStateDidChange:"playbackStateDidChange",playbackStateWillChange:"playbackStateWillChange",playbackTargetAvailableDidChange:"playbackTargetAvailableDidChange",playbackTargetIsWirelessDidChange:"playbackTargetIsWirelessDidChange",playbackTimeDidChange:"playbackTimeDidChange",playbackVolumeDidChange:"playbackVolumeDidChange",playerTypeDidChange:"playerTypeDidChange",presentationModeDidChange:"presentationModeDidChange",primaryPlayerDidChange:"primaryPlayerDidChange",queueIsReady:"queueIsReady",queueItemsDidChange:"queueItemsDidChange",queueItemForStartPosition:"queueItemForStartPosition",queuePositionDidChange:"queuePositionDidChange",shuffleModeDidChange:"shuffleModeDidChange",repeatModeDidChange:"repeatModeDidChange",storefrontCountryCodeDidChange:Xt.storefrontCountryCodeDidChange,storefrontIdentifierDidChange:Xt.storefrontIdentifierDidChange,textTrackAdded:"textTrackAdded",textTrackChanged:"textTrackChanged",textTrackRemoved:"textTrackRemoved",userTokenDidChange:Xt.userTokenDidChange};!function(t){t.apiStorefrontChanged="apiStorefrontChanged",t.hlsLevelUpdated="hlsLevelUpdated",t.mediaContentComplete="mediaContentComplete",t.playbackPause="playbackPause",t.playbackPlay="playbackPlay",t.playbackScrub="playbackScrub",t.playbackSeek="playbackSeek",t.playbackSkip="playbackSkip",t.playbackStop="playbackStop",t.playerActivate="playerActivate",t.playerExit="playerExit",t.queueModified="queueModified",t.userActivityIntent="userActivityIntent",t.applicationActivityIntent="applicationActivityIntent"}(er||(er={}));var or={};function adaptAddEventListener(t,n,l,d){void 0===d&&(d={});var p=d.once,h=function(t,n){var l=getCallbacksForName(t),wrappedCallback=function(t,l){n(l)};return l.push([n,wrappedCallback]),wrappedCallback}(n,l);!0===p?t.subscribeOnce(n,h):t.subscribe(n,h)}function getCallbacksForName(t){var n=or[t];return n||(n=[],or[t]=n),n}var ar,sr=getHlsJsCdnConfig(),ur={app:{},features:{xtrick:!0,isWeb:!0,bookmarking:!1},supportedMediaTypes:yt,unencryptedPlaybackTypes:{"uploaded-videos":!0,uploadedVideo:!0,"uploaded-audios":!0,uploadedAudio:!0,"podcast-episodes":!0},urls:{hls:sr.hls,rtc:sr.rtc,mediaApi:"https://amp-api.music.apple.com/v1",webPlayback:"https://"+getCommerceHostname("play")+"/WebObjects/MZPlay.woa/wa/webPlayback"}};var cr=function(){function Store(t,n){var l=this;void 0===n&&(n={}),this._hasAuthorized=!1,this._providedRequestUserToken=!1,this._dispatcher=n.services.dispatcher,n.precache&&(this.precache=n.precache),n.storefrontId&&(this.storefrontId=n.storefrontId),this._defaultStorefrontCountryCode=n.storefrontCountryCode,(n.affiliateToken||n.campaignToken)&&(n.linkParameters=__assign(__assign({},n.linkParameters||{}),{at:n.affiliateToken,ct:n.campaignToken})),this.storekit=new ir(t,{apiBase:ur.urls.mediaApi,authenticateMethod:ur.features["legacy-authenticate-method"]?"POST":"GET",deeplink:n.linkParameters,iconURL:ur.app.icon,persist:n.persist,realm:n.realm||0}),this.storekit.addEventListener(nr.authorizationStatusDidChange,(function(t){var n=t.authorizationStatus;l._hasAuthorized=[$t.AUTHORIZED,$t.RESTRICTED].includes(n)}))}return Object.defineProperty(Store.prototype,"authorizationStatus",{get:function(){return this.storekit.authorizationStatus},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"cid",{get:function(){return this.storekit.cid},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"developerToken",{get:function(){return this.storekit.developerToken},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"hasAuthorized",{get:function(){return this._hasAuthorized},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"isAuthorized",{get:function(){return this.storekit.hasAuthorized},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"isRestricted",{get:function(){return this.storekit.authorizationStatus===$t.RESTRICTED},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"musicUserToken",{get:function(){return this.storekit.userToken},set:function(t){this.storekit.userToken=t},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"dynamicMusicUserToken",{set:function(t){this.storekit.dynamicUserToken=t},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"needsGDPR",{get:function(){Pt.error("needsGDPR has been deprecated. Plesae migrate to shouldDisplayPrivacyLink()")},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"realm",{get:function(){return this.storekit.realm},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"requestUserToken",{set:function(t){this._providedRequestUserToken=!0,this.storekit.requestUserToken=t},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"restrictedEnabled",{get:function(){return this.storekit.restrictedEnabled},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"storefrontCountryCode",{get:function(){var t;return this.isAuthorized?this.storekit.storefrontCountryCode:null!==(t=this._defaultStorefrontCountryCode)&&void 0!==t?t:this.storekit.storefrontCountryCode},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"storefrontId",{get:function(){return this._apiStorefrontId||this.storekit.storefrontCountryCode},set:function(t){t&&(t=t.toLowerCase()),t!==this._apiStorefrontId&&(this._apiStorefrontId=t,this._dispatcher.publish(er.apiStorefrontChanged,{storefrontId:t}))},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"subscribeURL",{get:function(){return this.storekit.deeplinkURL({p:"subscribe"})},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"subscribeFamilyURL",{get:function(){return this.storekit.deeplinkURL({p:"subscribe-family"})},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"subscribeIndividualURL",{get:function(){return this.storekit.deeplinkURL({p:"subscribe-individual"})},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"subscribeStudentURL",{get:function(){return this.storekit.deeplinkURL({p:"subscribe-student"})},enumerable:!0,configurable:!0}),Object.defineProperty(Store.prototype,"userToken",{get:function(){return this.musicUserToken},enumerable:!0,configurable:!0}),Store.prototype.authorize=function(){return __awaiter(this,void 0,void 0,(function(){var t,n=this;return __generator(this,(function(l){switch(l.label){case 0:return this.storekit.userTokenIsValid?[2,this.storekit.userToken]:[4,this.storekit.requestUserToken()];case 1:return t=l.sent(),this._providedRequestUserToken&&(this.storekit.userToken=t),this.storekit.userTokenIsValid?[4,this.storekit.requestStorefrontCountryCode().catch((function(t){return __awaiter(n,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this.unauthorize()];case 1:return n.sent(),[2,Promise.reject(t)]}}))}))}))]:[3,3];case 2:return l.sent(),[2,t];case 3:return[2]}}))}))},Store.prototype.shouldDisplayPrivacyLink=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,this.storekit.shouldDisplayPrivacyLink(t)]}))}))},Store.prototype.unauthorize=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this.storekit.revokeUserToken()]}))}))},Store.prototype.validateAgeVerification=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l;return __generator(this,(function(d){switch(d.label){case 0:return 2!==this.storekit.realm?[2]:[4,this.storekit.me()];case 1:return(n=d.sent()).info?n.info.webAgeVerificationData&&!n.info.webAgeVerificationData.isVerified?[2,Promise.reject(new ke(ke.AGE_VERIFICATION,"Age verification required"))]:t.rating&&n.info.parentalControlsData&&n.info.parentalControlsData.videoContentRestrictions&&(l=t.rating.system.replace(/[^a-z0-9]+/i,"-"),n.info.parentalControlsData.videoContentRestrictions[l]<t.rating.value)?[2,Promise.reject(new ke(ke.CONTENT_RESTRICTED,"Content restricted"))]:[2]:[2]}}))}))},Store}(),lr=/\/([a-z]{2})\/(album|artist|episode|movie|music-video|playlist|podcast|post|show|song|station)\/(?:[^\/]*\/)?(?:id)?(\d+|[a-z]{2}\.[a-z0-9\-]+|umc.cmc.[a-zA-Z0-9]+)(?:.*(?:[\?|\&]i=(\d+)).*)?.*$/i;function formattedSeconds(t){return{hours:Math.floor(t/3600),minutes:Math.floor(t%3600/60)}}function formatMediaTime(t,n){void 0===n&&(n=":");var l=formattedSeconds(t),d=l.hours,p=l.minutes;t=Math.floor(t%3600%60);var h=[];return d?(h.push(""+d),h.push(p<10?"0"+p:""+p)):h.push(""+p),h.push(t<10?"0"+t:""+t),h.join(n)}function formattedMediaURL(t){if(!lr.test(t))throw new TypeError("Invalid Media URL: "+t);var n=__read(t.match(lr),5),l=n[1],d=n[2],p=n[3],h=n[4];return"music-video"===d&&(d="musicVideo"),-1!==["album","playlist"].indexOf(d)&&h?(d="song",p=h):"podcast"===d&&h&&(d="episode",p=h),{storefrontId:l,kind:d,contentId:p,isUTS:!!p&&p.startsWith("umc.")}}function hasAuthorization(t){return void 0===t&&(t=ar&&ar.storekit),void 0!==t&&t.hasAuthorized&&t.userTokenIsValid}function hasMusicSubscription(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return void 0===t&&(t=ar&&ar.storekit),[2,t.hasMusicSubscription()]}))}))}function rewriteLastUrlPath(t,n){var l=t.split("/");return l.pop(),l.push(n),l.join("/")}var dr,pr,getUpNextStart=function(t){return parseFloat(t.hlsMetadata["up-next.start"])},getWatchedTime=function(t){return parseFloat(t.hlsMetadata["watched.time"])},fetchHLSMetadata=function(t){return __awaiter(void 0,void 0,void 0,(function(){var n,l,d;return __generator(this,(function(p){switch(p.label){case 0:if(!t.isUTS||!t.assetURL)return[2];p.label=1;case 1:return p.trys.push([1,3,,4]),[4,fetch(t.assetURL).then((function(t){return t.text()}))];case 2:return n=p.sent(),(l=n.match(/^(?:#EXT-X-SESSION-DATA:?)DATA\-ID="([^"]+)".+VALUE="([^"]+)".*$/gm))&&l.forEach((function(n){var l=n.split(",")[0].split("com.apple.hls.")[1].replace(/"/g,""),d=n.split(",")[1].split("VALUE=")[1].replace(/"/g,"");t.hlsMetadata[l]=d})),[3,4];case 3:return d=p.sent(),Pt.log(d),[3,4];case 4:return[2]}}))}))};(dr=t.PlaybackType||(t.PlaybackType={}))[dr.none=0]="none",dr[dr.preview=1]="preview",dr[dr.unencryptedFull=2]="unencryptedFull",dr[dr.encryptedFull=3]="encryptedFull",function(t){t[t.none=0]="none",t[t.loading=1]="loading",t[t.ready=2]="ready",t[t.playing=3]="playing",t[t.ended=4]="ended",t[t.unavailable=5]="unavailable",t[t.restricted=6]="restricted",t[t.error=7]="error",t[t.unsupported=8]="unsupported"}(pr||(pr={}));var hr,fr,yr,parseRollItems=function(t,n){if(void 0===n&&(n=["pre-roll","mid-roll","post-roll"]),void 0===t.hlsMetadata)return[];var l=[];return n.forEach((function(n){var d=parseInt(t.hlsMetadata[n+".count"],10);if(!isNaN(d))for(var p=0;p<d;p++){var h=n+"."+p;l.push({index:p,type:n,skippable:"true"===t.hlsMetadata[h+".skippable"],"adam-id":t.hlsMetadata[h+".adam-id"],start:Math.round(parseFloat(t.hlsMetadata[h+".start"])),duration:Math.round(parseFloat(t.hlsMetadata[h+".duration"]))})}})),l},logDeprecation=function(t,n){if(void 0===n&&(n={}),Pt&&Pt.enabled){var l=[];l.push("Deprecation warning:"),l.push(n.message||t+" has been deprecated."),void 0!==n.until&&l.push(t+" will be removed in version "+n.until+"."),Pt.warn(l.join(" "))}},Bind=function(){return function(t,n,l){if(void 0===l||"function"!=typeof l.value)throw new TypeError("Only methods can be decorated with @Bind, but "+n+" is not a method.");return{configurable:!0,get:function(){var t=l.value.bind(this);return Object.defineProperty(this,n,{value:t,configurable:!0,writable:!0}),t}}}},vr=function(){function PlaybackMonitor(t){this.isActive=!1,this.isMonitoring=!1,this.watchers=[],this.handlePlaybackThreshold=this.handlePlaybackThreshold.bind(this),this.playbackController=t.controller,this.dispatcher=t.services.dispatcher,this.dispatcher.subscribe(nr.nowPlayingItemDidChange,this.handleMediaItemChange),this.apiManager=t.services.apiManager}return PlaybackMonitor.prototype.activate=function(){this.isActive=!0,this.startMonitor()},PlaybackMonitor.prototype.deactivate=function(){this.isActive=!1,this.clearMonitor()},PlaybackMonitor.prototype.clearMonitor=function(){this.isMonitoring&&(this.watchers.forEach((function(t){return t.stopMonitor()})),this.isMonitoring=!1)},PlaybackMonitor.prototype.shouldMonitor=function(){return this.isActive},PlaybackMonitor.prototype.startMonitor=function(){this.shouldMonitor()&&(this.watchers.forEach((function(t){return t.startMonitor()})),this.isMonitoring=!0)},PlaybackMonitor.prototype.handleMediaItemChange=function(){this.isActive&&(this.clearMonitor(),this.shouldMonitor()&&this.startMonitor())},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],PlaybackMonitor.prototype,"handleMediaItemChange",null),PlaybackMonitor}(),gr=function(){function SpanWatcher(t,n,l,d,p){void 0===p&&(p=!1),this.dispatcher=t,this.callback=n,this.start=l,this.stop=d,this.allowMultiple=p,this.inWatchSpan=!1}return SpanWatcher.prototype.startMonitor=function(){this.dispatcher.unsubscribe(nr.playbackTimeDidChange,this.handleTimeChange),this.dispatcher.subscribe(nr.playbackTimeDidChange,this.handleTimeChange)},SpanWatcher.prototype.stopMonitor=function(){this.dispatcher.unsubscribe(nr.playbackTimeDidChange,this.handleTimeChange)},SpanWatcher.prototype.handleTimeChange=function(t,n){var l=n.currentPlaybackTime;return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return!Number.isFinite(l)||l<this.start||l>this.stop?(this.inWatchSpan=!1,[2]):this.inWatchSpan?[2]:(this.allowMultiple||this.stopMonitor(),this.inWatchSpan=!0,[4,this.callback(l,this)]);case 1:return t.sent(),[2]}}))}))},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",Promise)],SpanWatcher.prototype,"handleTimeChange",null),SpanWatcher}(),_r=function(t){function RollMonitor(n){var l=t.call(this,n)||this;return l.rollMap=new Map,l}return __extends(RollMonitor,t),RollMonitor.prototype.handlePlaybackThreshold=function(t,n){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(l){return this.rollMap.has(n)?(t=this.rollMap.get(n),this.dispatcher.publish(nr.mediaRollEntered,t),this.rollMap.delete(n),[2]):[2]}))}))},RollMonitor.prototype.shouldMonitor=function(){return!!t.prototype.shouldMonitor.call(this)&&this.getRollMetadata().length>0},RollMonitor.prototype.startMonitor=function(){this.setupWatchers(this.getRollMetadata()),t.prototype.startMonitor.call(this)},RollMonitor.prototype.getRollMetadata=function(){var t=this.playbackController.nowPlayingItem;return void 0===t?[]:parseRollItems(t,["pre-roll","post-roll"])},RollMonitor.prototype.setupWatchers=function(t){var n=this,l=[];t.forEach((function(t){var d=t.start,p=t.duration,h=new gr(n.dispatcher,n.handlePlaybackThreshold,d,d+p);l.push(h),n.rollMap.set(h,t)})),this.watchers=l},RollMonitor}(vr),mr=function(t){function SkipAvailable(n){var l=t.call(this,n)||this;return l.skipMap=new Map,l}return __extends(SkipAvailable,t),SkipAvailable.prototype.handlePlaybackThreshold=function(t,n){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(l){return this.skipMap.has(n)?(t=this.skipMap.get(n),this.dispatcher.publish(nr.mediaSkipAvailable,t),this.skipMap.delete(n),[2]):[2]}))}))},SkipAvailable.prototype.shouldMonitor=function(){return!!t.prototype.shouldMonitor.call(this)&&this.getNowPlayingMetadata().length>0},SkipAvailable.prototype.startMonitor=function(){this.setupWatchers(this.getNowPlayingMetadata()),t.prototype.startMonitor.call(this)},SkipAvailable.prototype.getNowPlayingMetadata=function(){var t=this.playbackController.nowPlayingItem;return void 0===t?[]:this.getSkipMetadata(t)},SkipAvailable.prototype.getSkipMetadata=function(t){var n=parseInt(t.hlsMetadata["skip.count"],10),l=[];if(isNaN(n)||0===n)return l;for(var d=0;d<n;d++)l.push({start:parseFloat(t.hlsMetadata["skip."+d+".start"]),duration:parseFloat(t.hlsMetadata["skip."+d+".duration"]),target:parseFloat(t.hlsMetadata["skip."+d+".target"]),label:t.hlsMetadata["skip."+d+".label"]});return l},SkipAvailable.prototype.setupWatchers=function(t){var n=this,l=[];t.forEach((function(t){var d=t.start,p=t.duration,h=new gr(n.dispatcher,n.handlePlaybackThreshold,d,d+p);l.push(h),n.skipMap.set(h,t)})),this.watchers=l},SkipAvailable}(vr),br=function(t){function UpNextMonitor(n){var l=t.call(this,n)||this,d=l.handlePlaybackThreshold;return l.watchers=[{startMonitor:function(){l.dispatcher.unsubscribe(er.mediaContentComplete,d),l.dispatcher.subscribe(er.mediaContentComplete,d)},stopMonitor:function(){l.dispatcher.unsubscribe(er.mediaContentComplete,d)}}],l}return __extends(UpNextMonitor,t),UpNextMonitor.prototype.handlePlaybackThreshold=function(){var t;return __awaiter(this,void 0,void 0,(function(){var n,l;return __generator(this,(function(d){switch(d.label){case 0:return[4,null===(t=this.apiManager.utsAPI)||void 0===t?void 0:t.watchlistContinueWatching()];case 1:return(n=d.sent())&&n.items&&Array.isArray(n.items)?((l=n.items.find((function(t){var n;return"NextEpisode"===t.context&&(t.isAppleOriginal||(null===(n=t.content)||void 0===n?void 0:n.isAppleOriginal))})))&&this.dispatcher.publish(nr.mediaUpNext,l),[2]):[2]}}))}))},UpNextMonitor.prototype.shouldMonitor=function(){return!!t.prototype.shouldMonitor.call(this)&&(void 0!==this.playbackController.nowPlayingItem&&(n=this.playbackController.nowPlayingItem,!isNaN(getUpNextStart(n))&&!isNaN(getWatchedTime(n))));var n},UpNextMonitor}(vr);(hr=t.PlaybackBitrate||(t.PlaybackBitrate={}))[hr.STANDARD=64]="STANDARD",hr[hr.HIGH=256]="HIGH",(fr=t.PlaybackStates||(t.PlaybackStates={}))[fr.none=0]="none",fr[fr.loading=1]="loading",fr[fr.playing=2]="playing",fr[fr.paused=3]="paused",fr[fr.stopped=4]="stopped",fr[fr.ended=5]="ended",fr[fr.seeking=6]="seeking",fr[fr.waiting=8]="waiting",fr[fr.stalled=9]="stalled",fr[fr.completed=10]="completed",(yr=t.PresentationMode||(t.PresentationMode={}))[yr.pictureinpicture=0]="pictureinpicture",yr[yr.inline=1]="inline";var Pr,typeRequiresItem=function(t){return[er.playbackPlay,er.playbackSkip].includes(t)},itemIsRequired=function(t,n){return void 0!==n&&typeRequiresItem(t)},cleanContainer=function(t){var n=__assign({},t);return delete n.attributes,n},computeContainer=function(t,n){var l,d,p=function(t,n){var l;return itemIsRequired(t,n)&&(null===(l=null==n?void 0:n.container)||void 0===l?void 0:l.name)||null}(t,n),h=itemIsRequired(t,n)?__assign(__assign({},null==n?void 0:n.container),null===(d=null===(l=null==n?void 0:n.container)||void 0===l?void 0:l.attributes)||void 0===d?void 0:d.playParams):null;if(null!==p||null!==h)return{container:cleanContainer(__assign(__assign({},h),null!==p?{name:p}:{}))}},generateItemDescriptorForPAF=function(t,n){var l=__assign(__assign(__assign(__assign({},function(t,n){return typeRequiresItem(t)?void 0===n?{}:__assign({},n.playParams):{}}(t,n)),function(t,n){if(!typeRequiresItem(t)||void 0===n)return{};var l=n.context;return{recoData:(void 0===l?{}:l).reco_id}}(t,n)),function(t,n){if(!typeRequiresItem(t)||void 0===n)return{};var l=n.playbackDuration;return l?{duration:l/1e3}:{}}(t,n)),computeContainer(t,n));return Pt.trace("PAF descriptor",l),l},asCode=function(n){switch(typeof n){case"string":return n;case"undefined":return"undefined";default:return"PlayActivityEndReasonType."+t.PlayActivityEndReasonType[n]}},kr=function(){function PAFTrackerAPI(){}return Object.defineProperty(PAFTrackerAPI.prototype,"apiService",{get:function(){if(void 0===this.service)throw new ke(ke.CONFIGURATION_ERROR,"Play Activity service was called before configuration.");return this.service},enumerable:!0,configurable:!0}),PAFTrackerAPI.prototype.configure=function(t,n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){return this.service=new ht(t.developerToken,t.musicUserToken,t.storefrontCountryCode,{app:{build:ur.app.build,name:ur.app.name,version:ur.app.version},fetch:!_t&&fetch.bind(window),logInfo:Pt.enabled,sourceType:t.sourceType,services:n.services,userIsSubscribed:function(){return t.isAuthorized&&ar.storekit._getIsActiveSubscription.getCachedValue()}}),[2,this]}))}))},PAFTrackerAPI.prototype.cleanup=function(){},PAFTrackerAPI.prototype.shouldConfigure=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,void 0!==t.musicUserToken]}))}))},PAFTrackerAPI.prototype.activate=function(t){return void 0===t&&(t={}),this.apiService.activate(t.flush)},PAFTrackerAPI.prototype.exit=function(t){return void 0===t&&(t={}),Pt.debug("PAF debug","client.exit("+t.position+")"),this.apiService.exit(t.position)},PAFTrackerAPI.prototype.pause=function(t,n){return void 0===n&&(n={}),Pt.debug("PAF debug","client.pause("+n.position+")"),this.apiService.pause(n.position)},PAFTrackerAPI.prototype.play=function(t,n){void 0===n&&(n={});var l=generateItemDescriptorForPAF(er.playbackPlay,t);return Pt.debug("PAF debug","client.play("+JSON.stringify(l)+", "+n.position+")"),this.apiService.play(l,n.position)},PAFTrackerAPI.prototype.scrub=function(t,n){return void 0===n&&(n={}),Pt.debug("PAF debug","client.scrub("+n.position+", "+asCode(n.endReasonType)+")"),this.apiService.scrub(n.position,n.endReasonType)},PAFTrackerAPI.prototype.seek=function(n,l){return void 0===l&&(l={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(d){switch(d.label){case 0:return[4,this.scrub(n,{position:l.startPosition,endReasonType:t.PlayActivityEndReasonType.SCRUB_BEGIN})];case 1:return d.sent(),[4,this.scrub(n,{position:l.position,endReasonType:t.PlayActivityEndReasonType.SCRUB_END})];case 2:return d.sent(),[2]}}))}))},PAFTrackerAPI.prototype.skip=function(t,n){return void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){var l,d;return __generator(this,(function(p){switch(p.label){case 0:l=generateItemDescriptorForPAF(er.playbackSkip,t),Pt.debug("PAF debug","client.skip("+JSON.stringify(l)+", "+asCode(n.direction)+", "+n.position+")"),p.label=1;case 1:return p.trys.push([1,3,,7]),[4,this.apiService.skip(l,n.direction,n.position)];case 2:return p.sent(),[3,7];case 3:return"A play stop() method was called without a previous play() descriptor"!==(d=p.sent()).message?[3,5]:[4,this.play(t,n)];case 4:return p.sent(),[3,6];case 5:return[2,Promise.reject(d)];case 6:return[3,7];case 7:return[2]}}))}))},PAFTrackerAPI.prototype.stop=function(n,l){var d;return void 0===l&&(l={}),(null==n?void 0:n.isLiveRadioStation)&&l.position&&(l.position=l.position-l.startPosition),(null==n?void 0:n.isLiveRadioStation)&&(l.endReasonType=null!==(d=l.endReasonType)&&void 0!==d?d:t.PlayActivityEndReasonType.PLAYBACK_MANUALLY_PAUSED),Pt.debug("PAF debug","client.stop("+l.position+", "+asCode(l.endReasonType)+")"),this.apiService.stop(l.position,l.endReasonType)},PAFTrackerAPI.prototype.shouldTrackPlayActivity=function(n,l){var d=hasAuthorization(),p=!l||l.playbackType!==t.PlaybackType.preview,h=this.alwaysSendForActivityType(n),f=!l||l&&this.mediaRequiresPlayActivity(l);return!(!d||!p||!h&&!f)},PAFTrackerAPI.prototype.alwaysSendForActivityType=function(t){return t===er.playerActivate||t===er.playerExit},PAFTrackerAPI.prototype.mediaRequiresPlayActivity=function(t){return isAUC(t.type)||-1!==["musicVideo","song","radioStation"].indexOf(t.type)},PAFTrackerAPI}(),Tr=[er.playbackPause,er.playbackPlay,er.playbackScrub,er.playbackSeek,er.playbackSkip,er.playbackStop,er.playerActivate,er.playerExit,nr.nowPlayingItemWillChange],Sr=((Pr={})[er.playbackPause]="pause",Pr[er.playbackPlay]="play",Pr[er.playbackScrub]="scrub",Pr[er.playbackSeek]="seek",Pr[er.playbackSkip]="skip",Pr[er.playbackStop]="stop",Pr[er.playerActivate]="activate",Pr[er.playerExit]="exit",Pr),Ar=function(){function PlayActivityService(t,n){this.isBuffering=!1,this.apis=Array.isArray(t)?t:[t],this.dispatcher=n}return PlayActivityService.prototype.cleanup=function(){this.currentItem=void 0,this.teardownWatchers(),this.apis.forEach((function(t){return t.cleanup()}))},PlayActivityService.prototype.configure=function(t,n){return __awaiter(this,void 0,void 0,(function(){var l,d,p,h;return __generator(this,(function(f){switch(f.label){case 0:return[4,Promise.all(this.apis.map((function(n){return n.shouldConfigure(t)})))];case 1:if(l=f.sent(),0===(d=this.apis.filter((function(t,n){return l[n]}))).length)return[2];this.cleanup(),this.instance=t,p=d.map((function(l){return l.configure(t,n)})),f.label=2;case 2:return f.trys.push([2,4,5,6]),[4,Promise.all(p)];case 3:return f.sent(),[3,6];case 4:return h=f.sent(),Pt.error("Error configuring a play activity service",h),[3,6];case 5:return this.setupWatchers(),this.clearIntention(),[7];case 6:return[2]}}))}))},PlayActivityService.prototype.getTrackerByType=function(t){return this.apis.find((function(n){return n instanceof t}))},PlayActivityService.prototype.handleEvent=function(t,n){void 0===n&&(n={});var l=n.item;void 0!==l&&(this.currentItem=l),Pt.debug(t,n);var d=Sr[t];if(void 0!==d){var p=this.addIntention(t,n);switch(delete p.item,t){case er.playbackPause:case er.playbackPlay:case er.playbackScrub:case er.playbackSeek:case er.playbackSkip:case er.playbackStop:return this.callApis(t,d,this.currentItem,p);case er.playerActivate:p.flush="boolean"==typeof n.isPlaying?!n.isPlaying:void 0;case er.playerExit:return this.callApis(t,d,p);case nr.nowPlayingItemWillChange:this.currentItem=l}}},PlayActivityService.prototype.addIntention=function(t,n){var l=__assign({},n);return this.shouldAddIntention(t)?(l=__assign(__assign(__assign({},this.lastUserIntent),this.lastApplicationIntent),l),this.clearIntention(),l):l},PlayActivityService.prototype.callApis=function(t,n){for(var l=[],d=2;d<arguments.length;d++)l[d-2]=arguments[d];return __awaiter(this,void 0,void 0,(function(){var d,p=this;return __generator(this,(function(h){return d=this.apis.map((function(d){if("function"==typeof d[n]&&d.shouldTrackPlayActivity(t,p.currentItem))return d[n].apply(d,__spread(l))})),[2,Promise.all(d)]}))}))},PlayActivityService.prototype.clearIntention=function(){this.lastUserIntent=void 0,this.lastApplicationIntent=void 0},PlayActivityService.prototype.onPlaybackStateChange=function(n,l){return __awaiter(this,void 0,void 0,(function(){var n,d;return __generator(this,(function(p){return n=l.state,d={position:this.instance.currentPlaybackTime},n===t.PlaybackStates.waiting?(this.isBuffering=!0,[2,this.callApis("bufferStart","bufferStart",this.currentItem,d)]):n===t.PlaybackStates.playing&&this.isBuffering?(this.isBuffering=!1,[2,this.callApis("bufferEnd","bufferEnd",this.currentItem,d)]):[2]}))}))},PlayActivityService.prototype.recordApplicationIntent=function(t,n){this.lastApplicationIntent=n},PlayActivityService.prototype.recordUserIntent=function(t,n){this.lastUserIntent=n},PlayActivityService.prototype.shouldAddIntention=function(t){return[er.playbackPause,er.playbackStop].includes(t)},PlayActivityService.prototype.setupWatchers=function(){var t=this;Tr.forEach((function(n){t.dispatcher.subscribe(n,t.handleEvent)})),this.dispatcher.subscribe(er.userActivityIntent,this.recordUserIntent),this.dispatcher.subscribe(er.applicationActivityIntent,this.recordApplicationIntent),this.dispatcher.subscribe(nr.playbackStateDidChange,this.onPlaybackStateChange)},PlayActivityService.prototype.teardownWatchers=function(){var t=this;Tr.forEach((function(n){t.dispatcher.unsubscribe(n,t.handleEvent)})),this.dispatcher.unsubscribe(er.userActivityIntent,this.recordUserIntent),this.dispatcher.unsubscribe(er.applicationActivityIntent,this.recordApplicationIntent),this.dispatcher.unsubscribe(nr.playbackStateDidChange,this.onPlaybackStateChange)},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[String,Object]),__metadata("design:returntype",void 0)],PlayActivityService.prototype,"handleEvent",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",Promise)],PlayActivityService.prototype,"onPlaybackStateChange",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],PlayActivityService.prototype,"recordApplicationIntent",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],PlayActivityService.prototype,"recordUserIntent",null),PlayActivityService}(),wr={setDelegate:!0};function isDefinedNonNull(t){return function(t){return void 0!==t}(t)&&null!==t}function isFunction(t){return"function"==typeof t}function isNumber(t){return"number"==typeof t}function isInteger(t){return isNumber(t)&&t%1==0}function isArray(t){return t&&t.constructor===Array}function extend(t){var n=[!0,!0,!0].concat(Array.prototype.slice.call(arguments));return copyKeysAndValues.apply(null,n)}function copyKeysAndValues(t,n,l,d){for(var p,h=l&&d||{},f=3;f<arguments.length;f++)for(var y in p=arguments[f])if(Object.prototype.hasOwnProperty.call(p,y)){var v=p[y];(t||null!=v)&&(n||"function"!=typeof v)&&(h[y]=v)}return h}function attachDelegate(t,n){var l=!1;if(t&&n&&t!==n){var d={};Object.keys(n).forEach((function(n){t[n]||(d[n]=!0)})),extend(d,wr),l=attachMethods(t,n,null,d)}return l}function attachMethods(t,n,l,d){var p=!1;if(t&&n){d=d||{},l=l||n;var captureFunction=function(t,n,l,d){var returnValue=function(){return l[d].apply(t,arguments)};return n&&(returnValue.origFunction=n),returnValue};for(var h in n)if(!(h in d)&&n[h]&&isFunction(n[h])){var f=t[h],y=f&&isFunction(f)?f.bind(t):null;t[h]=captureFunction(l,y,n,h),p=!0}}return p}function setDelegates(t,n){var l={};for(var d in t)n[d]&&isFunction(t[d].setDelegate)&&(l[d]=t[d].setDelegate(n[d]));return l}function exceptionString(t,n){return"The function "+t+"."+n+"() must be overridden with a platform-specific delegate function.If you have no data for this function, have your delegate return null or undefined (no 'return')"}var Ir={flagArguments:{INCLUDE_CALL_STACK:new function(){},MIRROR_TO_SERVER:new function(){},SUPPRESS_CLIENT_OUTPUT:new function(){}},setDelegate:function(t){return attachDelegate(this,t)},execute:function(t,n,l){var d=t.levelStringToIntMap[n];if(t.level()!==t.NONE&&t.level()<=d){var p=Array.prototype.slice.call(l),h=Ir.nonFlagLogArguments(p),f=Ir.logOptions(t,d,p),y=f.includeCallStack?(new Error).stack:null,v=y?h.concat("\n"+y):h;if(t[n]._lastLog=v,f.mirrorToServer&&Ir.sendToServer(t,n,h,y),f.throwInsteadOfPrint)throw new Error(h.toString());f.suppressClientOutput||(console[n]?console[n].apply(console,v):console.log.apply(console,v))}},isFlagObject:function(t){return t&&t===Ir.flagArguments[t.constructor.name]},nonFlagLogArguments:function(t){return t.filter((function(t){return!Ir.isFlagObject(t)}))},logOptions:function(t,n,l){var d,p={};return l.forEach((function(t){Ir.isFlagObject(t)&&(d=function(t,n){var l="";if(t)for(var d,p=t.toLowerCase().split("_"),h=0;h<p.length;h++)d=p[h][0],(0!==h||n)&&(d=d.toUpperCase()),l+=d+p[h].slice(1);return l}(t.constructor.name),p[d]=!0)})),isFunction(t.mirrorToServerLevel)&&t.mirrorToServerLevel()!==t.NONE&&t.mirrorToServerLevel()<=n&&(p.mirrorToServer=!0),t.throwLevel()!==t.NONE&&t.throwLevel()<=n&&(p.throwInsteadOfPrint=!0),p},sendToServer:function(t,n,l,d){}},Er={MIN_LEVEL:0,NONE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,MAX_LEVEL:4,levelIntToStringMap:{0:"none",1:"debug",2:"info",3:"warn",4:"error"},levelStringToIntMap:{none:0,debug:1,info:2,warn:3,error:4}},Rr={loggerName:"defaultLogger",level:Er.INFO,throwLevel:Er.NONE},Or=!1,Cr={};function Logger$1(t){this._loggerName=t,this._level,this._throwLevel,Or||(Or=!0,extend(Logger$1.prototype,Er),extend(Logger$1.prototype,Ir.flagArguments))}function loggerNamed(t){var n=Cr[t=t||Rr.loggerName];return n||(n=new Logger$1(t),Cr[t]=n),n}Logger$1.level=function(){return Rr.level},Logger$1.throwLevel=function(){return Rr.throwLevel},Logger$1.prototype.setDelegate=function(t){return attachDelegate(this,t)},Logger$1.prototype.loggerName=function(){return this._loggerName},Logger$1.prototype.levelParameterAsInt=function(t){var n,l,d=null;return"string"==typeof(l=t)||l instanceof String?n=this.levelStringToIntMap[t.toLowerCase()]:isNumber(t)&&(n=t),n>=this.MIN_LEVEL&&n<=this.MAX_LEVEL&&(d=n),d},Logger$1.prototype.setLevel=function(t){var n=this.levelParameterAsInt(t);null!==n&&(this._level=n)},Logger$1.prototype.setThrowLevel=function(t){var n=this.levelParameterAsInt(t);null!==n&&(this._throwLevel=n)},Logger$1.prototype.level=function(){var t=this._level;return isNumber(t)?t:Logger$1.level()},Logger$1.prototype.levelString=function(){return this.levelIntToStringMap[this.level()]},Logger$1.prototype.throwLevel=function(){var t=this._throwLevel;return isNumber(t)?t:Logger$1.throwLevel()},Logger$1.prototype.debug=function(){Ir.execute(this,"debug",arguments)},Logger$1.prototype.info=function(){Ir.execute(this,"info",arguments)},Logger$1.prototype.warn=function(){Ir.execute(this,"warn",arguments)},Logger$1.prototype.error=function(){Ir.execute(this,"error",arguments)},Logger$1.prototype.lastLog=function(t){return this[t]?this[t]._lastLog:null};var Mr={LOCAL_STORAGE:"localStorage",SESSION_STORAGE:"sessionStorage"},_storageObject=function(t){var n=null,l=!1;return function(){return t?n=t:(l||(console.error("storageObject: storage object not found. Override this function if there is a platform-specific implementation"),l=!0),n||(n={storage:{},getItem:function(t){return this.storage[t]},setItem:function(t,n){this.storage[t]=n},removeItem:function(t){delete this.storage[t]}})),n}};function _defaultStorageObject(t){var n=null,l=t===Mr.LOCAL_STORAGE;try{n="undefined"!==(l?typeof localStorage:typeof sessionStorage)?l?localStorage:sessionStorage:null}catch(e){n=null,console.error("_utils.storage._defaultStorageObject: Unable to retrieve storage object: "+e)}return n}var Dr=_storageObject(_defaultStorageObject(Mr.LOCAL_STORAGE)),Lr=_storageObject(_defaultStorageObject(Mr.SESSION_STORAGE));function saveObjectToStorage(t,n,l){var d=null;if(l)try{t.setItem(n,JSON.stringify(l)),d=l}catch(e){}else d=t.removeItem(n);return d}function objectFromStorage(t,n){var l=null,d=t.getItem(n);if(d)try{l=JSON.parse(d)}catch(e){l=void 0}return l}var Nr={maxWait:1500,initialDelay:100,factor:2},ExponentialStrategy=function(t,n,l){this.delay=t||Nr.initialDelay,this.maxWait=isNumber(n)?n:Nr.maxWait,this.factor=l||Nr.factor,this.timeWaited=0};function exponentialBackoff(t,n,l,d,p,h){!function _backoff(t,n,l,d){n.call(n,l,(function(){var p=t.nextDelay();p?setTimeout(_backoff.bind(null,t,n,l,d),p):d.apply(d,arguments)}))}(new ExponentialStrategy(d,p,h),t,n,l)}function _valueForKeyPath(t,n,l){var d=n;if(t&&n)for(var p=t.split("."),h=0;d&&h<p.length;h++){var f=p[h];!(f in d)&&l&&(d[f]={}),d=f in d?d[f]:null}return d}function valueForKeyPath(t){var n=null;if(t&&arguments.length>1)for(var l=sourcesArray(Array.prototype.slice.call(arguments,1)),d=l.length-1;d>=0;d--){var p=l[d];if(isDefinedNonNull(n=_valueForKeyPath(t,p)))break}return n}function sourcesArray(t){var n=[],l=[];l=l.concat(t),arguments&&arguments.length>1&&(l=l.concat(Array.prototype.slice.call(arguments,1)));for(var d=0;d<l.length;d++){var p=l[d];n=n.concat(p)}return n}function makeAjaxRequest(t,n,l,d,p,h){var f=new XMLHttpRequest;l=l||void 0,h=h||{},d=isFunction(d)?d:function(){},p=isFunction(p)?p:function(){};var y=!1!==h.async;h.timeout&&y&&(f.timeout=h.timeout),f.onload=function(){f.status>=200&&f.status<300?d(f.response):p(new Error("XHR error: server responded with status "+f.status+" "+f.statusText),f.status)},f.onerror=function(){p(new Error("XHR error"))},f.open(n,t,y),f.withCredentials=!0,f.setRequestHeader("Content-type","application/json"),f.send(l)}ExponentialStrategy.prototype.nextDelay=function(){var t=null,n=this.maxWait-this.timeWaited;return n>0&&(this.delay=Math.min(this.delay,n),this.timeWaited+=this.delay),(0===this.maxWait||n>0)&&(t=this.delay,this.delay=this.delay*this.factor),t};var xr={setDelegate:function(t){return attachDelegate(this,t)},localStorageObject:Dr,sessionStorageObject:Lr},Ur={setDelegate:function(t){return attachDelegate(this,t)},makeAjaxRequest:makeAjaxRequest},Br={blacklistedFields:["capacitySystem","capacitySystemAvailable","capacityDisk","capacityData","capacityDataAvailable"],compoundSeparator:"_",configBaseUrl:"https://xp.apple.com/config/1/report",constraints:{profiles:{AMPWeb:{precedenceOrderedRules:[{filters:"any",fieldConstraints:{clientId:{generateValue:!0,namespace:"AMPWeb_isSignedOut",expirationPeriod:864e5}}},{filters:{valueMatches:{isSignedIn:[!0]}},fieldConstraints:{clientId:{generateValue:!0,namespace:"AMPWeb_isSignedIn",expirationPeriod:15552e6}}}]},strict:{precedenceOrderedRules:[{filters:"any",fieldConstraints:{clientId:{generateValue:!0,scopeFieldName:"parentPageUrl",scopeStrategy:"mainDomain",expirationPeriod:864e5},consumerId:{blacklisted:!0},dsId:{blacklisted:!0},parentPageUrl:{scope:"hostname"}}},{filters:{valueMatches:{eventType:["click"],actionType:["signUp"]}},fieldConstraints:{parentPageUrl:{scope:"fullWithoutParams"}}},{filters:{valueMatches:{eventType:["dialog"],dialogType:["upsell"],result:["upsell"]}},fieldConstraints:{parentPageUrl:{scope:"fullWithoutParams"}}},{filters:{valueMatches:{userType:["signedIn"]}},fieldConstraints:{clientId:{scopeStrategy:"all"}}},{filters:{valueMatches:{userType:["signedIn"],eventType:["click","dialog","media","search"]}},fieldConstraints:{clientId:{blacklisted:!0},consumerId:{blacklisted:!1},dsId:{blacklisted:!1}}},{filters:{valueMatches:{userType:["signedIn"],eventType:["page","impressions"]},nonEmptyFields:["pageHistory"]},fieldConstraints:{clientId:{blacklisted:!0},consumerId:{blacklisted:!1},dsId:{blacklisted:!1}}}]}}},fieldsMap:{cookies:["itcCt","itscc"],custom:{impressions:["id","adamId","link.type","station-hash"],location:["id","adamId","dataSetId","name","fcKind","kindIds","type","link.type","station-hash","core-seed-name"]},single:{targetId:["id","adamId","contentId","type","link.type","fcId","userPreference","label","station-hash","linkIdentifier"]}},metricsUrl:"https://xp.apple.com/report",postFrequency:6e4,postFrequencyLowLatency:5e3,tokenSeparator:"|"},jr={},_appendSectionAndSubsectionToConfigSources=function(t,n,l){if(l){t.push(l);var d=l[n];d&&function(t){for(var n in t)if(t.hasOwnProperty(n))return!0}(d)&&t.push(d)}},Config=function(t){this._topic=t,this._debugSource=null,this._cachedSource=null,this._serviceSource=null,this._initCalled=!1,this._initialized=!1,this._showedDebugWarning=!1,this._showedNoProvidedSourceWarning=!1,this._keyPathsThatSuppressWarning={configBaseUrl:!0},this.DEBUG_SOURCE_KEY="mtClientConfig_debugSource"+Br.compoundSeparator+this._topic,this.CACHED_SOURCE_KEY="mtClientConfig_cachedSource"+Br.compoundSeparator+this._topic};function disabled(t){return!!this.value("disabled",t)}function blacklistedEvents(t){return this.value("blacklistedEvents",t)||[]}function blacklistedFields(t){return this.value("blacklistedFields",t)||[]}function removeBlacklistedFields(t,n){if(t)for(var l=blacklistedFields.call(this,n),d=0;d<l.length;d++){var p=l[d];p&&p in t&&delete t[p]}return t}function metricsDisabledOrBlacklistedEvent(t,n){return disabled.call(this,n)||!!t&&blacklistedEvents.call(this,n).indexOf(t)>-1}Config.createConfig=function(t,n,l,d){var p=Config.getConfig(t);return t&&"noTopicConfig"!==t&&!p._initCalled&&p.init(n,l,d),p},Config.getConfig=function(t){var n=jr[t=t||"noTopicConfig"];return n||(n=new Config(t),jr[t]=n),n},Config.defaultConfig=function(){return Config.getConfig()},Config.value=function(t,n){var l=n&&jr[n]||Config.defaultConfig();return l.value.call(l,t)},Config.environment=xr,Config.logger=loggerNamed("mt-client-config"),Config.network=Ur,Config.prototype._defaults=function(){return Br},Config.prototype._setInitialized=function(t){this._initialized=t},Config.prototype._setInitCalled=function(t){this._initCalled=t},Config.prototype._setShowedDebugWarning=function(t){this._showedDebugWarning=t},Config.prototype._setShowedNoProvidedSourceWarning=function(t){this._showedNoProvidedSourceWarning=t},Config.prototype.setDelegate=function(t){return attachDelegate(this,t)},Config.prototype.topic=function(){return this._topic},Config.prototype.configHostname=function(){},Config.prototype.configUrl=function(){var t,n=this.configHostname();return t=n?"https://"+n+"/config/1/report":this.value("configBaseUrl"),"noTopicConfig"!==this._topic?t+="/"+this.topic():Config.logger.error("config.configUrl(): Topic must be provided"),t},Config.prototype.sources=function(){},Config.prototype.value=function(t){var n,l=this.cachedSource(),d=this.serviceSource(),p=this.sources(),h=this.debugSource(),f=l||d||p||h;return p||d||t in this._keyPathsThatSuppressWarning||this._showedNoProvidedSourceWarning||(this._showedNoProvidedSourceWarning=!0,Config.logger.warn("Metrics config: No config provided via delegate or fetched via init(), using default/cached config values.")),h&&(this._showedDebugWarning||(this._showedDebugWarning=!0,Config.logger.warn('"debugSource" found.\nThis will override any same-named client-supplied configSource fields.\nThis setting "sticks" across session, use "setDebugSource(null)" to clear'))),isArray(p)||(p=[p]),n=0===t.indexOf("blacklisted")?f?[l,d,p,h]:[Br]:[Br,l,d,p,h],n=this.configSourcesWithOverrides(n,this.topic()),valueForKeyPath.apply(null,[t].concat(n))},Config.prototype.configSourcesWithOverrides=function(t,n){var l=t;if(t&&t.length&&n){l=[];for(var d=0;d<t.length;d++){var p=t[d];if(p)if(isArray(p)&&p.length){for(var h=[],f=0;f<p.length;f++)_appendSectionAndSubsectionToConfigSources(h,n,p[f]);l.push(h)}else _appendSectionAndSubsectionToConfigSources(l,n,p)}}return l},Config.prototype.setDebugSource=function(t){return this._debugSource=t||null,saveObjectToStorage(xr.localStorageObject(),this.DEBUG_SOURCE_KEY,this._debugSource)},Config.prototype.debugSource=function(){return this._debugSource||(this._debugSource=objectFromStorage(xr.localStorageObject(),this.DEBUG_SOURCE_KEY)),this._debugSource},Config.prototype.setCachedSource=function(t){return this._cachedSource=t||null,saveObjectToStorage(xr.localStorageObject(),this.CACHED_SOURCE_KEY,this._cachedSource)},Config.prototype.cachedSource=function(){return this._cachedSource||(this._cachedSource=objectFromStorage(xr.localStorageObject(),this.CACHED_SOURCE_KEY)),this._cachedSource},Config.prototype.setServiceSource=function(t){return this._serviceSource=t,this._serviceSource},Config.prototype.serviceSource=function(){return this._serviceSource},Config.prototype.fetchConfig=function(t,n,l){l=l||function(){};exponentialBackoff(Ur.makeAjaxRequest.bind(Ur,t,"GET",null),(function(t){var d;try{t=JSON.parse(t),d=!0}catch(e){l.call(l,e)}d&&n&&n.call(n,t)}),l)},Config.prototype.init=function(t,n,l){if(!this._initCalled){this._initCalled=!0,n=n||function(){};var d=function(){this._initialized=!0,n.call(n)}.bind(this);if(t)this.setDelegate({sources:t}),d();else{this.setCachedSource(this.cachedSource());var p=this.configUrl(),h=function(t){this.setCachedSource(t),this.setServiceSource(t),d()}.bind(this);this.fetchConfig(p,h,l)}}},Config.prototype.initialize=function(t,n,l){return this.init.apply(this,Array.prototype.slice.call(arguments))},Config.prototype.initialized=function(){return this._initialized};function recordEvent(t,n,l){var d=null;return l&&!metricsDisabledOrBlacklistedEvent.call(Config,l.eventType,n)&&(removeBlacklistedFields.call(Config,l,n),t.apply(null,Array.prototype.slice.call(arguments,1)),d=l),d}var Fr=1e4,Kr="events",Vr="1.0",$r=2;function enrichAndSerializeEvents(t){var n=null;if(t&&t.length){var l={};l.deliveryVersion=Vr,l.postTime=Date.now(),l[Kr]=t;try{n=JSON.stringify(l)}catch(e){loggerNamed("mt-event-queue").error("Error stringifying events as JSON: "+e)}}return n}function _immediateRecordEvent(t,n){var l=enrichAndSerializeEvents([n]);l&&makeAjaxRequest(function(t){return Config.value("metricsUrl",t)+"/"+$r+"/"+t}(t),"POST",l,null,null,{timeout:function(t){var n=Config.value("requestTimeout",t)||Fr;return n=Math.min(n,Config.value("postFrequency",t))}(t)})}var Hr,zr,Wr,Yr={recordEvent:function(t,n){return recordEvent.apply(null,[_immediateRecordEvent].concat(Array.prototype.slice.call(arguments)))},sendMethod:function(){return"javascript"}},qr={_document:function(){if("undefined"!=typeof document)return document;throw"metricskit-delegates-html.environment HTML delegate 'document' object not found"},_window:function(){if("undefined"!=typeof window)return window;throw"metricskit-delegates-html.environment HTML delegate 'window' object not found"},cookie:function(){return qr._window().document.cookie},pageUrl:function(){return qr._window().location.href},parentPageUrl:function(){var t,n=qr._window(),l=n.parent;if(l!==n)try{t=l.location.href}catch(e){t=qr._document().referrer}return t},pixelRatio:function(){return qr._window().devicePixelRatio},screenHeight:function(){return qr._window().screen.height},screenWidth:function(){return qr._window().screen.width},userAgent:function(){return qr._window().navigator.userAgent},windowInnerHeight:function(){return qr._window().innerHeight},windowInnerWidth:function(){return qr._window().innerWidth},windowOuterHeight:function(){return qr._window().outerHeight},windowOuterWidth:function(){return qr._window().outerWidth},timeOriginOffset:function(){var t=null,n=qr._window().performance;return n&&n.timing&&(t=n.timing.navigationStart),t},app:function(){},appVersion:function(){},capacityData:function(){},capacityDataAvailable:function(){},capacityDisk:function(){},capacitySystem:function(){},capacitySystemAvailable:function(){},connectionType:function(){},dsId:function(){},hardwareBrand:function(){},hardwareFamily:function(){},hardwareModel:function(){},hostApp:function(){},hostAppVersion:function(){},os:function(){},osBuildNumber:function(){},osLanguages:function(){},osVersion:function(){},resourceRevNum:function(){},storeFrontCountryCode:function(){},storeFrontHeader:function(){},userType:function(){}};function mergeAndCleanEventFields(t){for(var n=[!1,!1,!1].concat(Array.prototype.slice.call(arguments)),l=[],d=0;d<n.length;d++){var p=n[d];if(p&&p.constructor===Array)for(var h=0;h<p.length;h++)l.push(p[h]);else l.push(p)}return copyKeysAndValues.apply(null,l)}function processMetricsData(t,n,l,d){var p=mergeAndCleanEventFields(d),h=p;if(t&&n){var f={};if(l||(n=n.filter((function(t){return t in p}))),n.length)for(var y=0;y<n.length;y++){var v=n[y],g=t[v];isFunction(g)&&(f[v]=g.call(t,p))}h=mergeAndCleanEventFields(h,f)}return h}function applyFieldsMap(t,n,l,d){var p,h,f,y;if(t&&n&&l){var v,g;if(h={},p=valueForKeyPath(n,l,l.custom))if(isArray(p))for(v=0;v<p.length;++v)isDefinedNonNull(g=t[p[v]])&&(h[p[v]]=g);else if((y=p)&&y.constructor===Object){for(var _ in p)for(v=0;v<p[_].length;++v)if(isDefinedNonNull(g=valueForKeyPath(p[_][v],t))){h[_]=g;break}}else f="metrics: incorrect data type provided to applyFieldsMap (only accepts objects and Arrays)";else f="metrics: unable to get "+n+" section from fieldsMap"}else{var m=[];t||m.push("data"),n||m.push("sectionName"),l||m.push("fieldsMap"),f="metrics: missing argument(s): "+m.join(",")+" not provided to applyFieldsMap"}return f&&isFunction(d)&&d(f),h}function environmentBaseFieldNames(){return zr||(zr=["app","appVersion","hardwareFamily","hardwareModel","os","osBuildNumber","osLanguages","osVersion","resourceRevNum","screenHeight","screenWidth","userAgent"].concat(["delegateApp","hardwareBrand","storeFrontCountryCode","storeFrontHeader"])),zr}function Base(t){this.setDelegate({topic:t}),Wr||(Wr=!0,environmentBaseFieldNames().forEach(function(t){Base.prototype[t]=function(n){return n&&n.hasOwnProperty(t)?n[t]:this.environment()[t]()}.bind(this)}.bind(this)))}Base._className="eventHandlers.base",Base.prototype.setDelegate=function(t){return attachDelegate(this,t)},Base.prototype.topic=function(){throw exceptionString(Base._className,"topic")},Base.prototype.environment=function(){throw exceptionString(Base._className,"environment")},Base.prototype.eventRecorder=function(){throw exceptionString(Base._className,"eventRecorder")},Base.prototype.metricsData=function(){throw exceptionString(Base._className,"metricsData")},Base.prototype.processMetricsData=function(){throw exceptionString(Base._className,"processMetricsData")},Base.prototype.knownFields=function(){return Hr||(Hr=environmentBaseFieldNames().concat(["baseVersion","clientEventId","connection","eventTime","eventType","eventVersion","timezoneOffset","xpPostFrequency","xpSendMethod"])),Hr},Base.prototype.baseVersion=function(){return 1},Base.prototype.clientEventId=function(t){return t&&t.clientEventId||function(t){var l;if(16777215==Math.floor(4294967295/256)){var d,p,h,f,y,v=n.crypto||n.msCrypto;if(v&&v.getRandomValues)d=v.getRandomValues(new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT)),y=!0;else if(v&&v.randomBytes){var g=v.randomBytes(16);d=new Uint32Array(g.buffer,g.byteOffset,g.byteLength/Uint32Array.BYTES_PER_ELEMENT),y=!0}else for(d=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),p=0;p<d.length;p++)d[p]=Math.floor(Math.random()*Math.floor(4294967295));if(d){for(l="",p=0;p<d.length;p++)for(f=d[p],h=0;h<6;h++)l+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[f%62],f=Math.floor(f/62);t&&(l="1_"+(y?"1":"2")+"_"+l)}}return l}(!0)},Base.prototype.connection=function(t){return t&&t.connection||this.environment().connectionType()},Base.prototype.dsId=function(t){return t&&t.dsId||this.environment().dsId()},Base.prototype.eventTime=function(t){return t&&t.eventTime||Date.now()},Base.prototype.eventVersion=function(t){return t&&t.eventVersion||null},Base.prototype.timezoneOffset=function(t){return t&&t.timezoneOffset||(new Date).getTimezoneOffset()},Base.prototype.xpPostFrequency=function(t){return t&&t.xpPostFrequency||Config.value("postFrequency",this.topic())},Base.prototype.xpSendMethod=function(t){return t&&t.xpSendMethod||this.eventRecorder().sendMethod()};var Gr=Base;function MetricsData(){this._eventData={}}MetricsData.prototype.updateData=function(){extend.apply(null,[this._eventData].concat(Array.prototype.slice.call(arguments)))};var Qr,Jr,Xr=MetricsData;function Environment(){Qr||(Qr=!0,["app","appVersion","hardwareFamily","hardwareModel","os","osBuildNumber","osLanguages","osVersion","resourceRevNum","screenHeight","screenWidth","userAgent"].forEach((function(t){Environment.prototype[t]=function(){throw exceptionString(Environment._className,t)}})),["delegateApp","hardwareBrand","storeFrontCountryCode","storeFrontHeader"].forEach((function(t){Environment.prototype[t]=function(){}})))}function topic(){return Jr}Environment._className="system.environment",Environment.prototype.setDelegate=function(t){return attachDelegate(this,t)},Environment.prototype.connectionType=function(){throw exceptionString(Environment._className,"connectionType")},Environment.prototype.dsId=function(){},Environment.prototype.localStorageObject=Dr,Environment.prototype.sessionStorageObject=Lr;var Zr="unknown",ei="next",ti="previous",ri="location",ii="interval",ni="playhead",oi="scrub",ai="transition",si="interruption",ui="buffering",ci="play",li="seek",di="skipIntro",pi="actionType",hi="consumerId",fi="consumerNs",yi="dsId",vi="eventType",gi="eventVersion",_i="isOffline",mi="videoViewportHeight",bi="videoViewportWidth",Pi={TYPE:{MANUAL:"manual",AUTOMATIC:"automatic",UNKNOWN:Zr},PLAY_START_REASON:{PLAY:ci,UNPAUSE:"unpause",NEXT:ei,PREVIOUS:ti,SEEK:li,TRANSITION:ai,INTERRUPTION:si,FOREGROUND:"foreground",FOCUS:"focus",BUFFERING:ui,UNKNOWN:Zr},PLAY_START_REASON_TYPE:{SKIP_INTRO:di},PLAY_STOP_REASON:{COMPLETE:"complete",TRANSITION:ai,PLAY_OTHER:"playOther",PAUSE:"pause",SEEK:li,NEXT:ei,INTERRUPTION:si,BACKGROUND:"background",EXIT:"exit",INACTIVITY:"inactivity",BUFFERING:ui,ERROR:"error",FAILURE:"failure",UNKNOWN:Zr,CLOSE_PLAYER:"closePlayer"},PLAY_STOP_REASON_TYPE:{SKIP_INTRO:di},SEEK_START_REASON:{NEXT:ei,PREVIOUS:ti,LOCATION:ri,INTERVAL:ii,PLAYHEAD:ni,SCRUB:oi,UNKNOWN:Zr,SKIP_INTRO:di},SEEK_STOP_REASON:{NEXT:ei,PREVIOUS:ti,LOCATION:ri,INTERVAL:ii,PLAYHEAD:ni,SCRUB:oi,UNKNOWN:Zr,SKIP_INTRO:di}},ki={ACTIVITY_TYPE:{PLAY:ci,SEEK:li},ACTION_TYPE:{START:"start",STOP:"stop"},EVENT_TYPE:{PLAY_ACTIVITY:"playActivity",SEEK_ACTIVITY:"seekActivity"}},Ti={INCLUDES_START_POSITIONS:"includesStartPositions",INCLUDES_END_POSITIONS:"includesEndPositions"};function VPAFKitEnvironment(){Environment.apply(this,arguments)}VPAFKitEnvironment.prototype=new Environment,VPAFKitEnvironment.prototype.constructor=VPAFKitEnvironment,VPAFKitEnvironment.prototype.consumerId=function(){},VPAFKitEnvironment.prototype.consumerNs=function(){},VPAFKitEnvironment.prototype.isOffline=function(){},VPAFKitEnvironment.prototype.videoViewportHeight=function(){},VPAFKitEnvironment.prototype.videoViewportWidth=function(){};var Si={setDelegate:function(t){return attachDelegate(this,t)},recordEvent:function(t,n){throw exceptionString("system.eventRecorder","recordEvent")},sendMethod:function(){throw exceptionString("system.eventRecorder","sendMethod")},flushUnreportedEvents:function(t){}},Ai={};Ai.environment=new VPAFKitEnvironment,Ai.eventRecorder=Si,Ai.logger=loggerNamed("mt-vpafkit");var wi=Gr,VPAFKitBase=function(){wi.apply(this,arguments)};(VPAFKitBase.prototype=new wi).constructor=VPAFKitBase,VPAFKitBase.prototype.environment=function(){return Ai.environment},VPAFKitBase.prototype.eventRecorder=function(){return Ai.eventRecorder},VPAFKitBase.prototype.knownFields=function(){var t=wi.prototype.knownFields().concat([pi,hi,fi,yi,_i,mi,bi]);return t},VPAFKitBase.prototype.consumerId=function(t){var n=hi;return t&&n in t?t[n]:this.environment().consumerId()},VPAFKitBase.prototype.consumerNs=function(t){var n=fi;return t&&n in t?t[n]:this.environment().consumerNs()},VPAFKitBase.prototype.isOffline=function(t){var n=_i;return t&&n in t?t[n]:this.environment().isOffline()},VPAFKitBase.prototype.videoViewportHeight=function(t){var n=mi;return t&&n in t?t[n]:this.environment().videoViewportHeight()},VPAFKitBase.prototype.videoViewportWidth=function(t){var n=bi;return t&&n in t?t[n]:this.environment().videoViewportWidth()};var Ii=new VPAFKitBase((function(){return topic()}));Ii.metricsData=function(){return Ii.processMetricsData.apply(Ii,[null].concat(Array.prototype.slice.call(arguments)))},Ii.processMetricsData=function(t){var n=null;if(!Config.metricsDisabledOrBlacklistedEvent(t,topic())){var l=Array.prototype.slice.call(arguments,1);if(this!==Ii){var d=Ii.metricsData.apply(Ii,l);l=[d].concat(l)}n=processMetricsData(this,this.knownFields(),!0,l)}return Config.removeBlacklistedFields(n,topic()),n};var MediaActivity=function(t,n){this._defaultEventType=t,this._reasonConstants=n,this._defaultActionType};extend(MediaActivity,ki),Object.defineProperties(MediaActivity.prototype,{TYPE:{get:function(){return Pi.TYPE}},REASON:{get:function(){return this._reasonConstants}}}),MediaActivity.prototype.setDelegate=function(t){return attachDelegate(this,t)},MediaActivity.prototype.knownFields=function(){var t=[pi,vi,gi];return t},MediaActivity.prototype.eventType=function(t){return this._defaultEventType},MediaActivity.prototype.eventVersion=function(t){var n=Ii.eventVersion(t);return null!==n?n:1},MediaActivity.prototype.actionType=function(t){return this._defaultActionType};var StartMediaActivity=function(t,n){MediaActivity.apply(this,arguments),this._defaultActionType=MediaActivity.ACTION_TYPE.START};(StartMediaActivity.prototype=new MediaActivity).constructor=StartMediaActivity,StartMediaActivity.prototype.metricsData=function(t,n,l,d){var p=this.eventType(),h={position:t,overallPosition:n,startType:l,startReason:d},f=Array.prototype.slice.call(arguments,4);return Ii.processMetricsData.apply(this,[p,h].concat(f))};var StopMediaActivity=function(t,n){MediaActivity.apply(this,arguments),this._defaultActionType=MediaActivity.ACTION_TYPE.STOP};(StopMediaActivity.prototype=new MediaActivity).constructor=StopMediaActivity,StopMediaActivity.prototype.metricsData=function(t,n,l,d,p){var h=this.eventType(),f={position:t,overallPosition:n,stopType:l,stopReason:d,startPosition:(p=p||{}).position,startOverallPosition:p.overallPosition,startTime:p.eventTime,startType:p.startType,startReason:p.startReason,startReasonType:p.startReasonType};h===MediaActivity.EVENT_TYPE.SEEK_ACTIVITY&&(f.startAssetId=p.assetId);var y=Array.prototype.slice.call(arguments,5);return Ii.processMetricsData.apply(this,[h,f].concat(y))};var Ei=new StartMediaActivity(MediaActivity.EVENT_TYPE.PLAY_ACTIVITY,Pi.PLAY_START_REASON),Ri=new StopMediaActivity(MediaActivity.EVENT_TYPE.PLAY_ACTIVITY,Pi.PLAY_STOP_REASON),Oi=new StartMediaActivity(MediaActivity.EVENT_TYPE.SEEK_ACTIVITY,Pi.SEEK_START_REASON),Ci=new StopMediaActivity(MediaActivity.EVENT_TYPE.SEEK_ACTIVITY,Pi.SEEK_STOP_REASON),Mi=Object.freeze({__proto__:null,base:Ii,playStart:Ei,playStop:Ri,seekStart:Oi,seekStop:Ci}),MediaActivity$1=function(t){this._activityType=t,this._startMetricsData=null,this._isStopped=!1};MediaActivity$1.ACTIVITY_TYPE=ki.ACTIVITY_TYPE,Object.defineProperties(MediaActivity$1.prototype,{isStopped:{get:function(){return this._isStopped}},type:{get:function(){return this._activityType}},startOverallPosition:{get:function(){return this._startMetricsData?this._startMetricsData.overallPosition:null}}}),extend(MediaActivity$1.prototype,Pi),MediaActivity$1.prototype.started=function(t,n,l,d){var p=this._startEventHandler();p&&(this._startMetricsData=p.metricsData.apply(p,arguments),this.type!=MediaActivity$1.ACTIVITY_TYPE.SEEK&&Si.recordEvent(topic(),this._startMetricsData))},MediaActivity$1.prototype.stopped=function(t,n,l,d){var p=this._stopEventHandler();if(p){this._isStopped=!0;var h=[t,n,l,d,this._startMetricsData].concat(Array.prototype.slice.call(arguments,4)),f=p.metricsData.apply(p,h);Si.recordEvent(topic(),f)}},MediaActivity$1.prototype._startEventHandler=function(){var t;switch(this.type){case MediaActivity$1.ACTIVITY_TYPE.PLAY:t=Ei;break;case MediaActivity$1.ACTIVITY_TYPE.SEEK:t=Oi}return t},MediaActivity$1.prototype._stopEventHandler=function(){var t;switch(this.type){case MediaActivity$1.ACTIVITY_TYPE.PLAY:t=Ri;break;case MediaActivity$1.ACTIVITY_TYPE.SEEK:t=Ci}return t};var TimeTracker=function(t,n){this._date=new Date,this._position=n,this._validatePlaybackRate(t),this._playbackRate=t};Object.defineProperties(TimeTracker.prototype,{playbackRate:{get:function(){return this._playbackRate}}}),TimeTracker.prototype.update=function(t,n){this._date=new Date,this._position=n,this._validatePlaybackRate(t),this._playbackRate=t},TimeTracker.prototype.estimatedTime=function(t){var n;isInteger(t)?n=t:(Ai.logger.error("VPAFKit error: position should be an integer"),n=Math.round(t));var l=(n-this._position)/(0==this.playbackRate?1:this.playbackRate);return this._date.getTime()+Math.round(l)},TimeTracker.prototype._validatePlaybackRate=function(t){0==t&&Ai.logger.error("VPAFKit error: playbackRate should not be zero.")};var Di=Xr,Li=Ti.INCLUDES_START_POSITIONS,Ni=Ti.INCLUDES_END_POSITIONS,MediaActivityTracker=function(t){Di.apply(this,arguments),this._playlist=t,this._playActivity=null,this._playStartPlaylistItem=null,this._seekActivity=null,this._timeTracker=null,this._shouldGenerateTransitions=!0};(MediaActivityTracker.prototype=new Di).constructor=MediaActivityTracker,extend(MediaActivityTracker.prototype,Pi),Object.defineProperties(MediaActivityTracker.prototype,{shouldGenerateTransitions:{get:function(){return this._shouldGenerateTransitions},set:function(t){this._shouldGenerateTransitions=t}}}),MediaActivityTracker.prototype.setDelegate=function(t){return attachDelegate(this,t)},MediaActivityTracker.prototype.playStarted=function(t,n,l){return this.playStartedWithPlaybackRate.apply(this,[1].concat(Array.prototype.slice.call(arguments)))},MediaActivityTracker.prototype.playStartedWithPlaybackRate=function(t,n,l,d){if(this._hasUnstoppedActivity(this._playActivity))this._error("inconsistent state: did you forget to call playStopped?");else{var p=this._playlistItem(n,Li);p&&(this._playStarted.apply(this,[p].concat(Array.prototype.slice.call(arguments,1))),this.shouldGenerateTransitions&&(this._timeTracker=new TimeTracker(t,n)))}},MediaActivityTracker.prototype.playStopped=function(t,n,l){this._generatePlaylistTransitionsIfNecessary(t),this._hasUnstoppedActivity(this._playActivity)?this._playStopped.apply(this,Array.prototype.slice.call(arguments)):this._error("inconsistent state: did you forget to call playStarted?"),this._playStartPlaylistItem=null,this._timeTracker=null},MediaActivityTracker.prototype.playTransitioned=function(t){this.playStopped.apply(this,[t,this.TYPE.AUTOMATIC,this.PLAY_STOP_REASON.TRANSITION].concat(Array.prototype.slice.call(arguments,1))),this.playStarted.apply(this,[t,this.TYPE.AUTOMATIC,this.PLAY_START_REASON.TRANSITION].concat(Array.prototype.slice.call(arguments,1)))},MediaActivityTracker.prototype.seekStarted=function(t,n,l){if(this._hasUnstoppedActivity(this._seekActivity))this._error("inconsistent state: did you forget to call seekStopped?");else{var d=this._playlistItem(t,Li);if(d){var p=this._activityArguments.apply(this,[d].concat(Array.prototype.slice.call(arguments)));this._seekActivity=new MediaActivity$1(MediaActivity$1.ACTIVITY_TYPE.SEEK),this._seekActivity.started.apply(this._seekActivity,p)}}},MediaActivityTracker.prototype.seekStopped=function(t,n,l){var d=this._playlistItem(t,Ni);if(d&&this._hasUnstoppedActivity(this._seekActivity)){var p=this._activityArguments.apply(this,[d].concat(Array.prototype.slice.call(arguments)));this._seekActivity.stopped.apply(this._seekActivity,p)}else this._error("inconsistent state: did you forget to call seekStarted?")},MediaActivityTracker.prototype.synchronize=function(t,n){if(this.shouldGenerateTransitions){var l=t>0,d=this._hasUnstoppedActivity(this._playActivity);d&&l?(this._generatePlaylistTransitionsIfNecessary(n),this._timeTracker.update(t,n)):d&&!l?this._error("inconsistent state: did you forget to call playStopped?"):!d&&l&&this._error("inconsistent state: did you forget to call playStarted?")}},MediaActivityTracker.prototype._playStarted=function(t,n,l,d){var p=this._activityArguments.apply(this,[t].concat(Array.prototype.slice.call(arguments,1)));this._playStartPlaylistItem=t,this._playActivity=new MediaActivity$1(MediaActivity$1.ACTIVITY_TYPE.PLAY),this._playActivity.started.apply(this._playActivity,p)},MediaActivityTracker.prototype._playStopped=function(t,n,l){var d=this._playStartPlaylistItem,p=this._activityArguments.apply(this,[d].concat(Array.prototype.slice.call(arguments)));this._playActivity.stopped.apply(this._playActivity,p)},MediaActivityTracker.prototype._playlistItem=function(t,n){var l;return this._playlist&&isFunction(this._playlist.getItem)&&(l=this._playlist.getItem(t,n)),l||this._error("unable to get item from playlist"),l},MediaActivityTracker.prototype._playlistItems=function(t,n){var l=[];return this._playlist&&isFunction(this._playlist.getItems)?l=this._playlist.getItems(t,n):this._error("unable to get items from playlist"),l},MediaActivityTracker.prototype._relativePosition=function(t,n){var l;return(n=n||this._playlistItem(t))&&isNumber(n.startOverallPosition)&&(l=t-n.startOverallPosition+(n.startPosition||0)),l},MediaActivityTracker.prototype._combineEventData=function(t,n){var l=this._playlist?this._playlist.eventData:null,d=t?t.eventData:null,p=[];return l&&p.push(l),d&&p.push(d),this._eventData&&p.push(this._eventData),n&&(p=p.concat(n)),p},MediaActivityTracker.prototype._activityArguments=function(t,n,l,d){var p=this._relativePosition(n,t),h=this._combineEventData(t,Array.prototype.slice.call(arguments,4)),f=[p,n,l,d].concat(h);return f},MediaActivityTracker.prototype._generatePlaylistTransitionsIfNecessary=function(t){if(this.shouldGenerateTransitions&&this._hasUnstoppedActivity(this._playActivity)){var n,l,d,p=this._playActivity.startOverallPosition||0,h=this._playlistItems(p,t);this._playlist._returnsOrderedItems||h.sort(this._playlistItemComparator);for(var f=0;f+1<h.length;f++)if(h[f],!((n=(l=h[f+1]).startOverallPosition)<=p)){if(n>=t)break;d={eventTime:this._timeTracker?this._timeTracker.estimatedTime(n):null},this._playStopped(n,this.TYPE.AUTOMATIC,this.PLAY_STOP_REASON.TRANSITION,d),this._playStarted(l,n,this.TYPE.AUTOMATIC,this.PLAY_START_REASON.TRANSITION,d)}}},MediaActivityTracker.prototype._hasUnstoppedActivity=function(t){return t&&!t.isStopped},MediaActivityTracker.prototype._error=function(t){Ai.logger.error(this.constructor.name+" error: "+t)},MediaActivityTracker.prototype._playlistItemComparator=function(t,n){return t.startOverallPosition==n.startOverallPosition?0:t.startOverallPosition<n.startOverallPosition?-1:1};var xi=Xr,MediaPlaylistItem=function(t){xi.apply(this,arguments),this._startOverallPosition=t,this._startPosition=0};(MediaPlaylistItem.prototype=new xi).constructor=MediaPlaylistItem,Object.defineProperties(MediaPlaylistItem.prototype,{startOverallPosition:{get:function(){return this._startOverallPosition}},startPosition:{get:function(){return this._startPosition},set:function(t){this._startPosition=t}},eventData:{get:function(){return this._eventData}}});var HLSRollItem=function(t,n){MediaPlaylistItem.apply(this,arguments),this._duration=n};(HLSRollItem.prototype=new MediaPlaylistItem).constructor=HLSRollItem,Object.defineProperties(HLSRollItem.prototype,{duration:{get:function(){return this._duration}},endOverallPosition:{get:function(){return this.startOverallPosition+this.duration}}}),HLSRollItem.prototype.containsOverallPosition=function(t){return this.startOverallPosition<=t&&this.endOverallPosition>t};var MediaPlaylist=function(){};MediaPlaylist.prototype.RANGE_OPTIONS=Ti,Object.defineProperties(MediaPlaylist.prototype,{eventData:{get:function(){}}}),MediaPlaylist.prototype.getItem=function(t,n){},MediaPlaylist.prototype.getItems=function(t,n){};var HLSVideoPlaylist=function(t){MediaPlaylist.apply(this,arguments),this._startPosition=t,this._mainFeatureMetricsData=copyKeysAndValues.apply(null,[!1,!1,!1,null].concat(Array.prototype.slice.call(arguments,1))),this._rollItems=[]};(HLSVideoPlaylist.prototype=new MediaPlaylist).constructor=HLSVideoPlaylist,HLSVideoPlaylist.prototype.setDelegate=function(t){return attachDelegate(this,t)},HLSVideoPlaylist.prototype.addRollInfoItems=function(t){t&&t.length&&t.forEach((function(t){this.addRollInfoItem(t)}),this)},HLSVideoPlaylist.prototype.addRollInfoItem=function(t){t&&this.addRollItem(1e3*t.start,1e3*t.duration,t.metricsData)},HLSVideoPlaylist.prototype.addRollItem=function(t,n){var l=new HLSRollItem(t,n);l.updateData.apply(l,Array.prototype.slice.call(arguments,2)),this._addRollItem(l)},HLSVideoPlaylist.prototype.updateMainFeatureMetricsData=function(){extend.apply(null,[this._mainFeatureMetricsData].concat(Array.prototype.slice.call(arguments)))},HLSVideoPlaylist.prototype.getItem=function(t,n){var l,d=this._indexOfLastRollItemWithStartBeforePosition(t);if(isInteger(d)){for(;n!=this.RANGE_OPTIONS.INCLUDES_START_POSITIONS&&this._rollItems[d].startOverallPosition==t&&d>0;)d--;(l=this._rollItems[d]).containsOverallPosition(t)||n==this.RANGE_OPTIONS.INCLUDES_END_POSITIONS&&l.endOverallPosition==t||(l=this._mainFeatureItemWithStartOverallPosition(l.endOverallPosition))}else l=this._mainFeatureItemWithStartOverallPosition(this._startPosition);return l},HLSVideoPlaylist.prototype.getItems=function(t,n){var l=[];if(this._rollItems.length){var d=this._indexOfLastRollItemWithStartBeforePosition(t);for(isInteger(d)||(l.push(this._mainFeatureItemWithStartOverallPosition(this._startPosition)),d=0);d<this._rollItems.length;){var p=this._rollItems[d];if(p.startOverallPosition>n)break;if(p.endOverallPosition>=t&&l.push(p),d++,p.endOverallPosition<n)if(d<this._rollItems.length){var h=this._rollItems[d];h.startOverallPosition&&h.startOverallPosition>p.endOverallPosition&&l.push(this._mainFeatureItemWithStartOverallPosition(p.endOverallPosition))}else l.push(this._mainFeatureItemWithStartOverallPosition(p.endOverallPosition))}}else l.push(this._mainFeatureItemWithStartOverallPosition(this._startPosition));return l},HLSVideoPlaylist.prototype._addRollItem=function(t){if(t){var n=this._insertionIndexForItemWithPosition(t.startOverallPosition);this._rollItems.splice(n,0,t)}},HLSVideoPlaylist.prototype._indexOfLastRollItemWithStartBeforePosition=function(t){var n,l=this._rollItems[0];return l&&isInteger(t)&&l.startOverallPosition<=t&&(n=this._insertionIndexForItemWithPosition(t)-1),n},HLSVideoPlaylist.prototype._insertionIndexForItemWithPosition=function(t){for(var n=0,l=this._rollItems.length;n<l;){var d=Math.floor((n+l)/2);this._rollItems[d].startOverallPosition>t?l=d:n=d+1}return n},HLSVideoPlaylist.prototype._mainFeatureItemWithStartOverallPosition=function(t){var n=new MediaPlaylistItem(t);return n.startPosition=this._featurePlayheadProgress(t),n.updateData(this._mainFeatureMetricsData),n},HLSVideoPlaylist.prototype._featurePlayheadProgress=function(t){t=t||0;var n,l,d=this._indexOfLastRollItemWithStartBeforePosition(t),p=this._startPosition||0;isInteger(d)||(d=-1);for(var h=d;h>=0;h--)n=this._rollItems[h],0===h?p+=n.startOverallPosition:(l=this._rollItems[h-1],p+=n.startOverallPosition-l.endOverallPosition);return p};var Ui=Object.freeze({__proto__:null,createTracker:function(t){var n=new MediaActivityTracker(t);return n.updateData.apply(n,Array.prototype.slice.call(arguments,1)),n},createHLSVideoPlaylist:function(t){var n=new HLSVideoPlaylist(t);return n.updateMainFeatureMetricsData.apply(n,Array.prototype.slice.call(arguments,1)),n}});var Bi=Object.freeze({__proto__:null,applyFieldsMap:function(t,n){return applyFieldsMap(t,n,Config.value("fieldsMap",topic()))}}),ji=Object.freeze({__proto__:null,eventFields:Bi});function PlayActivity$2(){this.config=Config.defaultConfig(),this._initCalled=!1}PlayActivity$2.prototype._utReset=function(){this.config=Config.defaultConfig(),this._initCalled=!1},PlayActivity$2.prototype.init=function(t,n,l,d,p){if(!this._initCalled){this._initCalled=!0,l&&(setDelegates(Mi,l),setDelegates(Ai,l)),function(t){Jr=t}(t);var h=Config.getConfig(t),f={metricsDisabledOrBlacklistedEvent:metricsDisabledOrBlacklistedEvent,removeBlacklistedFields:removeBlacklistedFields};attachMethods(h,f,h),attachMethods(Config,f,Config),function(t,n){var l=null;if(t&&n&&n.setDelegate){var d,p={};for(d in t)isFunction(t[d])&&t[d].origFunction&&(p[d]=t[d]);l=n.setDelegate(p)}}(this.config,h),h.init(n,d,p),this.config=h}},PlayActivity$2.prototype.system=Ai,PlayActivity$2.prototype.eventHandlers=Mi,PlayActivity$2.prototype.mediaActivityTracker=Ui,PlayActivity$2.prototype.utils=ji;var Fi,Ki,Vi,$i,Hi,zi,Wi,Yi,qi,Gi=new PlayActivity$2,Qi={"ac-3":"AC3",alac:"Apple Lossless","ec-3":"EC3",fLaC:"Free Lossless","mp4a.40.2":"AAC","mp4a.40.5":"AAC","mp4a.40.29":"HE-AACv2","mp4a.40.34":"MP3","mp4a.40.42":"xHE-AAC"},getDefaultPlayable=function(t){if(hasPlayables(t))return t.playables[0]},hasPlayables=function(t){return void 0!==t.playables&&Array.isArray(t.playables)&&t.playables.length>0},Ji={initial:"idle",states:{idle:{on:(Fi={},Fi.PLAY={target:"playing",context:{reason:"PLAY",manual:"MANUAL"}},Fi)},binging:{on:(Ki={},Ki.PLAY={target:"playing",context:{reason:"NEXT",manual:"~~previous~~"}},Ki)},playing:{on:(Vi={},Vi.BUFFER_START={target:"buffering",context:{reason:"BUFFERING",manual:"AUTOMATIC"}},Vi.EXIT={target:"idle",context:{reason:"EXIT"}},Vi.PAUSE={target:"paused",context:{reason:"PAUSE"}},Vi.STOP={target:"idle",context:{}},Vi.NEXT={target:"binging",context:{reason:"NEXT"}},Vi.NEW={target:"idle",context:{}},Vi)},paused:{on:($i={},$i.PLAY={target:"playing",context:{reason:"UNPAUSE"}},$i.NEW={target:"idle",context:{}},$i)},buffering:{on:(Hi={},Hi.BUFFER_STOP={target:"playing",context:{reason:"BUFFERING",manual:"AUTOMATIC"}},Hi)}}},Xi={manual:"UNKNOWN",reason:"UNKNOWN"},Zi=function(){function VPAFStateMachine(){this.currentState=Ji.initial,this.currentContext=Xi}return VPAFStateMachine.prototype.isAllowedTransition=function(t){return void 0!==this.getNextState(t)},VPAFStateMachine.prototype.transition=function(t,n){void 0===n&&(n={});var l=this.getNextState(t);if(l){var d={};return n.hasOwnProperty("manual")&&(void 0!==n.manual?d.manual=n.manual?"MANUAL":"AUTOMATIC":d.manual="UNKNOWN"),void 0!==n.reason&&(d.reason=n.reason),this.currentContext=__assign(__assign(__assign(__assign({},Xi),l.context),d),this.preservePreviousContext(l.context)),this.currentState=l.target,this.currentContext}},VPAFStateMachine.prototype.reset=function(){this.currentState=Ji.initial,this.currentContext=Xi},VPAFStateMachine.prototype.getNextState=function(t){return Ji.states[this.currentState].on[t]},VPAFStateMachine.prototype.preservePreviousContext=function(t){var n=this,l={};return["manual","reason","reasonType"].forEach((function(d){"~~previous~~"===t[d]&&(l[d]=n.currentContext[d])})),l},VPAFStateMachine}(),en=__assign(__assign({},{NEXT_ITEM:"NEXT"}),t.PlayActivityEndReasonType);!function(t){t[t.Manual=0]="Manual",t[t.Interval=1]="Interval",t[t.SkipIntro=2]="SkipIntro"}(zi||(zi={}));var tn,rn,nn=((Wi={})[er.playbackPause]="PAUSE",Wi[er.playbackPlay]="PLAY",Wi[er.playbackStop]="STOP",Wi[er.playerExit]="EXIT",Wi),on=((Yi={})[t.PlayActivityEndReasonType.EXITED_APPLICATION]="EXIT",Yi[t.PlayActivityEndReasonType.FAILED_TO_LOAD]="FAILURE",Yi[t.PlayActivityEndReasonType.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM]="PLAY_OTHER",Yi[t.PlayActivityEndReasonType.NATURAL_END_OF_TRACK]="COMPLETE",Yi[t.PlayActivityEndReasonType.PLAYBACK_PAUSED_DUE_TO_INACTIVITY]="INACTIVITY",Yi[t.PlayActivityEndReasonType.SCRUB_BEGIN]="SEEK",Yi[t.PlayActivityEndReasonType.TRACK_SKIPPED_BACKWARDS]="SEEK",Yi[t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS]="SEEK",Yi[en.NEXT_ITEM]="NEXT",Yi),an={captions:"closedCaptionLocale",subtitles:"subtitleLocale"},sn=((qi={})[t.PresentationMode.pictureinpicture]="pictureInPicture",qi[t.PresentationMode.inline]="foreground",qi._default="foreground",qi),un=(function(){function VPAFTrackerAPI(){this.isScrubbing=!1,this.vpafKitInited=!1,this.state=new Zi,Gi.config.setDelegate({configHostname:function(){return"daf.xp.apple.com"}})}VPAFTrackerAPI.prototype.configure=function(t,n){var l,d;return __awaiter(this,void 0,void 0,(function(){var p,h=this;return __generator(this,(function(f){switch(f.label){case 0:if(this.instance=t,this.dispatcher=n.services.dispatcher,ar.storekit.cid)return[3,4];f.label=1;case 1:return f.trys.push([1,3,,4]),[4,ar.storekit.infoRefresh()];case 2:return f.sent(),[3,4];case 3:return f.sent(),[3,4];case 4:return p=null===(d=null===(l=n.services.apiManager)||void 0===l?void 0:l.utsAPI)||void 0===d?void 0:d.config,[2,new Promise((function(t,n){var l=[];navigator.languages?l=navigator.languages:navigator.language?l=[navigator.language]:navigator.userLanguage&&(l=[navigator.userLanguage]);var onSuccess=function(){return Gi.system.environment.setDelegate({app:function(){return"com.apple.tv"},appVersion:function(){return"1.0"},consumerId:function(){return ar.storekit.cid},consumerNs:function(){return"TV"},isOffline:function(){return!1},delegateApp:function(){return"web-tv-player"},osLanguages:function(){return l},resourceRevNum:function(){return ur.app.build},storeFrontCountryCode:function(){return(null==p?void 0:p.storefrontSupported)?p.country:""}}),h.setupListeners(),h.vpafKitInited=!0,t(h)};if(h.vpafKitInited)return onSuccess();var d={environment:qr,eventRecorder:Yr};Gi.init("xp_amp_tv_vpaf",null,d,onSuccess,(function(t){n(t)}))}))]}}))}))},VPAFTrackerAPI.prototype.cleanup=function(){this.tracker=void 0,this.isScrubbing=!1,this.scrubStopPosition=void 0,this.teardownListeners(),this.stopSynchronizing()},VPAFTrackerAPI.prototype.shouldConfigure=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,!0]}))}))},VPAFTrackerAPI.prototype.shouldTrackPlayActivity=function(t,n){if(!n)return!1;var l=getDefaultPlayable(n);if(!l||!l.vpafMetrics)return!1;var d=nn[t];return void 0===d||this.state.isAllowedTransition(d)},VPAFTrackerAPI.prototype.activate=function(t){return Promise.resolve()},VPAFTrackerAPI.prototype.bufferStart=function(t,n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return void 0!==this.currentItem&&this.isCurrentItem(t)?[3,2]:[4,this.play(t,n)];case 1:d.sent(),d.label=2;case 2:return[4,this.shouldTrack(t)];case 3:return d.sent()?(l=this.adjustedPosition(n),this.state.transition("BUFFER_START"),this.trackEvent("playStopped",l),[2]):[2]}}))}))},VPAFTrackerAPI.prototype.bufferEnd=function(t,n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return[4,this.shouldTrack(t)];case 1:return d.sent()?(l=this.adjustedPosition(n),this.state.transition("BUFFER_STOP"),this.trackEvent("playStarted",l),[2]):[2]}}))}))},VPAFTrackerAPI.prototype.exit=function(t){return void 0===t&&(t={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this.shouldTrack()];case 1:return n.sent()?(this.state.transition("EXIT"),this.trackEvent("playStopped",this.adjustedPosition(t)),this.stopSynchronizing(),[2]):[2]}}))}))},VPAFTrackerAPI.prototype.pause=function(t,n){return void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){var l,d;return __generator(this,(function(p){switch(p.label){case 0:return l=this.adjustedPosition(n),[4,this.shouldTrack(t)];case 1:return p.sent()?(d=n.endReasonType===en.NEXT_ITEM?"NEXT":"PAUSE",this.state.transition(d,this.getExplicitStateContext(n)),this.trackEvent("playStopped",l),[2]):[2]}}))}))},VPAFTrackerAPI.prototype.play=function(t,n){return void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){var l,d;return __generator(this,(function(p){switch(p.label){case 0:return l=this.adjustedPosition(n),d=void 0!==l?l:0,[4,this.shouldTrack(t)];case 1:return p.sent()?(this.state.transition("PLAY",this.getExplicitStateContext(n)),this.trackEvent("playStarted",d),[2]):[2]}}))}))},VPAFTrackerAPI.prototype.scrub=function(t,n){return void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){return void 0===t||void 0===n.position?[2]:(l=this.adjustedPosition(n),this.isScrubbing&&void 0===n.endReasonType?(this.scrubStopPosition=l,[2]):(this.isScrubbing&&this.scrubEnd(t,l),[2]))}))}))},VPAFTrackerAPI.prototype.seek=function(t,n){return void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){switch(l.label){case 0:return void 0===t||void 0===n.startPosition||void 0===n.position?[2]:this.isSkippingIntro(n)||this.isSeekingInterval(n)?(this.trackSeekStart(t,__assign(__assign({},n),{position:n.startPosition})),this.trackSeekStop(t,n),[2]):[4,this.scrubStart(t,this.convertTime(n.startPosition))];case 1:return l.sent(),this.scrubEnd(t,this.convertTime(n.position)),[2]}}))}))},VPAFTrackerAPI.prototype.skip=function(t,n){return Promise.resolve()},VPAFTrackerAPI.prototype.stop=function(t,n){return void 0===n&&(n={}),__awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return[4,this.shouldTrack(t)];case 1:return d.sent()?(l=this.adjustedPosition(n),this.state.transition("STOP",this.getExplicitStateContext(n)),this.trackEvent("playStopped",l),this.stopSynchronizing(),[2]):[2]}}))}))},VPAFTrackerAPI.prototype.adjustedPosition=function(t){return void 0===t.position?void 0:this.convertTime(t.position)},VPAFTrackerAPI.prototype.calculateOverallLength=function(t,n,l){var d=parseFloat(t.hlsMetadata["feature.duration"]);if(isNaN(d))return this.convertTime(n.duration);var p=l.reduce((function(t,n){return t+n.duration}),d);return this.convertTime(p)},VPAFTrackerAPI.prototype.convertTime=function(t){return Math.round(1e3*t)},VPAFTrackerAPI.prototype.createTracker=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l,d,p,h,f,y,v;return __generator(this,(function(g){return void 0===t||this.isCurrentItem(t)?[2]:(this.state.transition("NEW"),this.currentItem=t,void 0===(n=getDefaultPlayable(t))?[2]:(l=this.getMainFeatureData(t,n),d=this.transformRollItems(t),Pt.debug("VPAF: Creating HLS Playlist",l),p=Gi.mediaActivityTracker.createHLSVideoPlaylist(0,l),Pt.debug("VPAF: adding roll items",d),p.addRollInfoItems(d),h=Gi.utils.eventFields.applyFieldsMap(n,"utsVpafPlayable"),f=Gi.utils.eventFields.applyFieldsMap(t.attributes,"utsVpafContent"),y=n.vpafMetrics,(v=this.getAdditionalTrackingData(n)).overallLength=this.calculateOverallLength(t,n,d),Pt.debug("VPAF: creating tracker with",[h,f,y,v]),this.tracker=Gi.mediaActivityTracker.createTracker(p,h,f,y,v),this.startSynchronizing(),[2,this.tracker]))}))}))},VPAFTrackerAPI.prototype.getCurrentAudioSelection=function(){var t,n,l,d,p,h=null===(l=null===(n=this.instance)||void 0===n?void 0:n.currentAudioTrack)||void 0===l?void 0:l.language;if(void 0!==h){var f="description"===(null===(p=null===(d=this.instance)||void 0===d?void 0:d.currentAudioTrack)||void 0===p?void 0:p.kind)?"audioDescriptionLocale":"audioLocale",y="audioLocale"===f?"audioDescriptionLocale":"audioLocale";return(t={})[f]=h,t[y]=void 0,t}},VPAFTrackerAPI.prototype.getMainFeatureData=function(t,n){var l,d=null===(l=null==t?void 0:t.hlsMetadata)||void 0===l?void 0:l["feature.adam-id"],p={url:t.attributes.url,assetPlacement:"feature",assetId:d};return!0===t.attributes.isAdultContent&&(p.sensitiveContentType="adult"),p},VPAFTrackerAPI.prototype.transformRollItems=function(t){return parseRollItems(t).map((function(t){return{start:t.start,duration:t.duration,metricsData:{assetPlacement:t.type.replace("-",""),assetId:t["adam-id"],isSkippable:t.skippable}}}))},VPAFTrackerAPI.prototype.getMappedStopReason=function(t){if(void 0!==t.endReasonType)return on[t.endReasonType]},VPAFTrackerAPI.prototype.getExplicitStateContext=function(t){return{manual:t.userInitiated,reason:this.getMappedStopReason(t)}},VPAFTrackerAPI.prototype.handleLevelUpdated=function(t,n){var l;if(n.audioCodec||n.videoRange){var d={};n.audioCodec&&(d.audioFormat=function(t,n){var l;return null!==(l=Qi[t])&&void 0!==l?l:t}(n.audioCodec,this.currentAudioChannels)),n.videoRange&&(d.videoColorRange=n.videoRange),null===(l=this.tracker)||void 0===l||l.updateData(d)}},VPAFTrackerAPI.prototype.handleAudioTrackChange=function(t,n){var l;this.currentAudioChannels=null===(l=null==n?void 0:n.hlsTrack)||void 0===l?void 0:l.channels;var d=this.tracker;if(void 0!==d){var p=this.getCurrentAudioSelection();p&&d.updateData(p)}},VPAFTrackerAPI.prototype.handleForcedTextTrackChange=function(t,n){var l;null===(l=this.tracker)||void 0===l||l.updateData({forcedSubtitleLocale:null==n?void 0:n.language})},VPAFTrackerAPI.prototype.handlePresentationModeChange=function(t,n){var l,d,p=n.mode,h=null!==(l=sn[p])&&void 0!==l?l:sn._default;null===(d=this.tracker)||void 0===d||d.updateData({playbackFocus:h})},VPAFTrackerAPI.prototype.handleTargetWirelessChange=function(){var t;null===(t=this.tracker)||void 0===t||t.updateData({delegatedPlayback:this.getDelegatedPlayback()})},VPAFTrackerAPI.prototype.handleTextTrackChange=function(){var t,n=this.tracker;if(void 0!==n){var l=null===(t=this.instance)||void 0===t?void 0:t.currentTextTrack;if(l&&("captions"===l.kind||"subtitles"===(null==l?void 0:l.kind))){var d=""===l.language?void 0:l.language,p={closedCaptionLocale:"captions"===l.kind?d:void 0,subtitleLocale:"subtitles"===l.kind?d:void 0};n.updateData(p)}}},VPAFTrackerAPI.prototype.isSkippingIntro=function(t){return t.seekReasonType===zi.SkipIntro},VPAFTrackerAPI.prototype.isSeekingInterval=function(t){return t.seekReasonType===zi.Interval},VPAFTrackerAPI.prototype.shouldTrack=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this.createTracker(t)];case 1:return n.sent(),[2,void 0!==this.tracker]}}))}))},VPAFTrackerAPI.prototype.isCurrentItem=function(t){return void 0!==this.currentItem&&void 0!==t&&this.currentItem.id===t.id},VPAFTrackerAPI.prototype.getAdditionalTrackingData=function(t){var n,l,d,p=this.instance,h=null===(n=null==p?void 0:p.videoContainerElement)||void 0===n?void 0:n.querySelector("video"),f=null===(l=t.primaryLocale)||void 0===l?void 0:l.locale,y=null!==(d=this.getCurrentAudioSelection())&&void 0!==d?d:void 0!==f?{audioLocale:f}:{},v=null==p?void 0:p.currentTextTrack,g={programmingType:"videoOnDemand",downloadState:"streaming",videoViewportHeight:null==h?void 0:h.clientHeight,videoViewportWidth:null==h?void 0:h.clientWidth,playbackFocus:sn._default,delegatedPlayback:this.getDelegatedPlayback()};if(v){var _=an[v.kind];_&&v.language&&(g[_]=v.language)}return __assign(__assign({},g),y)},VPAFTrackerAPI.prototype.getDelegatedPlayback=function(){var t;return(null===(t=this.instance)||void 0===t?void 0:t.playbackTargetIsWireless)?"Airplay":"None"},VPAFTrackerAPI.prototype.onVideoComponentScrubStart=function(t){return this.scrubStart(this.currentItem,this.convertTime(t.detail.currentSeconds))},VPAFTrackerAPI.prototype.setupListeners=function(){void 0!==this.dispatcher&&(this.dispatcher.subscribe(nr.audioTrackChanged,this.handleAudioTrackChange),this.dispatcher.subscribe(nr.textTrackChanged,this.handleTextTrackChange),this.dispatcher.subscribe(nr.forcedTextTrackChanged,this.handleForcedTextTrackChange),this.dispatcher.subscribe(er.hlsLevelUpdated,this.handleLevelUpdated),this.dispatcher.subscribe(nr.playbackTargetIsWirelessDidChange,this.handleTargetWirelessChange),this.dispatcher.subscribe(nr.presentationModeDidChange,this.handlePresentationModeChange)),_t||window.addEventListener("triggerSeekStart",this.onVideoComponentScrubStart)},VPAFTrackerAPI.prototype.teardownListeners=function(){void 0!==this.dispatcher&&(this.dispatcher.unsubscribe(nr.audioTrackChanged,this.handleAudioTrackChange),this.dispatcher.unsubscribe(nr.textTrackChanged,this.handleTextTrackChange),this.dispatcher.unsubscribe(nr.forcedTextTrackChanged,this.handleForcedTextTrackChange),this.dispatcher.unsubscribe(er.hlsLevelUpdated,this.handleLevelUpdated),this.dispatcher.unsubscribe(nr.playbackTargetIsWirelessDidChange,this.handleTargetWirelessChange),this.dispatcher.unsubscribe(nr.presentationModeDidChange,this.handlePresentationModeChange)),_t||window.removeEventListener("triggerSeekStart",this.onVideoComponentScrubStart)},VPAFTrackerAPI.prototype.scrubEnd=function(t,n){this.trackEvent("seekStopped",n,this.tracker.TYPE.MANUAL,this.tracker.SEEK_STOP_REASON.SCRUB),"playing"===this.state.currentState&&(this.trackEvent("playStopped",this.scrubStopPosition,this.tracker.TYPE.AUTOMATIC,this.tracker.PLAY_STOP_REASON.SEEK),this.trackEvent("playStarted",n,this.tracker.TYPE.AUTOMATIC,this.tracker.PLAY_START_REASON.SEEK)),this.isScrubbing=!1,this.scrubStopPosition=void 0},VPAFTrackerAPI.prototype.scrubStart=function(t,n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){switch(l.label){case 0:return[4,this.shouldTrack(t)];case 1:return l.sent()?(this.isScrubbing=!0,this.scrubStopPosition=n,this.trackEvent("seekStarted",n,this.tracker.TYPE.MANUAL,this.tracker.SEEK_START_REASON.SCRUB),[2]):[2]}}))}))},VPAFTrackerAPI.prototype.startSynchronizing=function(){void 0===this.synchronizeTimeout&&(this.synchronizeTimeout=setInterval(this.synchronize,6e4))},VPAFTrackerAPI.prototype.stopSynchronizing=function(){void 0!==this.synchronizeTimeout&&(clearInterval(this.synchronizeTimeout),this.synchronizeTimeout=void 0)},VPAFTrackerAPI.prototype.synchronize=function(){if(void 0!==this.tracker&&void 0!==this.instance){var t="paused"===this.state.currentState,n=this.instance,l=n.playbackRate,d=n.currentPlaybackTime,p=t?0:l,h=Math.round(1e3*d);Pt.debug("VPAF: synchronize rate: "+p+" and current time: "+h),this.tracker.synchronize(p,h)}else this.stopSynchronizing()},VPAFTrackerAPI.prototype.trackSeekStart=function(t,n){var l=n.seekReasonType===zi.SkipIntro?this.tracker.SEEK_START_REASON.SKIP_INTRO:this.tracker.SEEK_START_REASON.INTERVAL,d=this.adjustedPosition(n),p=this.tracker.TYPE.MANUAL;this.trackEvent("seekStarted",d,p,l),"playing"===this.state.currentState&&this.trackEvent("playStopped",d,p,this.tracker.PLAY_STOP_REASON.SEEK,this.isSkippingIntro(n)?{stopReasonType:this.tracker.PLAY_STOP_REASON_TYPE.SKIP_INTRO}:void 0)},VPAFTrackerAPI.prototype.trackSeekStop=function(t,n){var l=this.isSeekingInterval(n)?this.tracker.SEEK_STOP_REASON.INTERVAL:this.tracker.SEEK_STOP_REASON.SKIP_INTRO,d=this.adjustedPosition(n),p=this.tracker.TYPE.AUTOMATIC;this.trackEvent("seekStopped",d,p,l),"playing"===this.state.currentState&&this.trackEvent("playStarted",d,p,this.tracker.PLAY_START_REASON.SEEK,this.isSkippingIntro(n)?{startReasonType:this.tracker.PLAY_START_REASON_TYPE.SKIP_INTRO}:void 0)},VPAFTrackerAPI.prototype.trackEvent=function(t,n,l,d,p){void 0===l&&(l=this.tracker.TYPE[this.state.currentContext.manual]),void 0===d&&(d="playStarted"===t?this.tracker.PLAY_START_REASON[this.state.currentContext.reason]:this.tracker.PLAY_STOP_REASON[this.state.currentContext.reason]),Pt.debug("VPAF: "+t,n,l,d,p),this.tracker[t].call(this.tracker,Math.round(n),l,d,p)},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"handleLevelUpdated",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"handleAudioTrackChange",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"handleForcedTextTrackChange",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"handlePresentationModeChange",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"handleTargetWirelessChange",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"handleTextTrackChange",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[CustomEvent]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"onVideoComponentScrubStart",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],VPAFTrackerAPI.prototype,"synchronize",null)}(),function(){}),asAsync=function(t){t.then(un,un)},cn=un;!function(t){t.playbackLicenseError="playbackLicenseError",t.playbackSessionError="playbackSessionError",t.manifestParsed="manifestParsed",t.audioCodecIdentified="audioCodecIdentified",t.audioTracksSwitched="audioTracksSwitched",t.audioTracksUpdated="audioTracksUpdated",t.textTracksSwitched="textTracksSwitched",t.textTracksUpdated="textTracksUpdated",t.sessionCreated="sessionCreated",t.levelUpdated="levelUpdated"}(tn||(tn={})),function(t){t.MP4="audio/mp4",t.AVC1="video/mp4"}(rn||(rn={}));var hasSessionStorage=function(){return"undefined"!=typeof window&&window.sessionStorage};function findMediaKeySystemAccess(t,n){return __awaiter(this,void 0,void 0,(function(){var l,d,p;return __generator(this,(function(h){switch(h.label){case 0:l=0,h.label=1;case 1:if(!(l<t.length))return[3,6];h.label=2;case 2:return h.trys.push([2,4,,5]),d=t[l],[4,navigator.requestMediaKeySystemAccess(d,n)];case 3:return p=h.sent(),[2,[d,p]];case 4:return h.sent(),[3,5];case 5:return l++,[3,1];case 6:return[2,[]]}}))}))}var ln;function potentialKeySystemsForAccess(){return hasSessionStorage()&&"true"===window.sessionStorage.getItem("mk-playready-cbcs-unsupported")?[et.WIDEVINE]:ur.features["prefer-playready"]?[et.PLAYREADY,et.WIDEVINE]:[et.WIDEVINE,et.PLAYREADY]}function findKeySystemPreference(){var t,n;return __awaiter(this,void 0,void 0,(function(){var l,d,p,h;return __generator(this,(function(f){switch(f.label){case 0:return _t?[2,void 0]:(null===(t=window.WebKitMediaKeys)||void 0===t?void 0:t.isTypeSupported(et.FAIRPLAY+".1_0",rn.AVC1))?(ln=et.FAIRPLAY,[3,4]):[3,1];case 1:return(null===(n=window.MSMediaKeys)||void 0===n?void 0:n.isTypeSupported(et.PLAYREADY,rn.AVC1))?(ln=et.PLAYREADY,[3,4]):[3,2];case 2:return l=kt,hasMediaKeySupport()&&l.canPlayType('video/mp4;codecs="avc1.42E01E"')&&l.canPlayType('audio/mp4;codecs="mp4a.40.2"')?(d=[{videoCapabilities:[{contentType:'video/mp4;codecs="avc1.42E01E"',robustness:"SW_SECURE_CRYPTO"}],audioCapabilities:[{contentType:'audio/mp4;codecs="mp4a.40.2"'}]}],[4,findMediaKeySystemAccess(potentialKeySystemsForAccess(),d)]):[3,4];case 3:p=__read.apply(void 0,[f.sent(),1]),h=p[0],ln=h,f.label=4;case 4:return[2,ln]}}))}))}function hasMediaKeySupport(){return!!(navigator&&navigator.requestMediaKeySystemAccess&&window.MediaKeys&&window.MediaKeySystemAccess)}var dn,pn,hn,fn="mk-player-tsid",isInFullscreen=function(t){return void 0===t&&(t=self.document),!!(t.fullscreenElement||t.webkitFullscreenElement||t.mozFullScreenElement||t.msFullscreenElement)},yn=function(){function Fullscreen(t){this.player=t}return Fullscreen.prototype.exit=function(){return __awaiter(this,void 0,void 0,(function(){var t=this;return __generator(this,(function(n){return this.isInFullscreen()?[2,this.stopDispatchingEvents((function(){return t.exitFullscreen()}))]:[2]}))}))},Fullscreen.prototype.request=function(t){return __awaiter(this,void 0,void 0,(function(){var n=this;return __generator(this,(function(l){return void 0===t?[2]:[2,this.stopDispatchingEvents((function(){return n.requestFullscreenForElement(t)}))]}))}))},Fullscreen.prototype.stopDispatchingEvents=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,this.player.windowHandlers.stopListeningToVisibilityChanges(t)]}))}))},Fullscreen.prototype.exitFullscreen=function(){return __awaiter(void 0,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return document.exitFullscreen?[4,document.exitFullscreen()]:[3,2];case 1:return t.sent(),[3,8];case 2:return document.webkitExitFullscreen?[4,document.webkitExitFullscreen()]:[3,4];case 3:return t.sent(),[3,8];case 4:return document.mozCancelFullScreen?[4,document.mozCancelFullScreen()]:[3,6];case 5:return t.sent(),[3,8];case 6:return document.msExitFullscreen?[4,document.msExitFullscreen()]:[3,8];case 7:t.sent(),t.label=8;case 8:return[2]}}))}))},Fullscreen.prototype.isInFullscreen=function(){return isInFullscreen()},Fullscreen.prototype.requestFullscreenForElement=function(t){return n=t,__awaiter(void 0,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return void 0===n?[2]:n.requestFullscreen?[4,n.requestFullscreen()]:[3,2];case 1:return t.sent(),[3,8];case 2:return n.webkitRequestFullscreen?[4,n.webkitRequestFullscreen()]:[3,4];case 3:return t.sent(),[3,8];case 4:return n.mozRequestFullScreen?[4,n.mozRequestFullScreen()]:[3,6];case 5:return t.sent(),[3,8];case 6:return n.msRequestFullscreen?[4,n.msRequestFullscreen()]:[3,8];case 7:t.sent(),t.label=8;case 8:return[2]}}))}));var n},Fullscreen}(),vn=function(){function UnsupportedSeeker(){this.ended=!1}return UnsupportedSeeker.prototype.start=function(){Pt.warn("seeker.start is not supported in this playback method")},UnsupportedSeeker.prototype.end=function(){Pt.warn("seeker.end is not supported in this playback method")},UnsupportedSeeker.prototype.seekToTime=function(t){return Pt.warn("seekToTime is not supported in this playback method"),Promise.resolve()},UnsupportedSeeker}(),gn=function(){function PlayerSeeker(t){this._ended=!1,this._lastSeekedTime=-1,this._startTime=-1,Pt.debug("seeker: new"),this._player=t}return Object.defineProperty(PlayerSeeker.prototype,"ended",{get:function(){return this._ended},enumerable:!0,configurable:!0}),Object.defineProperty(PlayerSeeker.prototype,"isEngagedInPlayback",{get:function(){return this._player.isEngagedInPlayback},enumerable:!0,configurable:!0}),Object.defineProperty(PlayerSeeker.prototype,"stillPlayingSameItem",{get:function(){return this._currentItem===this._player.nowPlayingItem},enumerable:!0,configurable:!0}),PlayerSeeker.prototype.end=function(){Pt.debug("seeker: end"),-1!==this._startTime?this._ended?Pt.warn("seeker: Cannot end the same seeker twice."):(this.dispatchStartEvent(),this.dispatchEndEvent()):Pt.warn("seeker: Cannot end a seeker before starting it.")},PlayerSeeker.prototype.seekToTime=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return Pt.debug("seeker: seekToTime",t),this.ended?(Pt.warn("seeker: Cannot seek once the seeker has ended"),[2]):(this.stillPlayingSameItem||(this._currentItem=this._player.nowPlayingItem,this._startTime=0),this._lastSeekedTime=t,[2,this._player.seekToTime(t)])}))}))},PlayerSeeker.prototype.start=function(){Pt.debug("seeker: start"),-1===this._startTime?(this._currentItem=this._player.nowPlayingItem,this._startTime=this._player.currentPlaybackTime,this._lastSeekedTime=this._startTime):Pt.warn("seeker: Cannot start same seeker twice")},PlayerSeeker.prototype.dispatch=function(t,n){this.isEngagedInPlayback?(Pt.debug("seeker: dispatch",t),this._player.dispatch(t,n)):Pt.debug("seeker: do not dispatch because isEngagedInPlayback",this.isEngagedInPlayback)},PlayerSeeker.prototype.dispatchStartEvent=function(){this.stillPlayingSameItem||(this._startTime=0,this._lastSeekedTime=0),this.dispatch(er.playbackScrub,{position:this._startTime})},PlayerSeeker.prototype.dispatchEndEvent=function(){this._ended=!0,this.dispatch(er.playbackScrub,{position:this._lastSeekedTime,endReasonType:t.PlayActivityEndReasonType.SCRUB_END})},PlayerSeeker}(),_n=(pn="visibilitychange",hn="visibilityState",void 0!==document.mozHidden?(pn="mozvisibilitychange",hn="mozVisibilityState"):void 0!==document.msHidden?(pn="msvisibilitychange",hn="msVisibilityState"):document.webkitHidden&&(pn="webkitvisibilitychange",hn="webkitVisibilityState"),(dn={visibilityChangeEvent:pn,visibilityState:hn,unloadEventName:"onpagehide"in window?"pagehide":"unload"}).visibilityChangeEvent),mn=dn.visibilityState,bn=dn.unloadEventName,Pn=function(){function WindowHandlers(t,n){void 0===n&&(n=bt),this.browser=n,this.dispatchVisibilityChanges=!0,this.player=t}return WindowHandlers.prototype.activate=function(t,n){void 0===t&&(t=self),void 0===n&&(n=self.document),n.addEventListener(_n,this.visibilityChanged),t.addEventListener("storage",this.storage,!1),t.addEventListener(bn,this.windowUnloaded)},WindowHandlers.prototype.deactivate=function(){document.removeEventListener(_n,this.visibilityChanged),window.removeEventListener("storage",this.storage),window.addEventListener(bn,this.windowUnloaded)},WindowHandlers.prototype.stopListeningToVisibilityChanges=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return this.dispatchVisibilityChanges=!1,[4,t()];case 1:return n=l.sent(),this.dispatchVisibilityChanges=!0,[2,n]}}))}))},WindowHandlers.prototype.dispatch=function(t,n){void 0===n&&(n={}),this.player.dispatch(t,n)},WindowHandlers.prototype.storage=function(t){var n=t.key,l=t.newValue;n===fn&&this.player.tsidChanged(l)},WindowHandlers.prototype.visibilityChanged=function(t){var n=t.target[mn];Pt.log("dc visibilityState",n,t,isInFullscreen()),this.browser.isiOS&&this.dispatchVisibilityChanges&&("hidden"===n?this.dispatch(er.playerExit,{position:this.player.currentPlaybackTime}):"visible"===n&&this.dispatch(er.playerActivate))},WindowHandlers.prototype.windowUnloaded=function(){this.player.isPlaying&&this.dispatch(er.playerExit,{position:this.player.currentPlaybackTime})},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",void 0)],WindowHandlers.prototype,"storage",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Event]),__metadata("design:returntype",void 0)],WindowHandlers.prototype,"visibilityChanged",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],WindowHandlers.prototype,"windowUnloaded",null),WindowHandlers}(),kn=nr.bufferedProgressDidChange,Tn=nr.mediaCanPlay,Sn=nr.mediaElementCreated,An=nr.nowPlayingItemDidChange,wn=nr.nowPlayingItemWillChange,In=nr.metadataDidChange,En=nr.primaryPlayerDidChange,Rn=nr.playbackDurationDidChange,On=nr.playbackProgressDidChange,Cn=nr.playbackStateDidChange,Mn=nr.playbackStateWillChange,Dn=nr.playbackTargetAvailableDidChange,Ln=nr.playbackTargetIsWirelessDidChange,Nn=nr.playbackTimeDidChange,xn=nr.playbackVolumeDidChange,Un=["canplay","durationchange","ended","error","loadedmetadata","loadstart","pause","play","playing","progress","seeked","seeking","timeupdate","volumechange","waiting"],Bn=t.PlaybackStates.ended,jn=t.PlaybackStates.loading,Fn=t.PlaybackStates.paused,Kn=t.PlaybackStates.playing,Vn=t.PlaybackStates.seeking,$n=t.PlaybackStates.stopped,Hn=t.PlaybackStates.waiting,zn=function(){function BasePlayer(n){this.privateEnabled=!1,this.siriInitiated=!1,this.previewOnly=!1,this._currentBufferedProgress=0,this._paused=!1,this._playbackState=t.PlaybackStates.none,this._stopped=!1,this._currentPlaybackProgress=0,this._hasSmartPlayed=!1,this._isPrimaryPlayer=!0,this._playbackTargetAvailable=!1,this._playbackTargetIsWireless=!1,this._serial=Date.now().toString(),this._isDestroyed=!1,this._dispatcher=n.services.dispatcher,this._timing=n.services.timing,this._context=n.context||{},this.privateEnabled=n.privateEnabled||!1,this.siriInitiated=n.siriInitiated||!1,this._bitrateCalculator=n.services.bitrateCalculator,this.windowHandlers=new Pn(this),this.fullscreen=new yn(this),localStorage.setItem(fn,this._serial)}return Object.defineProperty(BasePlayer.prototype,"bitrate",{get:function(){return this._bitrateCalculator.bitrate},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"canSupportDRM",{get:function(){return!!this.extension&&!!ln},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"currentBufferedProgress",{get:function(){return this._currentBufferedProgress},set:function(t){this._currentBufferedProgress!==t&&(this._currentBufferedProgress=t,this._dispatcher.publish(kn,{progress:t}))},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"_currentDuration",{get:function(){return this._targetElement.duration},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"_currentTime",{get:function(){return this._targetElement.currentTime},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"currentPlaybackDuration",{get:function(){var n=this.nowPlayingItem,l=(null==n?void 0:n.playbackType)===t.PlaybackType.encryptedFull||(null==n?void 0:n.playbackType)===t.PlaybackType.unencryptedFull,d=null==n?void 0:n.playbackDuration;return l&&d?this._timing.time(d/1e3):this._timing.time(this._currentDuration)},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"currentPlaybackTime",{get:function(){var t=void 0===this.nowPlayingItem||void 0===this.nowPlayingItem.playEvent||this._hasSmartPlayed?this._currentTime:this.nowPlayingItem.playEvent.playCursorInSeconds;return this._timing.time(t)},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"currentPlaybackTimeRemaining",{get:function(){return this.currentPlaybackDuration-this.currentPlaybackTime},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"currentPlaybackProgress",{get:function(){return this._currentPlaybackProgress||0},set:function(t){this._currentPlaybackProgress!==t&&(this._currentPlaybackProgress=t,this._dispatcher.publish(On,{progress:t}))},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"formattedCurrentPlaybackDuration",{get:function(){return formattedSeconds(this.currentPlaybackDuration)},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"hasMediaElement",{get:function(){return this._targetElement instanceof HTMLElement&&null!==this._targetElement.parentNode},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"isEngagedInPlayback",{get:function(){return!this._stopped&&!this.isPaused()},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"isPlaying",{get:function(){return this.playbackState===Kn},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"isPrimaryPlayer",{get:function(){return this._isPrimaryPlayer},set:function(t){t!==this._isPrimaryPlayer&&(this._isPrimaryPlayer=t,this._isPrimaryPlayer?localStorage.setItem(fn,this._serial):(this._dispatcher.publish(En,{target:this}),this.pause({userInitiated:!1})))},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"isReady",{get:function(){return 0!==this._targetElement.readyState},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"nowPlayingItem",{get:function(){return this._nowPlayingItem},set:function(t){if(this._hasSmartPlayed=!1,void 0===t)return this._nowPlayingItem=t,void this._dispatcher.publish(An,{item:t});this._nowPlayingItem&&this._nowPlayingItem.isEqual(t)||(this._dispatcher.publish(wn,{item:t}),this.isPlaying&&this._pauseMedia(),this.canSupportDRM&&this.hasMediaElement&&this.extension.cancelPendingRenewal(),this._nowPlayingItem&&(this._nowPlayingItem.state=pr.ended,this._nowPlayingItem.endMonitoringStateDidChange(),this._nowPlayingItem.endMonitoringStateWillChange()),this._nowPlayingItem=t,this._nowPlayingItem.state=pr.playing,t&&t.info&&this._setTargetElementTitle(t.info),this._dispatcher.publish(An,{item:t}),this._dispatcher.publish(Rn,{currentTarget:this._targetElement,duration:this.currentPlaybackDuration,target:this._targetElement,type:"durationchange"}))},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"playbackRate",{get:function(){return this._targetElement.playbackRate},set:function(t){this._targetElement.playbackRate=t},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"playbackState",{get:function(){return this._playbackState},set:function(t){if(t!==this._playbackState){var n={oldState:this._playbackState,state:t,nowPlayingItem:this.nowPlayingItem?{id:this.nowPlayingItem.id,type:this.nowPlayingItem.type}:void 0};Pt.debug("BasePlayer.playbackState is changing",n),this._dispatcher.publish(Mn,n),this._playbackState=t,this._dispatcher.publish(Cn,n)}},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"playbackTargetAvailable",{get:function(){return void 0!==window.WebKitPlaybackTargetAvailabilityEvent&&this._playbackTargetAvailable},set:function(t){t!==this._playbackTargetAvailable&&(this._playbackTargetAvailable=t,this._dispatcher.publish(Dn,{available:t}))},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"playbackTargetIsWireless",{get:function(){return void 0!==window.WebKitPlaybackTargetAvailabilityEvent&&this._playbackTargetIsWireless},set:function(t){t!==this._playbackTargetIsWireless&&(this._playbackTargetIsWireless=t,this._dispatcher.publish(Ln,{playing:t}))},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"volume",{get:function(){return this._targetElement.volume},set:function(t){this._targetElement.volume=t},enumerable:!0,configurable:!0}),Object.defineProperty(BasePlayer.prototype,"isDestroyed",{get:function(){return this._isDestroyed},enumerable:!0,configurable:!0}),BasePlayer.prototype.initialize=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return Pt.debug("BasePlayer.initialize"),this.isPlayerSupported()?[4,this.initializeMediaElement()]:(Pt.warn("{this.constructor.name} not supported"),[2]);case 1:return t.sent(),[4,this.initializeExtension()];case 2:return t.sent(),this.initializeEventHandlers(),this._dispatcher.publish(Sn,this._targetElement),[2]}}))}))},BasePlayer.prototype.initializeEventHandlers=function(){var t=this;if(this.windowHandlers.activate(),this.hasMediaElement){var n=this._targetElement;window.WebKitPlaybackTargetAvailabilityEvent&&(n.addEventListener("webkitplaybacktargetavailabilitychanged",(function(n){t.playbackTargetAvailable="available"===n.availability})),n.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",(function(n){t.playbackTargetIsWireless=n.target===t._targetElement&&!t.playbackTargetIsWireless}))),Un.forEach((function(l){return n.addEventListener(l,t)})),this.dispatch(er.playerActivate,{isPlaying:this.isPlaying})}},BasePlayer.prototype.removeEventHandlers=function(){var t=this;Un.forEach((function(n){return t._targetElement.removeEventListener(n,t)})),this.windowHandlers.deactivate()},BasePlayer.prototype.isPaused=function(){return this._paused},BasePlayer.prototype.exitFullscreen=function(){return this.fullscreen.exit()},BasePlayer.prototype.requestFullscreen=function(t){return this.fullscreen.request(t)},BasePlayer.prototype.seekToTime=function(t,n){return void 0===n&&(n=zi.Manual),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return this._buffer?[4,this._buffer.seek(t)]:[3,2];case 1:n.sent(),n.label=2;case 2:return this._targetElement.currentTime=t,[2]}}))}))},BasePlayer.prototype.newSeeker=function(t){var n;return null===(n=this._seeker)||void 0===n||n.end(),this._seeker=new gn(this),this._seeker},BasePlayer.prototype.stop=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return Pt.debug("BasePlayer.stop",t),[4,this._waitForPendingPlay()];case 1:return n.sent(),this.isPlaying&&this.dispatch(er.playbackStop,__assign({position:this.currentPlaybackTime,startPosition:this._initialBufferPosition||0},t)),[4,this.stopMediaAndCleanup()];case 2:return n.sent(),[2]}}))}))},BasePlayer.prototype.stopMediaAndCleanup=function(t){return void 0===t&&(t=$n),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this._stopMediaElement()];case 1:return n.sent(),this._stopped=!0,this.playbackState=t,this.nowPlayingItem=void 0,this._initialBufferPosition=void 0,[2]}}))}))},BasePlayer.prototype._calculatePlaybackProgress=function(){this.currentPlaybackProgress=Math.round(100*(this.currentPlaybackTime/this.currentPlaybackDuration||0))/100},BasePlayer.prototype.destroy=function(){if(Pt.debug("BasePlayer.destroy"),this._isDestroyed=!0,this.hasMediaElement){var t=this._targetElement;this.extension&&this.extension.destroy(this._targetElement),this.removeEventHandlers(),null!==t.parentNode&&t.parentNode.removeChild(t)}},BasePlayer.prototype.handleEvent=function(n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:switch("timeupdate"!==n.type&&Pt.debug("BasePlayer.handleEvent: ",n.type,n,this.isPaused(),this._stopped),n.type){case"canplay":return[3,1];case"durationchange":return[3,2];case"ended":return[3,3];case"error":return[3,5];case"loadedmetadata":return[3,6];case"loadstart":return[3,7];case"pause":return[3,8];case"play":case"playing":return[3,9];case"progress":return[3,10];case"seeked":return[3,11];case"seeking":return[3,12];case"timeupdate":return[3,13];case"volumechange":return[3,14];case"waiting":return[3,15]}return[3,16];case 1:return this._dispatcher.publish(Tn,n),this.handleSmartPlay(),this._playbackState!==t.PlaybackStates.waiting||this._targetElement.paused||(this.playbackState=t.PlaybackStates.playing),[3,16];case 2:return this._targetElement.duration!==1/0&&(n.duration=this.currentPlaybackDuration,this._dispatcher.publish(Rn,n),this._calculatePlaybackProgress()),[3,16];case 3:return this.playbackState=Bn,this.dispatch(er.playbackStop,{endReasonType:t.PlayActivityEndReasonType.NATURAL_END_OF_TRACK}),[4,this.stopMediaAndCleanup(Bn)];case 4:return d.sent(),[3,16];case 5:case 6:return this._dispatcher.publish(In,n),[3,16];case 7:return this.playbackState=jn,[3,16];case 8:return this.playbackState=this._stopped?$n:Fn,[3,16];case 9:return this._paused=!1,this._stopped=!1,this.isPrimaryPlayer=!0,this.playbackState=Kn,[3,16];case 10:return l=this._targetElement.buffered,this.handleBufferStart(),1===l.length&&0===l.start(0)&&(this.currentBufferedProgress=Math.round(l.end(0)/this.currentPlaybackDuration*100)),[3,16];case 11:return this._stopped?this.playbackState=$n:this._paused?this.playbackState=Fn:this.playbackState=Kn,[3,16];case 12:return this.playbackState===Fn?this._paused=!0:this.playbackState===$n&&(this._stopped=!0),this.playbackState=Vn,[3,16];case 13:return this._dispatcher.publish(Nn,{currentPlaybackDuration:this.currentPlaybackDuration,currentPlaybackTime:this.currentPlaybackTime,currentPlaybackTimeRemaining:this.currentPlaybackTimeRemaining}),this._calculatePlaybackProgress(),this._buffer&&(this._buffer.currentTime=this.currentPlaybackTime),[3,16];case 14:return this._dispatcher.publish(xn,n),[3,16];case 15:return this.playbackState=Hn,[3,16];case 16:return[2]}}))}))},BasePlayer.prototype.handleBufferStart=function(){var t=this._targetElement;void 0!==this._initialBufferPosition||t.paused||0===t.buffered.length||(this._initialBufferPosition=t.buffered.start(0),Pt.debug("BasePlayer.handleBufferStart: setting initial buffer position ",this._initialBufferPosition))},BasePlayer.prototype.handleSmartPlay=function(){if(this._targetElement&&this.nowPlayingItem){var t=this.nowPlayingItem;t&&t.playEvent&&!t.playEvent.isDone&&!this._hasSmartPlayed&&(Pt.debug("BasePlayer.handleSmartPlay is resuming playCursor"),this._targetElement.currentTime=t.playEvent.playCursorInSeconds),this._hasSmartPlayed=!0}},BasePlayer.prototype.pause=function(t){return void 0===t&&(t={}),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this._waitForPendingPlay()];case 1:return n.sent(),this.isPlaying?[4,this._pauseMedia()]:[2];case 2:return n.sent(),this._paused=!0,this.dispatch(er.playbackPause,__assign({position:this.currentPlaybackTime},t)),[2]}}))}))},BasePlayer.prototype.play=function(t){return void 0===t&&(t=!0),__awaiter(this,void 0,void 0,(function(){var n,l,d=this;return __generator(this,(function(p){switch(p.label){case 0:if(Pt.debug("BasePlayer.play()"),!this.nowPlayingItem)return[2];p.label=1;case 1:return p.trys.push([1,3,,4]),n=function(){Pt.debug("BasePlayer.play dispatching playbackPlay"),d.dispatch(er.playbackPlay,{userInitiated:t,position:d.currentPlaybackTime})},[4,this._playMedia(n)];case 2:return p.sent(),[3,4];case 3:return"NotAllowedError"!==(l=p.sent()).name&&"NotSupportedError"!==l.name||Pt.error("BasePlayer.play() rejected due to",l),[2];case 4:return[2]}}))}))},BasePlayer.prototype.preload=function(){return this._loadMedia()},BasePlayer.prototype.showPlaybackTargetPicker=function(){this.playbackTargetAvailable&&this._targetElement.webkitShowPlaybackTargetPicker()},BasePlayer.prototype.dispatch=function(t,n){void 0===n&&(n={}),void 0===n.item&&(n.item=this.nowPlayingItem),void 0===n.position&&(n.position=this.currentPlaybackTime),n.isPlaying=this.isPlaying,this._dispatcher.publish(t,n)},BasePlayer.prototype.tsidChanged=function(t){void 0!==t&&""!==t&&(this.isPrimaryPlayer=t===this._serial)},BasePlayer.prototype._waitForPendingPlay=function(){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(n){switch(n.label){case 0:if(!this._playPromise)return[2];n.label=1;case 1:return n.trys.push([1,3,4,5]),[4,this._playPromise];case 2:return n.sent(),[3,5];case 3:return t=n.sent(),Pt.error("BasePlayer._waitForPendingPlay playPromise rejected",t),[3,5];case 4:return this._playPromise=void 0,[7];case 5:return[2]}}))}))},BasePlayer.prototype._loadMedia=function(){return Pt.debug("BasePlayer._loadMedia",this._targetElement),this._targetElement.load(),Promise.resolve()},BasePlayer.prototype._pauseMedia=function(){return this._targetElement.pause(),Promise.resolve()},BasePlayer.prototype._playAssetURL=function(t,n){Pt.debug("BasePlayer._playAssetURL",t),this._targetElement.src=t;var l=this._loadMedia();return n?(Pt.debug("BasePlayer.loadOnly"),l):this._playMedia()},BasePlayer.prototype.playItemFromUnencryptedSource=function(t,n){return this._playAssetURL(t,n)},BasePlayer.prototype._playMedia=function(t){return void 0===t&&(t=cn),__awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return Pt.debug("BasePlayer._playMedia",this._targetElement,this.extension),n=this._targetElement.play(),this._playPromise=n.then(t),[4,n];case 1:return l.sent(),[2]}}))}))},BasePlayer.prototype._setTargetElementTitle=function(t){this.hasMediaElement&&(this._targetElement.title=t)},BasePlayer.prototype._licenseError=function(){this._playPromise=void 0},BasePlayer.prototype._stopMediaElement=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this.hasMediaElement&&(this._targetElement.pause(),this._targetElement.currentTime=0,this._targetElement.removeAttribute("src"),this._targetElement.removeAttribute("title")),[2]}))}))},BasePlayer}();function requiresHlsJs(t){return __awaiter(this,void 0,void 0,(function(){var n,l;return __generator(this,(function(d){switch(d.label){case 0:return null==t?[3,1]:(l=t,[3,3]);case 1:return[4,findKeySystemPreference()];case 2:l=d.sent(),d.label=3;case 3:return[2,void 0!==(n=l)&&n!==et.FAIRPLAY]}}))}))}var Wn=function(){function RTCStreamingTracker(t){this.options=t}return RTCStreamingTracker.prototype.configure=function(t,n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return this.instance=t,[4,loadScript(ur.urls.rtc)];case 1:return n.sent(),[2,this]}}))}))},RTCStreamingTracker.prototype.prepareReportingAgent=function(t){var n;this.clearReportingAgent();var l=t||this.instance.nowPlayingItem,d=l?getDefaultPlayable(l):void 0,p=window.rtc.RTCReportingAgentConfigKeys,h=p.Sender,f=p.ClientName,y=p.ServiceName,v=p.ApplicationName,g=p.ReportingStoreBag,_=p.DeviceName,m={firmwareVersion:this.generateBrowserVersion(),model:this.options.browserName};d&&d.mediaMetrics&&d.mediaMetrics.MediaIdentifier&&(m.MediaIdentifier=d.mediaMetrics.MediaIdentifier),void 0===this._storeBag&&(this._storeBag=this.generateStoreBag());var b=((n={})[h]="HLSJS",n[f]=this.options.clientName,n[y]=this.options.serviceName,n[v]=this.options.applicationName,n[g]=this._storeBag,n[_]=this.options.osVersion,n.userInfoDict=m,n);return Pt.debug("RTC: creating reporting agent with config",b),this.reportingAgent=new window.rtc.RTCReportingAgent(b),Pt.debug("RTC: created reporting agent",this.reportingAgent),this.reportingAgent},RTCStreamingTracker.prototype.shouldConfigure=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,requiresHlsJs()]}))}))},RTCStreamingTracker.prototype.shouldTrackPlayActivity=function(t,n){return!0},RTCStreamingTracker.prototype.cleanup=function(){this.clearReportingAgent()},RTCStreamingTracker.prototype.clearReportingAgent=function(){void 0!==this.reportingAgent&&(this.reportingAgent.destroy(),Pt.debug("RTC: called destroy on reporting agent",this.reportingAgent),this.reportingAgent=void 0)},RTCStreamingTracker.prototype.generateBrowserVersion=function(){return this.options.browserMajorVersion?this.options.browserMajorVersion+"."+(this.options.browserMinorVersion||0):"unknown"},RTCStreamingTracker.prototype.generateStoreBag=function(){var t,n=this.options,l=n.storeBagURL,d=n.clientName,p=n.applicationName,h=n.serviceName,f=n.browserName,y={HLSJSVersion:null===(t=null===window||void 0===window?void 0:window.Hls)||void 0===t?void 0:t.version},v=new window.rtc.RTCStorebag.RTCReportingStoreBag(l,d,h,p,f,y);return Pt.debug("RTC: created store bag",v),v},RTCStreamingTracker}();function createLicenseChallengeBody(t,n,l,d,p){var h,f=l.challenge||de(l.licenseChallenge);return(h=n.isUTS?function(t,n){return void 0===n&&(n="start"),{"extra-server-parameters":t.keyServerQueryParameters,"license-action":n}}(n,t):n.isLiveRadioStation?{event:"beats1"}:function(t,n){return void 0===n&&(n=!1),{adamId:t.songId,isLibrary:t.isCloudItem,"user-initiated":n}}(n,p)).challenge=f,h["key-system"]=d,h.uri=l.keyuri,h}var Yn=function(){function License(){}return License.prototype.fetch=function(t){var n=new Headers({Authorization:"Bearer "+ar.developerToken,Accept:"application/json","Content-Type":"application/json","X-Apple-Music-User-Token":""+ar.musicUserToken});return fetch(this.licenseUrl,{method:"POST",body:JSON.stringify(t),headers:n})},License.prototype.reset=function(){this.licenseUrl=void 0,this.mediaItem=void 0,this.data=void 0,this.initiated=void 0,this.keySystem=void 0,this.startResponse=void 0},License.prototype.start=function(t,n,l,d,p){var h;return void 0===p&&(p=!1),__awaiter(this,void 0,void 0,(function(){var f,y,v,g,_,m;return __generator(this,(function(b){switch(b.label){case 0:this.licenseUrl=t,this.mediaItem=n,this.data=l,this.keySystem=d,this.initiated=p,f=l.isRenewalRequest?"renew":"start",y=createLicenseChallengeBody(f,n,l,d,p),this.startResponse=this.fetch(y),b.label=1;case 1:return b.trys.push([1,4,,5]),[4,this.startResponse];case 2:if(!(v=b.sent()).ok)throw new ke(ke.MEDIA_LICENSE,"Error acquiring license");return[4,v.json()];case 3:if((g=b.sent()).status=null!==(h=g.status)&&void 0!==h?h:g.errorCode,0!==g.status)throw g.message||(g.message=-1004===g.status?ke.DEVICE_LIMIT:ke.MEDIA_LICENSE),(_=ke.serverError(g)).errorCode===ke.PLAYREADY_CBC_ENCRYPTION_ERROR&&hasSessionStorage()&&window.sessionStorage.setItem("mk-playready-cbcs-unsupported","true"),_;return[2,g];case 4:throw m=b.sent(),this.startResponse=void 0,m;case 5:return[2]}}))}))},License.prototype.stop=function(){return __awaiter(this,void 0,void 0,(function(){var t,n,l;return __generator(this,(function(d){switch(d.label){case 0:if(!this.startResponse)return[3,4];d.label=1;case 1:return d.trys.push([1,3,,4]),[4,this.startResponse];case 2:return d.sent(),[3,4];case 3:return d.sent(),[3,4];case 4:if(!this.mediaItem||!this.data)return[2];if(!this.mediaItem.isUTS)return[2];t=createLicenseChallengeBody("stop",this.mediaItem,this.data,this.keySystem,this.initiated),n=this.fetch(t),this.reset(),d.label=5;case 5:return d.trys.push([5,7,,8]),[4,n];case 6:return d.sent(),[3,8];case 7:return l=d.sent(),Pt.warn("license.stop request error",l),[3,8];case 8:return[2]}}))}))},License}();function processLicenseError(t,n,l){var d=t.errorCode===ke.PLAYREADY_CBC_ENCRYPTION_ERROR;if(l&&!d)throw t;n.dispatchEvent(tn.playbackLicenseError,t)}var qn=function(t){function KeySession(){var n=t.call(this,[tn.playbackLicenseError,tn.playbackSessionError])||this;return n.initiated=!0,n.isLibrary=!1,n.keySystem=et.FAIRPLAY,n._storage=window.sessionStorage,n.boundDispatchKeyError=n.dispatchKeyError.bind(n),n.boundDispatchSessionError=n.dispatchSessionError.bind(n),n.boundHandleSessionCreation=n.handleSessionCreation.bind(n),n.boundStartLicenseSession=n.startLicenseSession.bind(n),n.license=new Yn,n}return __extends(KeySession,t),Object.defineProperty(KeySession.prototype,"extID",{get:function(){if(this.extURI)return this.extURI.replace("data:;base64,","")},enumerable:!0,configurable:!0}),Object.defineProperty(KeySession.prototype,"isFairplay",{get:function(){return this.keySystem===et.FAIRPLAY},enumerable:!0,configurable:!0}),Object.defineProperty(KeySession.prototype,"isPlayReady",{get:function(){return this.keySystem===et.PLAYREADY},enumerable:!0,configurable:!0}),Object.defineProperty(KeySession.prototype,"isWidevine",{get:function(){return this.keySystem===et.WIDEVINE},enumerable:!0,configurable:!0}),KeySession.prototype.acquirePlaybackLicense=function(t,n,l){return void 0===l&&(l=this.initiated),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(d){switch(d.label){case 0:if(!this.keyServerURL||!this.developerToken||!this.userToken)return[2];d.label=1;case 1:return d.trys.push([1,3,,4]),[4,this.license.start(this.keyServerURL,this.item,{challenge:n,keyuri:t},this.keySystem,this.initiated)];case 2:return[2,d.sent()];case 3:return processLicenseError(d.sent(),this,l),[3,4];case 4:return[2]}}))}))},KeySession.prototype.cancelPendingRenewal=function(){this._pendingRenewal&&(clearTimeout(this._pendingRenewal),this._pendingRenewal=void 0)},KeySession.prototype.startLicenseSession=function(t){var n,l=this;Pt.debug("Starting License Session",t);var d=t.message,p=t.target;if(this.isPlayReady){var h=String.fromCharCode.apply(null,new Uint16Array(d.buffer||d)),f=(new DOMParser).parseFromString(h,"application/xml");n=f.getElementsByTagName("Challenge")[0].childNodes[0].nodeValue}else n=de(new Uint8Array(d));return this.acquirePlaybackLicense(p.extURI||this.extURI,n).then((function(t){l._handleLicenseJson(t,p,n)}))},KeySession.prototype.setKeyURLs=function(t){this.keyCertURL=t[this.isFairplay?"hls-key-cert-url":"widevine-cert-url"],this.keyServerURL=t["hls-key-server-url"]},KeySession.prototype.dispatchKeyError=function(t){console.error(ke.MEDIA_KEY+" error in dispatchKeyError:",t),this.dispatchEvent(tn.playbackSessionError,new ke(ke.MEDIA_KEY,t))},KeySession.prototype.dispatchSessionError=function(t){this.dispatchEvent(tn.playbackSessionError,new ke(ke.MEDIA_SESSION,t))},KeySession.prototype.loadCertificateBuffer=function(){return __awaiter(this,void 0,void 0,(function(){var t,n,l,d,p,h,f,y,v,g,_,m,b;return __generator(this,(function(P){switch(P.label){case 0:if(!this.keyCertURL)return[2,Promise.reject(new ke(ke.MEDIA_SESSION,"No certificate URL"))];if((t=document.createElement("a")).href=this.keyCertURL,n=Date.now(),l=(""+t.hostname+t.pathname).replace(/[^a-z0-9.]/gi,"."),d=this._storage.getItem(l),p=parseInt(this._storage.getItem("com.ai.mk.vmcc.exp")||"",10),d&&p&&p>n){for(h=new Uint8Array(d.length),f=d.length;f--;)h[f]=d.charCodeAt(f);return[2,h.buffer]}return[4,fetch(this.keyCertURL+"?t="+Date.now())];case 1:return y=P.sent(),v=y.headers.get("cache-control"),g=86400,v&&ft.test(v)&&(_=v.match(ft))&&_[1]&&(g=parseInt(_[1],10)),[4,y.arrayBuffer()];case 2:return m=P.sent(),b=String.fromCharCode.apply(String,new Uint8Array(m)),/^\<\?xml/.test(b)?[2,Promise.reject(new ke(ke.MEDIA_CERTIFICATE,"Invalid certificate."))]:(this._storage.setItem(l,b),this._storage.setItem("com.ai.mk.vmcc.exp",(n+1e3*g).toString()),[2,m])}}))}))},KeySession.prototype.handleSessionCreation=function(t){return __awaiter(this,void 0,void 0,(function(){var n=this;return __generator(this,(function(l){return[2,this.createSession(t).catch((function(t){n.dispatchSessionError(t)}))]}))}))},KeySession.prototype._handleLicenseJson=function(t,n,l){if(Pt.debug("handleLicenseResponse",t),null==t?void 0:t.license){var d=ue(t.license);return n.update(d)}},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",void 0)],KeySession.prototype,"startLicenseSession",null),KeySession}(he),Gn=/^(?:.*)(skd:\/\/.+)$/i,Qn=function(t){function WebKitSession(){return null!==t&&t.apply(this,arguments)||this}return __extends(WebKitSession,t),WebKitSession.prototype.attachMedia=function(t,n){return this.target=t,t.addEventListener("webkitneedkey",this.boundHandleSessionCreation,!1),t.addEventListener("webkitkeyerror",this.boundDispatchKeyError),t},WebKitSession.prototype.detachMedia=function(t){t&&(t.removeEventListener("webkitneedkey",this.boundHandleSessionCreation,!1),t.removeEventListener("webkitkeyerror",this.boundDispatchKeyError))},WebKitSession.prototype.destroy=function(){Pt.debug("FPS destroy"),this.detachMedia(this.target),this.session&&(this.session.removeEventListener("webkitkeyerror",this.boundDispatchKeyError),this.session.removeEventListener("webkitkeymessage",this.boundStartLicenseSession))},WebKitSession.prototype.createSession=function(t){var n=this;Pt.debug("FPS createSession",t);var l=t.initData,d=t.target,p=this._extractAssetId(l);if(Pt.debug("extURI",p),!d.webkitKeys){var h=new window.WebKitMediaKeys(this.keySystem);d.webkitSetMediaKeys(h)}return this.loadCertificateBuffer().then((function(t){var h=n._concatInitDataIdAndCertificate(l,p,t),f="VIDEO"===d.tagName?rn.AVC1:rn.MP4,y=d.webkitKeys.createSession(f,h);n.session=y,y.extURI=p,y.addEventListener("webkitkeyerror",n.boundDispatchKeyError),y.addEventListener("webkitkeymessage",n.boundStartLicenseSession)}))},WebKitSession.prototype._extractAssetId=function(t){var n=String.fromCharCode.apply(null,new Uint16Array(t.buffer||t)),l=n.match(Gn);return l&&l.length>=2&&(n=l[1]),Pt.debug("Extracted assetId from EXT-X-KEY URI",n),n},WebKitSession.prototype._concatInitDataIdAndCertificate=function(t,n,l){"string"==typeof n&&(n=le(n)),l=new Uint8Array(l);var d=0,p=new ArrayBuffer(t.byteLength+4+n.byteLength+4+l.byteLength),h=new DataView(p);new Uint8Array(p,d,t.byteLength).set(t),d+=t.byteLength,h.setUint32(d,n.byteLength,!0),d+=4;var f=new Uint8Array(p,d,n.byteLength);return f.set(n),d+=f.byteLength,h.setUint32(d,l.byteLength,!0),d+=4,new Uint8Array(p,d,l.byteLength).set(l),new Uint8Array(p,0,p.byteLength)},WebKitSession}(qn);function bindSessionData(t,n){t.developerToken=ar.developerToken,t.userToken=ar.musicUserToken,t.item=n,t.adamId=n.songId,t.isLibrary=n.isCloudItem,t.setKeyURLs(n.keyURLs)}var Jn=tn.audioTracksSwitched,Xn=tn.audioTracksUpdated,Zn=tn.textTracksSwitched,eo=tn.textTracksUpdated,to=function(t){function HlsJsTracks(n){var l=t.call(this,[Jn,Xn,Zn,eo])||this;return l.session=n,l._audioTracks=[],l._textTracks=[],l._hlsAudioTracks=[],l.session.on(window.Hls.Events.MANIFEST_LOADED,l.handleManifestLoaded.bind(l)),l.session.on(window.Hls.Events.AUDIO_TRACK_SWITCHED,l.handleAudioTrackSwitched.bind(l)),l.session.on(window.Hls.Events.SUBTITLE_TRACK_SWITCH,l.handleSubtitleTrackSwitch.bind(l)),l}return __extends(HlsJsTracks,t),Object.defineProperty(HlsJsTracks.prototype,"audioTracks",{get:function(){return this._audioTracks},enumerable:!0,configurable:!0}),Object.defineProperty(HlsJsTracks.prototype,"textTracks",{get:function(){return this._textTracks},enumerable:!0,configurable:!0}),Object.defineProperty(HlsJsTracks.prototype,"audioTrack",{set:function(t){this.session&&t&&t.id&&(this.session.audioSelectedPersistentID=t.id)},enumerable:!0,configurable:!0}),Object.defineProperty(HlsJsTracks.prototype,"textTrack",{set:function(t){var n;this.session.subtitleSelectedPersistentID=null!==(n=null==t?void 0:t.id)&&void 0!==n?n:-1},enumerable:!0,configurable:!0}),HlsJsTracks.prototype.selectForcedTrack=function(){var t=this.session;if(null==t?void 0:t.audioTracks){var n=this.session.audioTracks.filter((function(n){return n.id===t.audioTrack})),l=n&&n.length&&n[0];if(l){var d,p=t.subtitleMediaOptions.filter((function(t){return 0===t.MediaSelectionOptionsDisplaysNonForcedSubtitles&&t.MediaSelectionOptionsExtendedLanguageTag===l.lang})),h=null==p?void 0:p[0];return h&&(Pt.debug("hlsjsTracks: found forced track for "+h.MediaSelectionOptionsExtendedLanguageTag),t.subtitleSelectedPersistentID=h.MediaSelectionOptionsPersistentID,d=this.normalizeTextTrack(h)),d}}},HlsJsTracks.prototype.audioTracksUpdated=function(t,n){var l,d=n&&n.audioMediaSelectionGroup&&n.audioMediaSelectionGroup.MediaSelectionGroupOptions||[];window.hlsSession=this.session;var p=d.map(this.normalizeAudioTrack,this);this._audioTracks=p,this._hlsAudioTracks=null!==(l=null==n?void 0:n.audioTracks)&&void 0!==l?l:[],this.dispatchEvent(Xn,p)},HlsJsTracks.prototype.handleAudioTrackSwitched=function(t,n){var l=n.id,d=this._hlsAudioTracks.find((function(t){return t.id===l}));this.dispatchEvent(Jn,{selectedId:this.session.audioSelectedPersistentID,hlsTrack:d})},HlsJsTracks.prototype.handleManifestLoaded=function(t,n){this.audioTracksUpdated(t,n),this.subtitleTracksUpdated(t,n)},HlsJsTracks.prototype.handleSubtitleTrackSwitch=function(t,n){this.dispatchEvent(Zn,n)},HlsJsTracks.prototype.subtitleTracksUpdated=function(t,n){var l=this,d=n&&n.subtitleMediaSelectionGroup&&n.subtitleMediaSelectionGroup.MediaSelectionGroupOptions||[],p=Array();d.forEach((function(t){0!==t.MediaSelectionOptionsDisplaysNonForcedSubtitles&&p.push(l.normalizeTextTrack(t))})),this._textTracks=p,this.dispatchEvent(eo,p)},HlsJsTracks.prototype.normalizeAudioTrack=function(t){var n,l="public.accessibility.describes-video"===(null===(n=t.MediaSelectionOptionsTaggedMediaCharacteristics)||void 0===n?void 0:n[0])?"description":"main";return __assign(__assign({},this.normalizeSelectionOption(t)),{enabled:!1,kind:l})},HlsJsTracks.prototype.normalizeTextTrack=function(t){var n,l;return l=(null===(n=t.MediaSelectionOptionsTaggedMediaCharacteristics)||void 0===n?void 0:n.includes("public.accessibility.describes-music-and-sound"))||"clcp"===t.MediaSelectionOptionsMediaType?"captions":"subtitles",__assign(__assign({},this.normalizeSelectionOption(t)),{mode:"disabled",kind:l})},HlsJsTracks.prototype.normalizeSelectionOption=function(t){return{id:t.MediaSelectionOptionsPersistentID,label:t.MediaSelectionOptionsName,language:t.MediaSelectionOptionsExtendedLanguageTag}},HlsJsTracks}(he),ro={};ro[et.FAIRPLAY]="fairplaystreaming",ro[et.PLAYREADY]="playready",ro[et.WIDEVINE]="widevine";var io=tn.levelUpdated,no=tn.manifestParsed,oo=tn.playbackLicenseError,ao=tn.sessionCreated,so=function(n){function HlsJsMediaExtension(t,l){var d=n.call(this,[io,no,oo,ao])||this;return d.video=t,d.initiated=!0,void 0!==l&&void 0!==l.playActivity&&(d.rtcTracker=l.playActivity.getTrackerByType(Wn)),d.license=new Yn,d}return __extends(HlsJsMediaExtension,n),HlsJsMediaExtension.prototype.init=function(){return __awaiter(this,void 0,void 0,(function(){var t,n;return __generator(this,(function(l){switch(l.label){case 0:return[4,findKeySystemPreference()];case 1:return t=l.sent(),this._keySystem=t,void 0===t?[2]:[4,requiresHlsJs(t)];case 2:if(!l.sent())return[3,7];l.label=3;case 3:return l.trys.push([3,5,,6]),[4,loadScript(ur.urls.hls)];case 4:return l.sent(),[3,6];case 5:throw n=l.sent(),Pt.error("HLS.js extension failed to load script "+ur.urls.hls,n),n;case 6:return[3,8];case 7:return[2,this.setSession(this.video,t)];case 8:return[2]}}))}))},Object.defineProperty(HlsJsMediaExtension.prototype,"hasMediaSession",{get:function(){return void 0!==this.session},enumerable:!0,configurable:!0}),Object.defineProperty(HlsJsMediaExtension.prototype,"hasMediaKeySupport",{get:function(){return hasMediaKeySupport()},enumerable:!0,configurable:!0}),Object.defineProperty(HlsJsMediaExtension.prototype,"extURI",{set:function(t){this.session.extURI=t},enumerable:!0,configurable:!0}),Object.defineProperty(HlsJsMediaExtension.prototype,"isFairplay",{get:function(){return this.session.isFairplay},enumerable:!0,configurable:!0}),HlsJsMediaExtension.prototype.cancelPendingRenewal=function(){},HlsJsMediaExtension.prototype.destroy=function(t){this.destroySession(),asAsync(this.license.stop())},HlsJsMediaExtension.prototype.destroySession=function(){this.session&&(this.session.license&&asAsync(this.session.license.stop()),this.session.destroy&&(this.session.stopLoad&&(Pt.debug("session.stopLoad()"),this.session.stopLoad()),this.session.detachMedia&&(Pt.debug("session.detachMedia()"),this.session.detachMedia()),this.video.src="",Pt.debug("session.destroy()"),this.session.destroy()))},HlsJsMediaExtension.prototype.setMediaItem=function(n){this.mediaItem=n,n.playbackType!==t.PlaybackType.preview&&(this.isFairplay?bindSessionData(this.session,n):(this.licenseServerUrl=n.keyURLs["hls-key-server-url"],this.session.setProtectionData({widevine:{serverCertUrl:n.keyURLs["widevine-cert-url"]}}),this.songId=n.songId))},HlsJsMediaExtension.prototype.setCurrentSrc=function(t){var n=this,l=this._keySystem;if(l){if(this.setSession(this.video,l),l===et.FAIRPLAY)return this.video.src=t,void this.video.addEventListener("loadedmetadata",(function(t){n.mediaItem&&(n.mediaItem.state=pr.ready),n.dispatchEvent(no)}));var d={platformInfo:{requiresCDMAttachOnStart:!0}};if(this.rtcTracker){var p=this.rtcTracker.prepareReportingAgent(this.mediaItem);void 0!==p&&(d.appData={reportingAgent:p})}Pt.debug("RTC: loadSource with load options",d),this.session.loadSource(t,d),this.session.attachMedia(this.video)}},HlsJsMediaExtension.prototype.setSession=function(t,n){if(n===et.FAIRPLAY)this.session=new Qn,this.session.attachMedia(t);else{var l=new window.Hls({clearMediaKeysOnPromise:!1,customTextTrackCueRenderer:!0,debug:!!Pt.enabled,enablePerformanceLogging:!!Pt.enabled,enablePlayReadyKeySystem:!0,enableRtcReporting:void 0!==this.rtcTracker,keySystemPreference:ro[n],useMediaKeySystemAccessFilter:!0}),d=window.Hls.Events,p=d.ERROR,h=d.MANIFEST_PARSED,f=d.KEY_REQUEST_STARTED,y=d.LICENSE_CHALLENGE_CREATED,v=d.LEVEL_SWITCHED;l.on(p,this.handleHlsError),l.on(h,this.handleManifestParsed),l.on(f,this.handleKeyRequestStarted),l.on(y,this.handleLicenseChallengeCreated),l.on(v,this.handleLevelSwitched),this.hlsJsTracks=new to(l),this.session=l}this.dispatchEvent(ao)},HlsJsMediaExtension.prototype.handleLevelSwitched=function(t,n){var l,d,p=n.level;if(p){var h=null===(l=this.levels)||void 0===l?void 0:l.find((function(t){return t.persistentId===p}));h&&(null===(d=this.currentLevel)||void 0===d?void 0:d.persistentId)!==(null==h?void 0:h.persistentId)&&(this.currentLevel=h,this.dispatchEvent(io,h))}},HlsJsMediaExtension.prototype.handleHlsError=function(t,n){if(Pt.warn("HLS.js error",n),n.fatal)throw this.session.destroy(),new ke(ke.UNSUPPORTED_ERROR,n.reason)},HlsJsMediaExtension.prototype.handleManifestParsed=function(t,n){var l;this.levels=null!==(l=n.levels)&&void 0!==l?l:[],this.mediaItem.state=pr.ready,this.dispatchEvent(no)},HlsJsMediaExtension.prototype.handleKeyRequestStarted=function(t,n){this.session.generateKeyRequest(n.keyuri,{})},HlsJsMediaExtension.prototype.handleLicenseChallengeCreated=function(t,n){return __awaiter(this,void 0,void 0,(function(){var t,l,d;return __generator(this,(function(p){switch(p.label){case 0:return p.trys.push([0,2,,3]),[4,this.license.start(this.licenseServerUrl,this.mediaItem,n,this._keySystem,this.initiated)];case 1:return(null==(t=p.sent())?void 0:t.license)&&(l={license:ue(t.license),statusCode:t.status},(d=t["renew-after"])&&(l.renewalDate=new Date(Date.now()+1e3*d)),this.session.setLicenseResponse(n.keyuri,l)),[3,3];case 2:return processLicenseError(p.sent(),this,this.initiated),[3,3];case 3:return[2]}}))}))},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],HlsJsMediaExtension.prototype,"handleLevelSwitched",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],HlsJsMediaExtension.prototype,"handleHlsError",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],HlsJsMediaExtension.prototype,"handleManifestParsed",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],HlsJsMediaExtension.prototype,"handleKeyRequestStarted",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",Promise)],HlsJsMediaExtension.prototype,"handleLicenseChallengeCreated",null),HlsJsMediaExtension}(he);function restoreSelectedTrack(t,n){Pt.debug("MEDIA_TRACKS restoreSelectedTrack");var l=t.getPersistedTrack(),d=t.fields,p=n.currentTrack;if(l)if(p&&trackEquals(p,l,d))Pt.debug("MEDIA_TRACKS persisted track is equal to current track, not setting");else{var h=n.tracks;if(h&&h.length)for(var f=0;f<h.length;f++){var y=h[f];if(Pt.debug("MEDIA_TRACKS testing track "+y.label+" against persisted track "+JSON.stringify(l)),trackEquals(y,l,d)){Pt.debug("MEDIA_TRACKS found matching track "+y.label),n.currentTrack=y;break}}}else Pt.debug("MEDIA_TRACKS no persisted track")}function trackEquals(t,n,l){for(var d=!0,p=0;p<l.length;p++){var h=l[p];if(t[h]!==n[h]){d=!1;break}}return d}var uo=function(){function TrackPersistence(t,n){this.storageKey=t,this.fields=n}return TrackPersistence.prototype.getPersistedTrack=function(){if(!window||!window.localStorage)return!1;var t=window.localStorage.getItem(this.storageKey)||"";try{return JSON.parse(t)}catch(e){return Pt.warn("MEDIA_TRACK could not parse persisted value "+t),!1}},TrackPersistence.prototype.setPersistedTrack=function(t){if(window&&window.localStorage)if(Pt.debug("MEDIA_TRACK setPersistedTrack "+t.language+","+t.label+","+t.kind+" with keys "+this.fields),t){var n=JSON.stringify(this.extractFieldValuesFromTrack(t));Pt.debug("MEDIA_TRACK Extracted values "+n),window.localStorage.setItem(this.storageKey,n)}else window.localStorage.setItem(this.storageKey,"")},TrackPersistence.prototype.extractFieldValuesFromTrack=function(t){var n={};return this.fields.forEach((function(l){var d=t[l];null==d&&Pt.warn("MEDIA_TRACK No value for field "+l+" on track "+JSON.stringify(t)),n[l]=d})),n},TrackPersistence}(),co=nr.audioTrackAdded,lo=nr.audioTrackChanged,po=nr.audioTrackRemoved,ho=tn.audioTracksSwitched,fo=tn.audioTracksUpdated,yo=function(){function AudioTrackManager(t,n,l){if(this.mediaElement=t,this.dispatcher=n,this.extensionTracks=l,this._extensionTracks=[],this.trackPersistence=new uo("mk-audio-track",["label","language","kind"]),this.extensionTracks){Pt.debug("MEDIA_TRACK Initializing audio track manager for hls track events"),this.onExtensionAudioTracksUpdated=this.onExtensionAudioTracksUpdated.bind(this),this.onExtensionAudioTrackSwitched=this.onExtensionAudioTrackSwitched.bind(this);var d=this.extensionTracks;d.addEventListener(fo,this.onExtensionAudioTracksUpdated),d.addEventListener(ho,this.onExtensionAudioTrackSwitched)}else{if(!t.audioTracks)return;Pt.debug("MEDIA_TRACK Initializing audio track manager for native track events"),this.onAudioTrackAdded=this.onAudioTrackAdded.bind(this),this.onAudioTrackChanged=this.onAudioTrackChanged.bind(this),this.onAudioTrackRemoved=this.onAudioTrackRemoved.bind(this),t.audioTracks.addEventListener("addtrack",this.onAudioTrackAdded),t.audioTracks.addEventListener("change",this.onAudioTrackChanged),t.audioTracks.addEventListener("removetrack",this.onAudioTrackRemoved)}}return Object.defineProperty(AudioTrackManager.prototype,"currentTrack",{get:function(){return this.tracks.find((function(t){return t.enabled}))},set:function(t){t&&(Pt.debug("MEDIA_TRACK Setting audio track "+t.label),this.extensionTracks?(Pt.debug("MEDIA_TRACK Setting track on extension "+t.id+"-"+t.label),this.extensionTracks.audioTrack=t):t.enabled=!0,this.trackPersistence.setPersistedTrack(t))},enumerable:!0,configurable:!0}),Object.defineProperty(AudioTrackManager.prototype,"tracks",{get:function(){return this.extensionTracks?this._extensionTracks||this.extensionTracks.audioTracks||[]:Array.from(this.mediaElement.audioTracks)},enumerable:!0,configurable:!0}),AudioTrackManager.prototype.destroy=function(){if(this.extensionTracks){var t=this.extensionTracks;t.removeEventListener(fo,this.onExtensionAudioTracksUpdated),t.removeEventListener(ho,this.onExtensionAudioTrackSwitched)}else{if(!this.mediaElement.audioTracks)return;this.mediaElement.audioTracks.removeEventListener("addtrack",this.onAudioTrackAdded),this.mediaElement.audioTracks.removeEventListener("change",this.onAudioTrackChanged),this.mediaElement.audioTracks.removeEventListener("removetrack",this.onAudioTrackRemoved)}},AudioTrackManager.prototype.restoreSelectedTrack=function(){return restoreSelectedTrack(this.trackPersistence,this)},AudioTrackManager.prototype.onExtensionAudioTracksUpdated=function(t){Pt.debug("MEDIA_TRACK Extension audio tracks updated "+JSON.stringify(t)),this._extensionTracks=t,this.restoreSelectedTrack(),this.dispatcher.publish(co,t)},AudioTrackManager.prototype.onExtensionAudioTrackSwitched=function(t){if(Pt.debug("MEDIA_TRACK Extension audio track switched "+JSON.stringify(t)),this._extensionTracks){this._extensionTracks.forEach((function(n){n.enabled=t.selectedId===n.id}))}this.dispatcher.publish(lo,t)},AudioTrackManager.prototype.onAudioTrackAdded=function(t){var n,l,d,p;n=t.track,l=this.trackPersistence,d=this,(p=l.getPersistedTrack())&&trackEquals(n,p,l.fields)&&(Pt.debug("MEDIA_TRACK onTrackAdded with track that matches persisted track "+n.label),d.currentTrack=n),this.dispatcher.publish(co,t)},AudioTrackManager.prototype.onAudioTrackChanged=function(t){this.dispatcher.publish(lo,t)},AudioTrackManager.prototype.onAudioTrackRemoved=function(t){this.dispatcher.publish(po,t)},AudioTrackManager}(),vo=createCommonjsModule((function(t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.isValidPercentValue=function(t){return"number"==typeof t&&t>=0&&t<=100},n.isValidAlignSetting=function(t){return"string"==typeof t&&["start","center","end","left","right","middle"].includes(t)},n.isValidDirectionSetting=function(t){return"string"==typeof t&&["","rl","lr"].includes(t)},n.isValidLineAndPositionSetting=function(t){return"number"==typeof t||"auto"===t},n.isValidLineAlignSetting=function(t){return"string"==typeof t&&["start","center","end"].includes(t)},n.isValidPositionAlignSetting=function(t){return"string"==typeof t&&["line-left","center","line-right","auto","left","start","middle","end","right"].includes(t)},n.isValidScrollSetting=function(t){return["","up"].includes(t)}}));unwrapExports(vo);vo.isValidPercentValue,vo.isValidAlignSetting,vo.isValidDirectionSetting,vo.isValidLineAndPositionSetting,vo.isValidLineAlignSetting,vo.isValidPositionAlignSetting,vo.isValidScrollSetting;var go=createCommonjsModule((function(t,n){Object.defineProperty(n,"__esModule",{value:!0});const l={"&amp;":"&","&lt;":"<","&gt;":">","&lrm;":"‎","&rlm;":"‏","&nbsp;":" "},d={c:"span",i:"i",b:"b",u:"u",ruby:"ruby",rt:"rt",v:"span",lang:"span"},p={v:"title",lang:"lang"},h={rt:"ruby"},f={"text-combine-upright":"-webkit-text-combine:horizontal; text-orientation: mixed;"};class ParserUtility{static parseTimeStamp(t){function computeSeconds(t){const[n,l,d,p]=t.map(t=>t?parseInt(""+t):0);return 3600*n+60*l+d+p/1e3}const n=/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/.exec(t);return n?n[3]?computeSeconds([n[1],n[2],n[3].substring(1),n[4]]):parseInt(n[1])>59?computeSeconds([n[1],n[2],null,n[4]]):computeSeconds([null,n[1],n[2],n[4]]):null}static parseContent(t,n,y){let v=n.text;function nextToken(){if(!v)return null;const t=/^([^<]*)(<[^>]+>?)?/.exec(v);return n=t[1]?t[1]:t[2],v=v.substr(n.length),n;var n}function unescape1(t){return l[t]}function unescape(t){return t.replace(/&(amp|lt|gt|lrm|rlm|nbsp);/g,unescape1)}function shouldAdd(t,n){return!h[n.dataset.localName]||h[n.dataset.localName]===t.dataset.localName}function createElement(n,l,h){const v=d[n];if(!v)return null;const g=t.document.createElement(v);g.dataset.localName=v;const _=p[n];if(_&&h&&(g[_]=h.trim()),l)if(y[l]){const t=function(t){let n="";for(const l in t)n+=f[l]?f[l]:l+":"+t[l]+";";return n}(y[l]);g.setAttribute("style",t)}else console.info(`WebVTT: parseContent: Style referenced, but no style defined for '${l}'!`);return g}const g=t.document.createElement("div"),_=[];let m,b,P=g;for(;null!==(m=nextToken());)if("<"!==m[0])P.appendChild(t.document.createTextNode(unescape(m)));else{if("/"===m[1]){_.length&&_[_.length-1]===m.substr(2).replace(">","")&&(_.pop(),P=P.parentNode);continue}const n=ParserUtility.parseTimeStamp(m.substr(1,m.length-2));let l;if(n){l=t.document.createProcessingInstruction("timestamp",n.toString()),P.appendChild(l);continue}if(b=/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/.exec(m),!b)continue;if(l=createElement(b[1],b[2],b[3]),!l)continue;if(!shouldAdd(P,l))continue;b[2],_.push(b[1]),P.appendChild(l),P=l}return g}}n.default=ParserUtility}));unwrapExports(go);var _o=createCommonjsModule((function(t,n){var d=l&&l.__decorate||function(t,n,l,d){var p,h=arguments.length,f=h<3?n:null===d?d=Object.getOwnPropertyDescriptor(n,l):d;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)f=Reflect.decorate(t,n,l,d);else for(var y=t.length-1;y>=0;y--)(p=t[y])&&(f=(h<3?p(f):h>3?p(n,l,f):p(n,l))||f);return h>3&&f&&Object.defineProperty(n,l,f),f};Object.defineProperty(n,"__esModule",{value:!0});let p=class{constructor(t,n,l){this._id="",this._pauseOnExit=!1,this._region=null,this._vertical="",this._snapToLines=!0,this._line="auto",this._lineAlign="start",this._position=50,this._positionAlign="center",this._size=50,this._align="center",this.hasBeenReset=!1,this._startTime=t,this._endTime=n,this._text=l}get id(){return this._id}set id(t){this._id=""+t}get pauseOnExit(){return this._pauseOnExit}set pauseOnExit(t){this._pauseOnExit=!!t}get startTime(){return this._startTime}set startTime(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number: "+t);this._startTime=t,this.hasBeenReset=!0}get endTime(){return this._endTime}set endTime(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number: "+t);this._endTime=t,this.hasBeenReset=!0}get text(){return this._text}set text(t){this._text=""+t,this.hasBeenReset=!0}get region(){return this._region}set region(t){this._region=t,this.hasBeenReset=!0}get vertical(){return this._vertical}set vertical(t){if(!vo.isValidDirectionSetting(t))throw new SyntaxError("An invalid or illegal string was specified for vertical: "+t);this._vertical=t,this.hasBeenReset=!0}get snapToLines(){return this._snapToLines}set snapToLines(t){this._snapToLines=!!t,this.hasBeenReset=!0}get line(){return this._line}set line(t){if(!vo.isValidLineAndPositionSetting(t))throw new SyntaxError("An invalid number or illegal string was specified for line: "+t);this._line=t,this.hasBeenReset=!0}get lineAlign(){return this._lineAlign}set lineAlign(t){if(!vo.isValidLineAlignSetting(t))throw new SyntaxError("An invalid or illegal string was specified for lineAlign: "+t);this._lineAlign=t,this.hasBeenReset=!0}get position(){return this._position}set position(t){if(!vo.isValidLineAndPositionSetting(t))throw new Error("Position must be between 0 and 100 or auto: "+t);this._position=t,this.hasBeenReset=!0}get positionAlign(){return this._positionAlign}set positionAlign(t){if(!vo.isValidPositionAlignSetting(t))throw new SyntaxError("An invalid or illegal string was specified for positionAlign: "+t);this._positionAlign=t,this.hasBeenReset=!0}get size(){return this._size}set size(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100: "+t);this._size=t,this.hasBeenReset=!0}get align(){return this._align}set align(t){if(!vo.isValidAlignSetting(t))throw new SyntaxError("An invalid or illegal string was specified for align: "+t);this._align=t,this.hasBeenReset=!0}getCueAsHTML(){return go.default.parseContent(window,this,{})}static create(t){if(!t.hasOwnProperty("startTime")||!t.hasOwnProperty("endTime")||!t.hasOwnProperty("text"))throw new Error("You must at least have start time, end time, and text.");const n=new this(t.startTime,t.endTime,t.text);return Object.keys(t).forEach(l=>{n.hasOwnProperty(l)&&(n[l]=t[l])}),n}static fromJSON(t){return this.create(JSON.parse(t))}toJSON(){const t={};return Object.keys(this).forEach(n=>{this.hasOwnProperty(n)&&"getCueAsHTML"!==n&&"hasBeenReset"!==n&&"displayState"!==n&&(t[n]=this[n])}),t}};p=d([function(t){let n=t;"undefined"!=typeof window&&null!=window.VTTCue&&(n=window.VTTCue,n.create=t.create,n.fromJSON=t.fromJSON,n.prototype.toJSON=t.prototype.toJSON);return n}],p),n.VTTCue=p}));unwrapExports(_o);_o.VTTCue;var mo=createCommonjsModule((function(t,n){var d=l&&l.__decorate||function(t,n,l,d){var p,h=arguments.length,f=h<3?n:null===d?d=Object.getOwnPropertyDescriptor(n,l):d;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)f=Reflect.decorate(t,n,l,d);else for(var y=t.length-1;y>=0;y--)(p=t[y])&&(f=(h<3?p(f):h>3?p(n,l,f):p(n,l))||f);return h>3&&f&&Object.defineProperty(n,l,f),f};Object.defineProperty(n,"__esModule",{value:!0});let p=class{constructor(){this._id="",this._lines=3,this._regionAnchorX=0,this._regionAnchorY=100,this._scroll="",this._viewportAnchorX=0,this._viewportAnchorY=100,this._width=100}get id(){return this._id}set id(t){if("string"!=typeof t)throw new Error("ID must be a string.");this._id=t}get lines(){return this._lines}set lines(t){if("number"!=typeof t)throw new TypeError("Lines must be set to a number.");this._lines=t}get regionAnchorX(){return this._regionAnchorX}set regionAnchorX(t){if(!vo.isValidPercentValue(t))throw new TypeError("RegionAnchorX must be between 0 and 100.");this._regionAnchorX=t}get regionAnchorY(){return this._regionAnchorY}set regionAnchorY(t){if(!vo.isValidPercentValue(t))throw new TypeError("RegionAnchorY must be between 0 and 100.");this._regionAnchorY=t}get scroll(){return this._scroll}set scroll(t){if("string"==typeof t){const n=t.toLowerCase();if(vo.isValidScrollSetting(n))return void(this._scroll=n)}throw new SyntaxError("An invalid or illegal string was specified.")}get viewportAnchorX(){return this._viewportAnchorX}set viewportAnchorX(t){if(!vo.isValidPercentValue(t))throw new TypeError("ViewportAnchorX must be between 0 and 100.");this._viewportAnchorX=t}get viewportAnchorY(){return this._viewportAnchorY}set viewportAnchorY(t){if(!vo.isValidPercentValue(t))throw new TypeError("ViewportAnchorY must be between 0 and 100.");this._viewportAnchorY=t}get width(){return this._width}set width(t){if(!vo.isValidPercentValue(t))throw new TypeError("Width must be between 0 and 100.");this._lines=t}toJSON(){const t={};return Object.keys(this).forEach(n=>{this.hasOwnProperty(n)&&(t[n]=this[n])}),t}static create(t){const n=new this;return Object.keys(t).forEach(l=>{n.hasOwnProperty(l)&&(n[l]=t[l])}),n}static fromJSON(t){return this.create(JSON.parse(t))}};p=d([function(t){let n=t;"undefined"!=typeof window&&null!=window.VTTRegion&&(n=window.VTTRegion,n.create=t.create,n.fromJSON=t.fromJSON,n.prototype.toJSON=t.prototype.toJSON);return n}],p),n.VTTRegion=p}));unwrapExports(mo);mo.VTTRegion;var bo=createCommonjsModule((function(t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.VTTCue=_o.VTTCue,n.VTTRegion=mo.VTTRegion;class ParsingError extends Error{constructor(t,n){super(),this.name="ParsingError",this.code="number"==typeof t?t:t.code,n?this.message=n:t instanceof ParsingError&&(this.message=t.message)}}n.ParsingError=ParsingError,ParsingError.Errors={BadSignature:new ParsingError(0,"Malformed WebVTT signature."),BadTimeStamp:new ParsingError(1,"Malformed time stamp.")};class Settings{constructor(){this.values={}}set(t,n){this.get(t)||""===n||(this.values[t]=n)}get(t,n,l){return"object"==typeof n&&"string"==typeof l?this.has(t)?this.values[t]:n[l]:this.has(t)?this.values[t]:n}has(t){return t in this.values}alt(t,n,l){for(let d=0;d<l.length;++d)if(n===l[d]){this.set(t,n);break}}integer(t,n){/^-?\d+$/.test(n)&&this.set(t,parseInt(n,10))}percent(t,n){if(n.match(/^([\d]{1,3})(\.[\d]*)?%$/))try{const l=parseFloat(n);if(l>=0&&l<=100)return this.set(t,l),!0}catch(Gs){return!1}return!1}}class WebVTTParser{constructor(t,n,l){this.window=t,this.state="INITIAL",this.buffer="",this.decoder=n||new TextDecoder("utf8"),this.regionList=[],this.onStylesParsedCallback=l,this._styles={}}static StringDecoder(){return{decode:t=>{if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}}reportOrThrowError(t){if(!(t instanceof ParsingError&&"function"==typeof this.onparsingerror))throw t;this.onparsingerror(t)}parseOptions(t,n,l,d){const p=d?t.split(d):[t];for(const h of p){if("string"!=typeof h)continue;const t=h.split(l);2===t.length&&n(t[0],t[1])}}parseCue(t,n,l){const d=t,consumeTimeStamp=()=>{const n=go.default.parseTimeStamp(t);if(null===n)throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed timestamp: "+d);return t=t.replace(/^[^\sa-zA-Z-]+/,""),n},skipWhitespace=()=>{t=t.replace(/^\s+/,"")};if(skipWhitespace(),n.startTime=consumeTimeStamp(),skipWhitespace(),"--\x3e"!==t.substr(0,3))throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '--\x3e'): "+d);t=t.substr(3),skipWhitespace(),n.endTime=consumeTimeStamp(),skipWhitespace(),((t,n)=>{const d=new Settings;this.parseOptions(t,(t,n)=>{let p,h;switch(t){case"region":for(let p=l.length-1;p>=0;p--)if(l[p].id===n){d.set(t,l[p].region);break}break;case"vertical":d.alt(t,n,["rl","lr"]);break;case"line":p=n.split(","),h=p[0],d.integer(t,h),d.percent(t,h)&&d.set("snapToLines",!1),d.alt(t,h,["auto"]),2===p.length&&d.alt("lineAlign",p[1],["start","center","end"]);break;case"position":if(p=n.split(","),d.percent(t,p[0]),2===p.length){let t=["line-left","line-right","center","auto","left","start","middle","end","right"];d.alt("positionAlign",p[1],t)}break;case"size":d.percent(t,n);break;case"align":let f=["start","center","end","left","right","middle"];d.alt(t,n,f)}},/:/,/\s/),n.region=d.get("region",null),n.vertical=d.get("vertical",""),n.line=d.get("line",void 0===n.line?"auto":n.line),n.lineAlign=d.get("lineAlign","start"),n.snapToLines=d.get("snapToLines",!0),n.size=d.get("size",100);let p=d.get("align","center");n.align="middle"===p?"center":p,n.position=d.get("position","auto");let h=d.get("positionAlign",{start:"start",left:"start",center:"center",right:"end",end:"end"},n.align);n.positionAlign={start:"start","line-left":"start",left:"start",center:"center",middle:"center","line-right":"end",right:"end",end:"end"}[h]})(t,n)}parseRegion(t){const n=new Settings;if(this.parseOptions(t,(t,l)=>{switch(t){case"id":n.set(t,l);break;case"width":n.percent(t,l);break;case"lines":n.integer(t,l);break;case"regionanchor":case"viewportanchor":{const d=l.split(",");if(2!==d.length)break;const p=new Settings;if(p.percent("x",d[0]),p.percent("y",d[1]),!p.has("x")||!p.has("y"))break;n.set(t+"X",p.get("x")),n.set(t+"Y",p.get("y"));break}case"scroll":n.alt(t,l,["up"])}},/=/,/\s/),n.has("id")){const t=new mo.VTTRegion;t.width=n.get("width",100),t.lines=n.get("lines",3),t.regionAnchorX=n.get("regionanchorX",0),t.regionAnchorY=n.get("regionanchorY",100),t.viewportAnchorX=n.get("viewportanchorX",0),t.viewportAnchorY=n.get("viewportanchorY",100),t.scroll=n.get("scroll",""),this.onregion&&this.onregion(t),this.regionList.push({id:n.get("id"),region:t})}}parseStyle(t){const parseStyles=t=>{const n={},l=t.split(";");for(let d=0;d<l.length;d++){const t=l[d].split(":",2),p=t[0].trim(),h=t[1].trim();""!==p&&""!==h&&(n[p]=h)}return n},n=t.replace(" ","").split("}");n.pop();for(const l of n){let t=null,n=null;const d=l.split("{");d[0]&&(t=d[0].trim()),d[1]&&(n=parseStyles(d[1])),t&&n&&(this._styles[t]=n)}this.onStylesParsedCallback&&this.onStylesParsedCallback(this._styles)}parseHeader(t){this.parseOptions(t,(function(t,n){switch(t){case"Region":this.parseRegion(n)}}),/:/)}parse(t){t&&(this.buffer+=this.decoder.decode(t,{stream:!0}));const collectNextLine=()=>{const t=this.buffer;let n=0;const calculateBreakPosition=(t,n)=>{const l={start:-1,length:-1};if("\r"===t[n])l.start=n,l.length=1;else if("\n"===t[n])l.start=n,l.length=1;else if("<"===t[n]&&n+1<t.length&&"b"===t[n+1]&&n+2<t.length&&"r"===t[n+2]){let d=n+2;for(;d<t.length&&">"!==t[d++];);l.start=n,l.length=d-n}return l};let l={start:t.length,length:0};for(;n<t.length;){const d=calculateBreakPosition(t,n);if(d.length>0){l=d;break}++n}const d=t.substr(0,l.start);return this.buffer=t.substr(l.start+l.length),d};try{let t;if(this.styleCollector="","INITIAL"===this.state){if(!/\r\n|\n/.test(this.buffer))return this;t=collectNextLine();const n=/^(ï»¿)?WEBVTT([ \t].*)?$/.exec(t);if(!n||!n[0])throw new ParsingError(ParsingError.Errors.BadSignature);this.state="HEADER"}let n=!1;for(;this.buffer;){if(!/\r\n|\n/.test(this.buffer))return this;switch(n?n=!1:t=collectNextLine(),this.state){case"HEADER":t.includes(":")?this.parseHeader(t):t||(this.state="ID");continue;case"NOTE":t||(this.state="ID");continue;case"STYLE":t?this.styleCollector+=t:(this.parseStyle(this.styleCollector),this.state="ID",this.styleCollector="");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){this.state="NOTE";break}if(/^STYLE($|[ \t])/.test(t)){this.state="STYLE";break}if(!t)continue;if(this.cue=new _o.VTTCue(0,0,""),this.state="CUE",!t.includes("--\x3e")){this.cue.id=t;continue}case"CUE":try{this.parseCue(t,this.cue,this.regionList)}catch(e){this.reportOrThrowError(e),this.cue=null,this.state="BADCUE";continue}this.state="CUETEXT";continue;case"CUETEXT":{const l=t.includes("--\x3e");if(!t||l){n=!0,this.oncue&&this.oncue(this.cue),this.cue=null,this.state="ID";continue}this.cue.text&&(this.cue.text+="\n"),this.cue.text+=t;continue}case"BADCUE":t||(this.state="ID");continue}}}catch(e){this.reportOrThrowError(e),"CUETEXT"===this.state&&this.cue&&this.oncue&&this.oncue(this.cue),this.cue=null,this.state="INITIAL"===this.state?"BADWEBVTT":"BADCUE"}return this}flush(){try{if(this.buffer+=this.decoder.decode(),(this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state)throw new ParsingError(ParsingError.Errors.BadSignature)}catch(e){this.reportOrThrowError(e)}return this.onflush&&this.onflush(),this}styles(){return this._styles}}n.default=WebVTTParser,n.WebVTTParser=WebVTTParser}));unwrapExports(bo);bo.VTTCue,bo.VTTRegion,bo.ParsingError,bo.WebVTTParser;var Po=createCommonjsModule((function(t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.VTTCue=_o.VTTCue;const l=[/^(::cue\()(\..*)(\))/,/^(::cue\()(#.*)(\))/,/^(::cue\()(c|i|b|u|ruby|rt|v|lang)(\))/],d=[[1470,1470],[1472,1472],[1475,1475],[1478,1478],[1488,1514],[1520,1524],[1544,1544],[1547,1547],[1549,1549],[1563,1563],[1566,1610],[1645,1647],[1649,1749],[1765,1766],[1774,1775],[1786,1805],[1807,1808],[1810,1839],[1869,1957],[1969,1969],[1984,2026],[2036,2037],[2042,2042],[2048,2069],[2074,2074],[2084,2084],[2088,2088],[2096,2110],[2112,2136],[2142,2142],[2208,2208],[2210,2220],[8207,8207],[64285,64285],[64287,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],[64323,64324],[64326,64449],[64467,64829],[64848,64911],[64914,64967],[65008,65020],[65136,65140],[65142,65276],[67584,67589],[67592,67592],[67594,67637],[67639,67640],[67644,67644],[67647,67669],[67671,67679],[67840,67867],[67872,67897],[67903,67903],[67968,68023],[68030,68031],[68096,68096],[68112,68115],[68117,68119],[68121,68147],[68160,68167],[68176,68184],[68192,68223],[68352,68405],[68416,68437],[68440,68466],[68472,68479],[68608,68680],[126464,126467],[126469,126495],[126497,126498],[126500,126500],[126503,126503],[126505,126514],[126516,126519],[126521,126521],[126523,126523],[126530,126530],[126535,126535],[126537,126537],[126539,126539],[126541,126543],[126545,126546],[126548,126548],[126551,126551],[126553,126553],[126555,126555],[126557,126557],[126559,126559],[126561,126562],[126564,126564],[126567,126570],[126572,126578],[126580,126583],[126585,126588],[126590,126590],[126592,126601],[126603,126619],[126625,126627],[126629,126633],[126635,126651],[1114109,1114109]];class StyleBox{applyStyles(t,n){n=n||this.div;for(const l in t)t.hasOwnProperty(l)&&(n.style[l]=t[l])}formatStyle(t,n){return 0===t?"0":t+n}}n.StyleBox=StyleBox;class CueStyleBox extends StyleBox{constructor(t,n,l,d,p){super(),this.cue=n;let h={textAlign:{start:"left","line-left":"left",left:"left",center:"center",middle:"center","line-right":"right",right:"right",end:"right"}[n.positionAlign]||n.align,whiteSpace:"pre-line",position:"absolute"};h.direction=this.determineBidi(this.cueDiv),h.writingMode=this.directionSettingToWritingMode(n.vertical),h.unicodeBidi="plaintext",this.div=t.document.createElement("div"),this.applyStyles(h),h={backgroundColor:d.backgroundColor,display:"inline-block"},this.parseOpacity(h.backgroundColor)&&(h.padding="5px",h.borderRadius="5px"),this.backgroundDiv=t.document.createElement("div"),this.applyStyles(h,this.backgroundDiv),h={color:l.color,backgroundColor:l.backgroundColor,textShadow:l.textShadow,fontSize:l.fontSize,fontFamily:l.fontFamily,position:"relative",left:"0",right:"0",top:"0",bottom:"0",display:"inline-block",textOrientation:"upright"},h.writingMode=this.directionSettingToWritingMode(n.vertical),h.unicodeBidi="plaintext",this.cueDiv=go.default.parseContent(t,n,p),this.applyStyles(h,this.cueDiv),this.backgroundDiv.appendChild(this.cueDiv),this.div.appendChild(this.backgroundDiv);let f=0;if("number"==typeof n.position){let t=n.positionAlign||n.align;if(t)switch(t){case"start":case"left":f=n.position;break;case"center":case"middle":f=n.position-n.size/2;break;case"end":case"right":f=n.position-n.size}}""===n.vertical?this.applyStyles({left:this.formatStyle(f,"%"),width:this.formatStyle(n.size,"%")}):this.applyStyles({top:this.formatStyle(f,"%"),height:this.formatStyle(n.size,"%")})}determineBidi(t){let n,l=[],p="";if(!t||!t.childNodes)return"ltr";function pushNodes(t,n){for(let l=n.childNodes.length-1;l>=0;l--)t.push(n.childNodes[l])}function nextTextNode(t){if(!t||!t.length)return null;let n=t.pop(),l=n.textContent||n.innerText;if(l){const n=/^.*(\n|\r)/.exec(l);return n?(t.length=0,n[0]):l}return"ruby"===n.tagName?nextTextNode(t):n.childNodes?(pushNodes(t,n),nextTextNode(t)):void 0}function isContainedInCharacterList(t,n){for(const l of n)if(t>=l[0]&&t<=l[1])return!0;return!1}for(pushNodes(l,t);p=nextTextNode(l);)for(let t=0;t<p.length;t++)if(n=p.charCodeAt(t),isContainedInCharacterList(n,d))return"rtl";return"ltr"}parseOpacity(t){if(!t||"string"!=typeof t)return null;const n=(t=t.replace(/ /g,"").replace("rgba(","").replace(")","")).split(",");return n&&n.length>=4?n[3]:null}directionSettingToWritingMode(t){return""===t?"horizontal-tb":"lr"===t?"vertical-lr":"vertical-rl"}move(t){this.applyStyles({top:this.formatStyle(t.top,"px"),bottom:this.formatStyle(t.bottom,"px"),left:this.formatStyle(t.left,"px"),right:this.formatStyle(t.right,"px"),height:this.formatStyle(t.height,"px"),width:this.formatStyle(t.width,"px")})}}n.CueStyleBox=CueStyleBox;class BoxPosition{constructor(t){var n;let l,d,p,h,f,y;if(t instanceof CueStyleBox&&t.cue?(n=t.cue)&&""!==n.vertical?this.property="width":this.property="height":t instanceof BoxPosition&&(this.property=t.property||"height"),t instanceof CueStyleBox&&t.div){p=t.div.offsetHeight,h=t.div.offsetWidth,f=t.div.offsetTop;const n=t.div.firstChild;if(y=n?n.getBoundingClientRect():t.div.getBoundingClientRect(),l=y&&y[this.property]||null,n&&n.firstChild){const t=n.firstChild;if(t&&"string"==typeof t.textContent){d=l/this.calculateNewLines(t.textContent)}}}else t instanceof BoxPosition&&(y=t);this.left=y.left,this.right=y.right,this.top=y.top||f,this.height=y.height||p,this.bottom=y.bottom||f+(y.height||p),this.width=y.width||h,this.lineHeight=null!==l?l:y.lineHeight,this.singleLineHeight=null!==d?d:y.singleLineHeight,this.singleLineHeight||(this.singleLineHeight=41)}calculateNewLines(t){let n=1;for(let l=0;l<t.length;l++)"\n"===t[l]&&n++;return n}move(t,n){switch(n=void 0!==n?n:this.singleLineHeight,t){case"+x":this.left+=n,this.right+=n;break;case"-x":this.left-=n,this.right-=n;break;case"+y":this.top+=n,this.bottom+=n;break;case"-y":this.top-=n,this.bottom-=n}}overlaps(t){return this.left<t.right&&this.right>t.left&&this.top<t.bottom&&this.bottom>t.top}overlapsAny(t){for(const n of t)if(this.overlaps(n))return!0;return!1}within(t){return this.top>=t.top&&this.bottom<=t.bottom&&this.left>=t.left&&this.right<=t.right}moveIfOutOfBounds(t,n){switch(n){case"+x":this.left<t.left&&(this.left=t.left,this.right=this.left+this.width);break;case"-x":this.right>t.right&&(this.right=t.right,this.left=this.right-this.width);break;case"+y":this.top<t.top&&(this.top=t.top,this.bottom=this.top+this.height);break;case"-y":this.bottom>t.bottom&&(this.bottom=t.bottom,this.top=this.bottom-this.height)}}toCSSCompatValues(t){return{top:this.top-t.top,bottom:t.bottom-this.bottom,left:this.left-t.left,right:t.right-this.right,height:this.height,width:this.width}}static getSimpleBoxPosition(t){let n=null;t instanceof StyleBox&&t.div?n=t.div:t instanceof HTMLElement&&(n=t);let l=n.offsetHeight||0,d=n.offsetWidth||0,p=n.offsetTop||0,h=p+l,f=n.getBoundingClientRect();const{left:y,right:v}=f;return f.top&&(p=f.top),f.height&&(l=f.height),f.width&&(d=f.width),f.bottom&&(h=f.bottom),{left:y,right:v,top:p,height:l,bottom:h,width:d}}static getBoxPosition(t,n){if(t&&t.length>0){let l=0,d=t[0][n];for(let p=0;p<t.length;p++)n in["top","right"]?t[p][n]>d&&(l=p,d=t[p][n]):n in["bottom","left"]&&t[p][n]<d&&(l=p,d=t[p][n]);return t[l]}return null}static moveToMinimumDistancePlacement(t,n,l){"height"===t.property?"+y"===n?(t.top=l.topMostBoxPosition.bottom+0,t.bottom=t.top+t.height):"-y"===n&&(t.bottom=l.bottomMostBoxPosition.top-0,t.top=t.bottom-t.height):"width"===t.property&&("+x"===n?(t.left=l.rightMostBoxPosition.right+0,t.right=t.left+t.width):"-x"===n&&(t.right=l.leftMostBoxPosition.left-0,t.left=t.right-t.width))}static moveBoxToLinePosition(t,n,l){const d=t.cue;let p,h=new BoxPosition(t),f=function(t){if("number"==typeof t.line&&(t.snapToLines||t.line>=0&&t.line<=100))return t.line;if(!t.track||!t.track.textTrackList||!t.track.textTrackList.mediaElement)return-1;let n=0;const l=t.track,d=l.textTrackList;for(let p=0;p<d.length&&d[p]!==l;p++)"showing"===d[p].mode&&n++;return-1*++n}(d),y=[];if(d.snapToLines){let t=0;switch(d.vertical){case"":y=["+y","-y"],p="height";break;case"rl":y=["+x","-x"],p="width";break;case"lr":y=["-x","+x"],p="width"}const l=h.lineHeight,v=n[p]+l,g=y[0];if(f<0){let p=0;switch(d.vertical){case"":p=n.height-l-.05*n.height;break;case"rl":case"lr":p=-n.width+l+.05*n.width}t=p,y=y.reverse()}else{switch(d.vertical){case"":t=l*Math.round(f);break;case"rl":t=n.width-l*Math.round(f);break;case"lr":t=l*Math.round(f)}Math.abs(t)>v&&(t=t<0?-1:1,t*=Math.ceil(v/l)*l)}h.move(g,t)}else{const l=""===d.vertical?n.height:n.width,p=h.lineHeight/l*100;switch(d.lineAlign){case"center":f-=p/2;break;case"end":f-=p}switch(d.vertical){case"":t.applyStyles({top:t.formatStyle(f,"%")});break;case"rl":t.applyStyles({right:t.formatStyle(f,"%")});break;case"lr":t.applyStyles({left:t.formatStyle(f,"%")})}y=["+y","-y","+x","-x"],"+y"===d.axis?y=["+y","-y","+x","-x"]:"-y"===d.axis&&(y=["-y","+y","+x","-x"]),h=new BoxPosition(t)}const v=function(t,d){let p;for(let h=0;h<d.length;h++){t.moveIfOutOfBounds(n,d[h]);let f=0,y=!1;for(;t.overlapsAny(l)&&!(f>9);)y?t.move(d[h]):(l&&l.length>0&&(p||(p={topMostBoxPosition:BoxPosition.getBoxPosition(l,"top"),bottomMostBoxPosition:BoxPosition.getBoxPosition(l,"bottom"),leftMostBoxPosition:BoxPosition.getBoxPosition(l,"left"),rightMostBoxPosition:BoxPosition.getBoxPosition(l,"right")}),BoxPosition.moveToMinimumDistancePlacement(t,d[h],p)),y=!0),f++}return t}(h,y);t.move(v.toCSSCompatValues(n))}}n.BoxPosition=BoxPosition;class WebVTTRenderer{constructor(t,n,l=!0){if(!t)return null;this.window=t,this.overlay=n,this.loggingEnabled=l,this.foregroundStyleOptions={fontFamily:"Helvetica",fontSize:"36px",color:"rgba(255, 255, 255, 1)",textShadow:"",backgroundColor:"rgba(0, 0, 0, 0)"},this.backgroundStyleOptions={backgroundColor:"rgba(0, 0, 0, 0.5)"},this.globalStyleCollection={};const d=t.document.createElement("div");d.style.position="absolute",d.style.left="0",d.style.right="0",d.style.top="0",d.style.bottom="0",d.style.margin="1.5%",this.paddedOverlay=d,n.appendChild(this.paddedOverlay),this.initSubtitleCSS()}initSubtitleCSS(){const t=[new _o.VTTCue(0,0,"String to init CSS - Won't be visible to user")];this.paddedOverlay.style.opacity="0",this.processCues(t),this.processCues([]),this.paddedOverlay.style.opacity="1"}convertCueToDOMTree(t){return t?go.default.parseContent(this.window,t,this.globalStyleCollection):null}setStyles(t){function applyStyles(t,n,l){for(const d in n)n.hasOwnProperty(d)&&(!0===l&&void 0!==t[d]||!1===l)&&(t[d]=n[d])}for(const n in t){let d=!1,p=null;"::cue"===n?(p=this.foregroundStyleOptions,d=!0):"::-webkit-media-text-track-display"===n&&(p=this.backgroundStyleOptions,d=!0);const h=t[n];if(!0===d)applyStyles(p,h,d);else for(let t=0;t<l.length;t++){const p=l[t].exec(n);if(p&&4===p.length){const t=p[2],n={};applyStyles(n,h,d),this.globalStyleCollection[t]=n}}}this.initSubtitleCSS(),this.loggingEnabled&&(console.log("WebVTTRenderer setStyles foregroundStyleOptions: "+JSON.stringify(this.foregroundStyleOptions)),console.log("WebVTTRenderer setStyles backgroundStyleOptions: "+JSON.stringify(this.backgroundStyleOptions)),console.log("WebVTTRenderer setStyles globalStyleCollection: "+JSON.stringify(this.globalStyleCollection)))}processCues(t){if(!t)return;for(;this.paddedOverlay.firstChild;)this.paddedOverlay.removeChild(this.paddedOverlay.firstChild);if(!function(t){for(let n=0;n<t.length;n++)if(t[n].hasBeenReset||!t[n].displayState)return!0;return!1}(t)){for(let n=0;n<t.length;n++)this.paddedOverlay.appendChild(t[n].displayState);return}const n=[],l=BoxPosition.getSimpleBoxPosition(this.paddedOverlay);t.length>1&&(t=function(t){const n=[];let l=0;for(let d=0;d<t.length;d++){let p=t[d];if("number"!=typeof p.line)return t;l+=p.line,n.push(p)}return l/=t.length,l>50?(n.forEach((function(t){t.axis="-y"})),n.sort((t,n)=>n.line-t.line)):(n.forEach((function(t){t.axis="+y"})),n.sort((t,n)=>t.line-n.line)),n}(t));for(let d=0;d<t.length;d++){let p=t[d],h=new CueStyleBox(this.window,p,this.foregroundStyleOptions,this.backgroundStyleOptions,this.globalStyleCollection);this.paddedOverlay.appendChild(h.div),BoxPosition.moveBoxToLinePosition(h,l,n),p.displayState=h.div,n.push(BoxPosition.getSimpleBoxPosition(h))}}setSize(t,n){t&&(this.overlay.style.width=t+"px"),n&&(this.overlay.style.height=n+"px")}getOverlay(){return this.overlay}}n.default=WebVTTRenderer,n.WebVTTRenderer=WebVTTRenderer}));unwrapExports(Po);Po.VTTCue,Po.StyleBox,Po.CueStyleBox,Po.BoxPosition,Po.WebVTTRenderer;var ko=createCommonjsModule((function(t,n){function __export(t){for(var l in t)n.hasOwnProperty(l)||(n[l]=t[l])}Object.defineProperty(n,"__esModule",{value:!0}),__export(bo),__export(Po)}));unwrapExports(ko);var To=ko.WebVTTRenderer,So=function(){function TrackManagerStub(){}return Object.defineProperty(TrackManagerStub.prototype,"currentTrack",{get:function(){return{}},set:function(t){},enumerable:!0,configurable:!0}),Object.defineProperty(TrackManagerStub.prototype,"tracks",{get:function(){return[]},enumerable:!0,configurable:!0}),TrackManagerStub.prototype.destroy=function(){},TrackManagerStub.prototype.restoreSelectedTrack=function(){},TrackManagerStub}(),Ao=nr.audioTrackAdded,wo=nr.audioTrackChanged,Io=nr.forcedTextTrackChanged,Eo=nr.textTrackAdded,Ro=nr.textTrackChanged,Oo=nr.textTrackRemoved,Co=tn.textTracksSwitched,Mo=tn.textTracksUpdated,Do=function(){function TextTrackManager(t,n,l){this.mediaElement=t,this.dispatcher=n,this.extensionTracks=l,this._tracks=[],this.trackPersistence=new uo("mk-text-track",["label","language","kind"]);var d,p,h,f,y=this.trackPersistence.getPersistedTrack();if(this._tracks.push({id:-2,label:"Off",language:"",kind:"subtitles",mode:y&&"Off"===y.label?"showing":"disabled"},{id:-1,label:"Auto",language:"",kind:"subtitles",mode:y&&"Auto"!==y.label?"disabled":"showing"}),this.extensionTracks){Pt.debug("MEDIA_TRACK Initializing text track manager for HLS.js track events");var v=t.parentElement;this.renderer=new To(window,v,!1),this.renderer.setStyles({"::cue":{fontSize:"calc(1vw + 1em)"}}),this.onExtensionTextTracksAdded=this.onExtensionTextTracksAdded.bind(this),this.onExtensionTextTrackSwitched=this.onExtensionTextTrackSwitched.bind(this),this.onCueChange=this.onCueChange.bind(this);var g=this.extensionTracks;g.addEventListener(Mo,this.onExtensionTextTracksAdded),g.addEventListener(Co,this.onExtensionTextTrackSwitched)}else Pt.debug("MEDIA_TRACK Initializing text track manager for native track events"),this.onTextTrackAdded=this.onTextTrackAdded.bind(this),this.onTextTrackChanged=this.onTextTrackChanged.bind(this),this.onTextTrackRemoved=this.onTextTrackRemoved.bind(this),this.onPlayStart=this.onPlayStart.bind(this),t.textTracks.addEventListener("addtrack",this.onTextTrackAdded),t.textTracks.addEventListener("change",this.onTextTrackChanged),t.textTracks.addEventListener("removetrack",this.onTextTrackRemoved),t.addEventListener("playing",this.onPlayStart);this.onAudioTrackAddedOrChanged=(d=this.onAudioTrackAddedOrChanged.bind(this),void 0===p&&(p=250),void 0===h&&(h={isImmediate:!1}),function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var l=this,doLater=function(){f=void 0,h.isImmediate||d.apply(l,t)},y=h.isImmediate&&void 0===f;void 0!==f&&clearTimeout(f),f=setTimeout(doLater,p),y&&d.apply(l,t)}),n.subscribe(wo,this.onAudioTrackAddedOrChanged),n.subscribe(Ao,this.onAudioTrackAddedOrChanged)}return Object.defineProperty(TextTrackManager.prototype,"currentTrack",{get:function(){return this.tracks.find((function(t){return"showing"===t.mode}))},set:function(t){var n;t&&(this.trackPersistence.setPersistedTrack(t),this.extensionTracks?(Pt.debug("MEDIA_TRACK Setting track on extension "+t.label),"Auto"===t.label?(this.clearCurrentlyPlayingTrack(),void 0===(n=this.extensionTracks.selectForcedTrack())&&this.onExtensionTextTrackSwitched({track:t})):this.extensionTracks.textTrack=t):(Pt.debug("MEDIA_TRACK Setting track on element "+t.label),this._tracks.forEach((function(n){n!==t&&"showing"===n.mode&&(n.mode="disabled")})),t&&(Pt.debug("MEDIA_TRACK setting track mode to showing for "+t.label),"Auto"===t.label?(this._tracks[1].mode="showing",n=this.selectNativeForcedTrack(this.mediaElement.audioTracks)):"Off"===t.label?this._tracks[0].mode="showing":t.mode="showing")),this.dispatcher.publish(nr.forcedTextTrackChanged,n))},enumerable:!0,configurable:!0}),Object.defineProperty(TextTrackManager.prototype,"tracks",{get:function(){return this._tracks},enumerable:!0,configurable:!0}),TextTrackManager.prototype.destroy=function(){if(this.clearCurrentlyPlayingTrack(),this.extensionTracks){var t=this.extensionTracks;t.removeEventListener(Mo,this.onExtensionTextTracksAdded),t.removeEventListener(Co,this.onExtensionTextTrackSwitched)}else this.mediaElement.textTracks.removeEventListener("addtrack",this.onTextTrackAdded),this.mediaElement.textTracks.removeEventListener("change",this.onTextTrackChanged),this.mediaElement.textTracks.removeEventListener("removetrack",this.onTextTrackRemoved),this.mediaElement.removeEventListener("playing",this.onPlayStart);this.dispatcher.unsubscribe(wo,this.onAudioTrackAddedOrChanged),this.dispatcher.unsubscribe(Ao,this.onAudioTrackAddedOrChanged)},TextTrackManager.prototype.restoreSelectedTrack=function(){return restoreSelectedTrack(this.trackPersistence,this)},TextTrackManager.prototype.onExtensionTextTracksAdded=function(t){var n;Pt.debug("MEDIA_TRACK Extension text tracks updated "+JSON.stringify(t)),(n=this._tracks).push.apply(n,__spread(t)),this.restoreSelectedTrack(),this.dispatcher.publish(Eo,t)},TextTrackManager.prototype.onExtensionTextTrackSwitched=function(t){if(Pt.debug("MEDIA_TRACKS Extension text track switched "+t),this.handleVTT(t),this._tracks){this._tracks.forEach((function(n){t.track?t.track.forced&&"Auto"===n.label||"Auto"===t.track.label&&"Auto"===n.label?n.mode="showing":n.mode=t.track.persistentID===n.id?"showing":"disabled":n.mode="Off"===n.label?"showing":"disabled"}))}this.dispatcher.publish(Ro,t)},TextTrackManager.prototype.handleVTT=function(t){var n=t&&t.track&&t.track.id;if(void 0!==n&&n>=0){var l=this.filterSelectableTextTracks(this.mediaElement.textTracks)[n];this.onNativeTrackChange(l)}else this.clearCurrentlyPlayingTrack()},TextTrackManager.prototype.onAudioTrackAddedOrChanged=function(t,n){if(Pt.debug("MEDIA_TRACKS text track manager detects audio track change"),this.shouldForceSubtitle())if(this.extensionTracks){Pt.debug("MEDIA_TRACKS selecting forced text track via extension");var l=this.extensionTracks.selectForcedTrack();l&&this.dispatcher.publish(Io,l)}else Pt.debug("MEDIA_TRACKS selecting forced text track natively"),this.currentTrack=this._tracks[1]},TextTrackManager.prototype.onTextTrackAdded=function(t){this._tracks.push(t.track),this.dispatcher.publish(Eo,t)},TextTrackManager.prototype.onPlayStart=function(){this.restoreSelectedTrack()},TextTrackManager.prototype.onTextTrackRemoved=function(t){this.dispatcher.publish(Oo,t)},TextTrackManager.prototype.onTextTrackChanged=function(t){var n=this.findNativeSelectedTextTrack(),l=this.trackPersistence.getPersistedTrack();if(l||(l=this._tracks[1]),n&&!trackEquals(n,l,this.trackPersistence.fields))if("Off"===l.label||"Auto"===l.label&&"forced"!==n.kind)this.currentTrack=l;else{var d=this.findNativeTrack(l);d&&(this.currentTrack=d)}else this.dispatcher.publish(Ro,t)},TextTrackManager.prototype.findNativeSelectedTextTrack=function(){for(var t=0;t<this.mediaElement.textTracks.length;t++){var n=this.mediaElement.textTracks[t];if("showing"===n.mode)return n}},TextTrackManager.prototype.findNativeTrack=function(t){for(var n=0;n<this.mediaElement.textTracks.length;n++){var l=this.mediaElement.textTracks[n];if(trackEquals(l,t,this.trackPersistence.fields))return l}},TextTrackManager.prototype.selectNativeForcedTrack=function(t){for(var n=0;n<t.length;n++){var l=t[n];if(l.enabled){var d=this.findNativeForcedTrack(l);return d&&"showing"!==d.mode&&(d.mode="showing"),d}}},TextTrackManager.prototype.findNativeForcedTrack=function(t){for(var n=this.mediaElement.textTracks,l=0;l<n.length;l++){var d=n[l];if("forced"===d.kind&&d.language===t.language)return d}},TextTrackManager.prototype.onNativeTrackChange=function(t){this.clearCurrentlyPlayingTrack(),this._currentlyPlayingTrack=t,t.addEventListener("cuechange",this.onCueChange)},TextTrackManager.prototype.clearCurrentlyPlayingTrack=function(){var t;void 0!==this._currentlyPlayingTrack&&("string"==typeof(t=this._currentlyPlayingTrack).id&&"removeEventListener"in t)&&(this._currentlyPlayingTrack.removeEventListener("cuechange",this.onCueChange),this.renderer.processCues({}),delete this._currentlyPlayingTrack)},TextTrackManager.prototype.onCueChange=function(t){var n=t&&t.target&&t.target.activeCues;n&&this.renderer.processCues(n)},TextTrackManager.prototype.filterSelectableTextTracks=function(t){for(var n=Array(),l=0;l<t.length;l++){var d=t[l];("captions"===d.kind||"subtitles"===d.kind||"metadata"===d.kind&&d.customTextTrackCueRenderer)&&n.push(d)}return n},TextTrackManager.prototype.shouldForceSubtitle=function(){Pt.debug("MEDIA_TRACKS Determining whether to select forced text track");var t=this.trackPersistence.getPersistedTrack();return!t||"Auto"===t.label},TextTrackManager}(),Lo={"picture-in-picture":t.PresentationMode.pictureinpicture,inline:t.PresentationMode.inline},No={};No[t.PresentationMode.pictureinpicture]="picture-in-picture",No[t.PresentationMode.inline]="inline";var xo=nr.presentationModeDidChange,Uo=tn.levelUpdated,Bo=tn.manifestParsed,jo=tn.playbackLicenseError,Fo=tn.sessionCreated,Ko=t.PlaybackStates.stopped,Vo=function(n){function VideoPlayer(t){var l=n.call(this,t)||this;return l.mediaPlayerType="video",l._textTrackManager=new So,l._audioTrackManager=new So,l.services=t.services,l.restrictPlatforms=!("restrict-platforms"in ur.features)||ur.features["restrict-platforms"],l.pipEventHandler=l.pipEventHandler.bind(l),l}return __extends(VideoPlayer,n),Object.defineProperty(VideoPlayer.prototype,"audioTracks",{get:function(){return this._audioTrackManager.tracks},enumerable:!0,configurable:!0}),Object.defineProperty(VideoPlayer.prototype,"containerElement",{get:function(){return this._context.videoContainerElement?this._context.videoContainerElement:document.getElementById("apple-music-video-container")},enumerable:!0,configurable:!0}),Object.defineProperty(VideoPlayer.prototype,"currentAudioTrack",{get:function(){return this._audioTrackManager.currentTrack},set:function(t){this._audioTrackManager.currentTrack=t},enumerable:!0,configurable:!0}),Object.defineProperty(VideoPlayer.prototype,"currentTextTrack",{get:function(){return this._textTrackManager.currentTrack},set:function(t){this._textTrackManager.currentTrack=t},enumerable:!0,configurable:!0}),Object.defineProperty(VideoPlayer.prototype,"_targetElement",{get:function(){return this.video||__assign({},document.createElement("video"))},enumerable:!0,configurable:!0}),Object.defineProperty(VideoPlayer.prototype,"textTracks",{get:function(){return this._textTrackManager.tracks},enumerable:!0,configurable:!0}),VideoPlayer.prototype.initializeExtension=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return this.restrictPlatforms&&bt.isAndroid?(Pt.warn("videoPlayer.initializeExtension Not supported on the current platform"),[2]):this.video?(this.extension=new so(this.video,this.services),[4,this.extension.init()]):(Pt.warn("videoPlayer.initializeExtension No video element, not initializing extension"),[2]);case 1:return t.sent(),this.extension.addEventListener(Bo,this.onManifestParsed),this.extension.addEventListener(Fo,this.onSessionCreated),this.extension.addEventListener(jo,this.onPlaybackLicenseError),this.extension.addEventListener(Uo,this.onLevelUpdated),[2]}}))}))},VideoPlayer.prototype.onLevelUpdated=function(t){this._dispatcher.publish(er.hlsLevelUpdated,t)},VideoPlayer.prototype.onManifestParsed=function(){Pt.debug("video.onManifestParsed"),asAsync(this._playMedia())},VideoPlayer.prototype.onPlaybackLicenseError=function(t){this._licenseError(),this._dispatcher.publish(jo,t)},VideoPlayer.prototype.onSessionCreated=function(){var t,n,l,d,p,h;null===(n=null===(t=this._textTrackManager)||void 0===t?void 0:t.destroy)||void 0===n||n.call(t),this._textTrackManager=new Do(this._targetElement,this._dispatcher,null===(l=this.extension)||void 0===l?void 0:l.hlsJsTracks),null===(p=null===(d=this._audioTrackManager)||void 0===d?void 0:d.destroy)||void 0===p||p.call(d),this._audioTrackManager=new yo(this._targetElement,this._dispatcher,null===(h=this.extension)||void 0===h?void 0:h.hlsJsTracks)},VideoPlayer.prototype.destroy=function(){this._textTrackManager.destroy(),this._audioTrackManager.destroy(),n.prototype.destroy.call(this)},VideoPlayer.prototype.initializeEventHandlers=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return n.prototype.initializeEventHandlers.call(this),this.hasMediaElement?(this._targetElement.addEventListener("webkitpresentationmodechanged",this.pipEventHandler),this._targetElement.addEventListener("enterpictureinpicture",this.pipEventHandler),this._targetElement.addEventListener("leavepictureinpicture",this.pipEventHandler),[2]):[2]}))}))},VideoPlayer.prototype.removeEventHandlers=function(){n.prototype.removeEventHandlers.call(this);var t=this.extension;if(t&&(t.removeEventListener(Bo,this.onManifestParsed),t.removeEventListener(Fo,this.onSessionCreated),t.removeEventListener(jo,this.onPlaybackLicenseError),t.removeEventListener(Uo,this.onLevelUpdated)),this.hasMediaElement){var l=this._targetElement;l.removeEventListener("webkitpresentationmodechanged",this.pipEventHandler),l.removeEventListener("enterpictureinpicture",this.pipEventHandler),l.removeEventListener("leavepictureinpicture",this.pipEventHandler)}},VideoPlayer.prototype.initializeMediaElement=function(){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(n){return Pt.debug("videoPlayer.initializeMediaElement Initializing media element"),(t=this.containerElement)?(this.video=((l=Tt.pop())?Pt.debug("dom-helpers: retrieving video tag, "+Tt.length+" remain"):(Pt.debug("dom-helpers: no available video tags, creating one"),l=document.createElement("video")),l),this.video.autoplay=!1,this.video.controls=!1,this.video.playsInline=!0,this.video.id="apple-music-video-player",t.appendChild(this.video),[2]):(Pt.warn("videoPlayer.initializeMediaElement No video element; no container defined"),[2]);var l}))}))},VideoPlayer.prototype._stopMediaElement=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,n.prototype._stopMediaElement.call(this)];case 1:return t.sent(),this.destroy(),[2]}}))}))},VideoPlayer.prototype.isPlayerSupported=function(){return mt.supportsEs6()},VideoPlayer.prototype.pipEventHandler=function(n){switch(n.type){case"enterpictureinpicture":this._dispatcher.publish(xo,{mode:t.PresentationMode.pictureinpicture});break;case"leavepictureinpicture":this._dispatcher.publish(xo,{mode:t.PresentationMode.inline});break;case"webkitpresentationmodechanged":var l=this._targetElement;this._dispatcher.publish(xo,{mode:this._translateStringToPresentationMode(l.webkitPresentationMode)})}},VideoPlayer.prototype.playItemFromEncryptedSource=function(n,l){return void 0===l&&(l=!1),__awaiter(this,void 0,void 0,(function(){var d;return __generator(this,(function(p){return Pt.debug("videoPlayer.playItemFromEncryptedSource",n,l),this.playbackState===Ko?(Pt.debug("videoPlayer.playItemFromEncryptedSource aborting playback because player is stopped"),[2]):(d=this.extension,n.playbackType=t.PlaybackType.encryptedFull,this.nowPlayingItem=n,d.initiated=l,n.state=pr.loading,d.setCurrentSrc(n.assetURL),d.setMediaItem(n),[2])}))}))},VideoPlayer.prototype.playItemFromUnencryptedSource=function(t,n){return __awaiter(this,void 0,void 0,(function(){var l,d,p;return __generator(this,(function(h){return l=this.extension,Pt.debug("videoPlayer.playItemFromUnencryptedSource",t,n),this.playbackState===Ko?(Pt.debug("videoPlayer.playItemFromUnencryptedSource aborting playback because player is stopped"),[2]):(d=__read(t.split("?"),1),(p=d[0]).endsWith("m3u")||p.endsWith("m3u8")?(l.setCurrentSrc(t),l.setMediaItem(this.nowPlayingItem),[2]):l&&l.session&&l.session.destroy?(l.session.destroy(),[2,this._playAssetURL(t,n)]):[2,this._playAssetURL(t,n)])}))}))},VideoPlayer.prototype.setPresentationMode=function(n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){if((l=this._targetElement).webkitSupportsPresentationMode&&"function"==typeof l.webkitSetPresentationMode)return[2,l.webkitSetPresentationMode(this._translatePresentationModeToString(n))];if(l.requestPictureInPicture&&document.exitPictureInPicture){if(n===t.PresentationMode.pictureinpicture)return[2,l.requestPictureInPicture()];if(n===t.PresentationMode.inline)return[2,document.exitPictureInPicture()]}return[2]}))}))},VideoPlayer.prototype._translateStringToPresentationMode=function(n){var l=Lo[n];return void 0===l&&(Pt.warn("videoPlayer._translateStringToPresentationMode "+n+" is not a valid presentation mode, setting to inline"),l=t.PresentationMode.inline),l},VideoPlayer.prototype._translatePresentationModeToString=function(t){var n=No[t];return void 0===n&&(Pt.warn("videoPlayer._translatePresentationModeToString "+t+" is not a valid presentation mode, setting to inline"),n="inline"),n},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",void 0)],VideoPlayer.prototype,"onLevelUpdated",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],VideoPlayer.prototype,"onManifestParsed",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object]),__metadata("design:returntype",void 0)],VideoPlayer.prototype,"onPlaybackLicenseError",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],VideoPlayer.prototype,"onSessionCreated",null),VideoPlayer}(zn),$o=function(t){function EncryptedSession(){return null!==t&&t.apply(this,arguments)||this}return __extends(EncryptedSession,t),EncryptedSession.prototype.attachMedia=function(t,n){var l=this;return this.keySystem=n.keySystem,t.addEventListener("encrypted",this.boundHandleSessionCreation,!1),n.createMediaKeys().then((function(n){t.setMediaKeys(n)})).catch((function(t){return l.dispatchKeyError(t)}))},EncryptedSession.prototype.detachMedia=function(t){t.removeEventListener("encrypted",this.boundHandleSessionCreation)},EncryptedSession.prototype.createSession=function(t){var n=this;Pt.debug("Encrypted createSession",t);var l=t.initData,d=t.initDataType,p=t.target;return this._mediaKeysServerCertificate?this._createSession(p,l,d):this.loadCertificateBuffer().then((function(t){return p.mediaKeys.setServerCertificate(t).then((function(){return n._mediaKeysServerCertificate=t,n._createSession(p,l,d)}))}))},EncryptedSession.prototype.generatePSSH=function(t){for(var n=new Uint8Array([0,0,0,52,112,115,115,104,0,0,0,0,237,239,139,169,121,214,74,206,163,200,39,220,213,29,33,237,0,0,0,20,8,1,18,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),l=ue(t),d=0;d<l.length;d++)n[n.length-16+d]=l[d];return Pt.debug("generatePSSH",n),n},EncryptedSession.prototype._createSession=function(t,n,l){var d,p,h=t.mediaKeys.createSession();this._teardownCurrentSession(),Pt.debug("creating media key session",h);var f=this.isWidevine&&!(null===(d=this.item)||void 0===d?void 0:d.isLiveRadioStation);if(null===(p=this.item)||void 0===p?void 0:p.isLiveRadioStation){var y=new Uint8Array(n).slice(0,56),v=de(y);Pt.debug("extracted uri",v),h.extURI=v}var g=f?this.generatePSSH(this.extID):n;return h.addEventListener("message",this.startLicenseSession),this._currentSession=h,h.generateRequest(l,g)},EncryptedSession.prototype._teardownCurrentSession=function(){this._currentSession&&(Pt.debug("tearing down media key session",this._currentSession),this._currentSession.removeEventListener("message",this.startLicenseSession),this._currentSession=void 0)},EncryptedSession}(qn),Ho=function(t){function MSSession(){return null!==t&&t.apply(this,arguments)||this}return __extends(MSSession,t),MSSession.prototype.attachMedia=function(t,n){return this.keySystem=n.keySystem,t.addEventListener("msneedkey",this.boundHandleSessionCreation,!1),t.addEventListener("mskeyerror",this.boundDispatchKeyError),t},MSSession.prototype.detachMedia=function(t){t.removeEventListener("msneedkey",this.boundHandleSessionCreation,!1),t.removeEventListener("mskeyerror",this.boundDispatchKeyError)},MSSession.prototype.createSession=function(t){var n=t.initData,l=t.target;if(!l.msKeys){var d=new MSMediaKeys(this.keySystem);l.msSetMediaKeys(d)}var p=l.msKeys.createSession(rn.MP4,n);return p.addEventListener("mskeyerror",this.dispatchKeyError),p.addEventListener("mskeymessage",this.startLicenseSession.bind(this)),p},MSSession}(qn),zo=function(t){function MediaExtension(n,l){var d=t.call(this,[tn.playbackLicenseError,tn.playbackSessionError])||this;return d.audio=n,d.contentType=l,bt.isIE||bt.isSafari&&bt.engineMajorVersion,d}return __extends(MediaExtension,t),Object.defineProperty(MediaExtension.prototype,"hasMediaKeySupport",{get:function(){return hasMediaKeySupport()},enumerable:!0,configurable:!0}),Object.defineProperty(MediaExtension.prototype,"hasMediaSession",{get:function(){return void 0!==this._session},enumerable:!0,configurable:!0}),Object.defineProperty(MediaExtension.prototype,"isFairplay",{get:function(){return this._session.isFairplay},enumerable:!0,configurable:!0}),Object.defineProperty(MediaExtension.prototype,"extURI",{set:function(t){this._session.extURI=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaExtension.prototype,"initiated",{set:function(t){this._session.initiated=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaExtension.prototype,"session",{get:function(){return this._session},enumerable:!0,configurable:!0}),MediaExtension.prototype.cancelPendingRenewal=function(){var t;null===(t=this._session)||void 0===t||t.cancelPendingRenewal()},MediaExtension.prototype.initializeKeySystem=function(){return __awaiter(this,void 0,void 0,(function(){var t,n=this;return __generator(this,(function(l){switch(l.label){case 0:return[4,this._attachSession()];case 1:return l.sent(),(t=this._session)?([tn.playbackLicenseError,tn.playbackSessionError].forEach((function(l){t.addEventListener(l,(function(t){n.dispatchEvent(l,t)}))})),[2]):[2]}}))}))},MediaExtension.prototype._attachSession=function(){var t,n,l;return __awaiter(this,void 0,void 0,(function(){var d,p,h,f,y,v;return __generator(this,(function(g){switch(g.label){case 0:return p=(d=this).audio,h=d.contentType,(null===(t=window.WebKitMediaKeys)||void 0===t?void 0:t.isTypeSupported(et.FAIRPLAY+".1_0",rn.MP4))?(this._session=new Qn,this._session.attachMedia(p,{keySystem:et.FAIRPLAY}),[3,4]):[3,1];case 1:return(null===(n=window.MSMediaKeys)||void 0===n?void 0:n.isTypeSupported(et.PLAYREADY,rn.MP4))?(this._session=new Ho,this._session.attachMedia(p,{keySystem:et.PLAYREADY}),[3,4]):[3,2];case 2:return this.hasMediaKeySupport&&p.canPlayType(h)?(this._session=new $o,f=[{initDataTypes:["cenc","keyids"],audioCapabilities:[{contentType:h}],distinctiveIdentifier:"optional",persistentState:"required"}],[4,findMediaKeySystemAccess(potentialKeySystemsForAccess(),f)]):[3,4];case 3:y=__read.apply(void 0,[g.sent(),2]),(v=y[1])?null===(l=this._session)||void 0===l||l.attachMedia(p,v):Pt.warn("media-extension: No keysystem detected!"),g.label=4;case 4:return[2]}}))}))},MediaExtension.prototype.setMediaItem=function(t){bindSessionData(this._session,t)},MediaExtension.prototype.destroy=function(t){this._session&&this._session.detachMedia(t)},MediaExtension}(he),Wo=function(){function ByteRangeSegment(t){var n=t.url,l=t.startByte,d=t.length;this.url=n,this.startByte=parseInt(l,10),this.length=parseInt(d,10),this.endByte=this.startByte+this.length-1,this.range="bytes="+this.startByte+"-"+this.endByte}return ByteRangeSegment.prototype.load=function(){return __awaiter(this,void 0,void 0,(function(){var t,n,l,d,p;return __generator(this,(function(h){switch(h.label){case 0:return n=(t=this).url,l=t.range,n?((d=new Headers).append("Range",l),[4,fetch(n,{headers:d})]):[2,new Uint8Array];case 1:return[4,h.sent().arrayBuffer()];case 2:return p=h.sent(),[2,new Uint8Array(p)]}}))}))},ByteRangeSegment}(),Yo=function(){function ContinuousSegment(t){this.url=t}return ContinuousSegment.prototype.load=function(){return __awaiter(this,void 0,void 0,(function(){var t,n;return __generator(this,(function(l){switch(l.label){case 0:return(t=this.url)?(Pt.debug("radio-segment: loading",t),[4,fetch(t)]):[2,new Uint8Array];case 1:return[4,l.sent().arrayBuffer()];case 2:return n=l.sent(),[2,new Uint8Array(n)]}}))}))},ContinuousSegment}(),qo=/^#EXT-X-BYTERANGE:([^\n]+)\n/gim,Go=/^#EXT-X-MAP:([^\n]+)\n/im,Qo=/#EXTINF:\d*\.\d*\,[\n](.+)|^#EXT-X-MAP:URI="([^"]*)"/gim;var Jo=function(){function SegmentList(){this._segments=[],this._addedSegments={}}return Object.defineProperty(SegmentList.prototype,"segments",{get:function(){return this._segments},enumerable:!0,configurable:!0}),SegmentList.prototype.addSegment=function(t,n){this._addedSegments[n]||(Pt.debug("Adding segment",n),this._segments.push(t),this._addedSegments[n]=!0)},SegmentList.prototype.extractLiveRadioSegments=function(t,n){if(!t||!Qo.test(t))return this;var l;for(Qo.lastIndex=0;l=Qo.exec(t);){var d,p=rewriteLastUrlPath(n,d=l[0].startsWith("#EXT-X-MAP")?l[2]:l[1]);this.addSegment(new Yo(p),d)}},SegmentList.prototype.extractByteRangeSegments=function(t,n){var l,d,p=this;if(t&&qo.test(t)){var h=function(t){if(t&&Go.test(t))return __read(t.match(Go),2)[1].split(",").reduce((function(t,n){var l=__read(n.split("="),2),d=l[0],p=l[1];return t[d.toLowerCase()]=p.replace(/\"/gi,""),t}),{})}(t),f=null!==(l=n.split("/").pop())&&void 0!==l?l:"",y=n.replace(f,h.uri),v=__read(h.byterange.split("@"),2),g=v[0],_=v[1],m=new Wo({url:y,startByte:_,length:g});this.addSegment(m,m.range),(null!==(d=t.match(qo))&&void 0!==d?d:[]).forEach((function(t){var n=__read(t.match(/^#EXT-X-BYTERANGE:(\d+)@(\d+)\n/),3),l=n[1],d=n[2],h=new Wo({url:y,startByte:d,length:l});p.addSegment(h,h.range)}))}},SegmentList}(),Xo=/^#EXT-X-TARGETDURATION:(\d+)/im,Zo=/^#EXT-X-KEY:[^\n]+URI="([^"]+)"/im;function loadManifestData(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,fetch(t)];case 1:return[2,n.sent().text()]}}))}))}var ea,ta=function(t){function Manifest(n,l){var d=t.call(this,[tn.manifestParsed])||this;if(d._downlink=0,d._segmentList=new Jo,d._data=n,d._item=l,d._url=l.assetURL,ln!==et.FAIRPLAY)if(l.isLiveRadioStation){d._segmentList.extractLiveRadioSegments(n,l.assetURL);var p=__read(d._data.match(Xo),2),h=(p[0],p[1]);Pt.debug("manifest: setting up manifest refresh interval at "+h+" seconds");var f=1e3*parseInt(h,10);d._manifestRefreshInterval=setInterval(d.liveRadioRefresh,f)}else d._segmentList.extractByteRangeSegments(n,l.assetURL);return d}return __extends(Manifest,t),Manifest.load=function(t,n){return void 0===n&&(n=!0),__awaiter(this,void 0,void 0,(function(){var l,d,p,h,f;return __generator(this,(function(y){switch(y.label){case 0:return l=t.assetURL,(p=!!window.sessionStorage&&n)&&(d=window.sessionStorage.getItem(l))?[2,new this(d,t)]:(h=(new Date).getTime(),[4,loadManifestData(l)]);case 1:return d=y.sent(),(f=new this(d,t)).downlink=function(t,n){return 8*n.length/(((new Date).getTime()-t)/1e3)/1024}(h,d),p&&window.sessionStorage.setItem(l,d),[2,Promise.resolve(f)]}}))}))},Object.defineProperty(Manifest.prototype,"downlink",{get:function(){return this._downlink},set:function(t){this._downlink=t},enumerable:!0,configurable:!0}),Object.defineProperty(Manifest.prototype,"mediaItem",{get:function(){return this._item},enumerable:!0,configurable:!0}),Manifest.prototype.liveRadioRefresh=function(){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(n){switch(n.label){case 0:return[4,loadManifestData(this._url)];case 1:return t=n.sent(),this._data=t,this._segmentList.extractLiveRadioSegments(t,this._url),this.dispatchEvent(tn.manifestParsed),[2]}}))}))},Object.defineProperty(Manifest.prototype,"segments",{get:function(){return this._segmentList.segments},enumerable:!0,configurable:!0}),Object.defineProperty(Manifest.prototype,"extURI",{get:function(){if(!this._extURI){var t=this._data.match(Zo);Pt.debug("manifest: EXT_X_KEY_URI matches",t),this._extURI=t&&t[1]||void 0}return this._extURI},enumerable:!0,configurable:!0}),Manifest.prototype.stop=function(){this._manifestRefreshInterval&&clearInterval(this._manifestRefreshInterval)},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",Promise)],Manifest.prototype,"liveRadioRefresh",null),Manifest}(he),ra=function(){function Buffer(t){var n=this,l=t.mediaSource,d=t.manifest,p=t.currentTime,h=t.duration;this._currentBufferIndex=0,this.isBufferActionRunning=!1,this.timeToTrim=10,this.mediaSource=l,Pt.trace("mediasource",l),this.sourceBuffer=l.addSourceBuffer('audio/mp4;codecs="mp4a.40.2"'),d.mediaItem.isLiveRadioStation&&(this.sourceBuffer.mode="sequence"),Pt.trace("sourcebuffer",this.sourceBuffer),this.manifest=d,this.manifest.addEventListener(tn.manifestParsed,(function(){n.currentBufferIndex=n.currentBufferIndex})),this._currentTime=p||0,this.duration=h,this.updateEndHandler=this.dequeueBufferAction.bind(this),this.bufferActionsQueue=[],this.sourceBuffer.addEventListener("updateend",this.updateEndHandler),this.addSegment(0)}return Object.defineProperty(Buffer.prototype,"currentTime",{get:function(){return this._currentTime},set:function(t){if(this._currentTime!==t){this._currentTime=t;var n=this.isOverBufferLimit,l=this.timeToTrim,d=t>this.timeToTrim;n&&d&&(this.removeToTime(l),this.addSegment(this.currentBufferIndex+1),this.timeToTrim+=10)}},enumerable:!0,configurable:!0}),Object.defineProperty(Buffer.prototype,"segments",{get:function(){return this.manifest.segments||[]},enumerable:!0,configurable:!0}),Object.defineProperty(Buffer.prototype,"currentBufferIndex",{get:function(){return this._currentBufferIndex},set:function(t){var n=this.segments,l=this.mediaSource,d=this.manifest;n.length&&t!==n.length-1?this.addSegment(t+1):d.mediaItem.isLiveRadioStation||this.addBufferAction(l.endOfStream.bind(l)),this._currentBufferIndex=t},enumerable:!0,configurable:!0}),Object.defineProperty(Buffer.prototype,"isBufferUpdating",{get:function(){return this.isBufferActionRunning||this.sourceBuffer.updating},enumerable:!0,configurable:!0}),Object.defineProperty(Buffer.prototype,"startBufferedTime",{get:function(){return 0===this.sourceBuffer.buffered.length?0:this.sourceBuffer.buffered.start(0)},enumerable:!0,configurable:!0}),Object.defineProperty(Buffer.prototype,"endBufferedTime",{get:function(){return 0===this.sourceBuffer.buffered.length?0:this.sourceBuffer.buffered.end(0)},enumerable:!0,configurable:!0}),Buffer.prototype.waitForSeekToLoad=function(t){return __awaiter(this,void 0,void 0,(function(){var n=this;return __generator(this,(function(l){return[2,new Promise((function(l){n.addBufferAction(n._checkSeekFinished(t,l))}))]}))}))},Buffer.prototype._checkSeekFinished=function(t,n){var l=this;return function(){if(t>l.startBufferedTime&&t<l.endBufferedTime)return n();l.addBufferAction(l._checkSeekFinished(t,n))}},Buffer.prototype.seek=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l,d,p,h,f,y;return __generator(this,(function(v){switch(v.label){case 0:return l=(n=this).startBufferedTime,d=n.endBufferedTime,p=n.duration,h=n.segments,l<=t&&d>=t?[2]:t>p?[2]:(this.removeToTime(d),this.timeToTrim=10*Math.floor(t/10),f=t/p<.05?t/p:t/p-.05,y=Math.floor(h.length*f),this.addSegment(y),[4,this.waitForSeekToLoad(t)]);case 1:return v.sent(),[2]}}))}))},Buffer.prototype.stop=function(){var t=this.mediaSource;try{this.bufferActionsQueue.length=0,this.addBufferAction(t.endOfStream.bind(t))}catch(e){}},Buffer.prototype.remove=function(){this.sourceBuffer.removeEventListener("updateend",this.updateEndHandler);try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){return}},Buffer.prototype.dequeueBufferAction=function(){return __awaiter(this,void 0,void 0,(function(){var t,n;return __generator(this,(function(l){switch(l.label){case 0:return t=this.bufferActionsQueue,this.isBufferUpdating?[2]:(n=t.shift())?(this.isBufferActionRunning=!0,[4,n()]):[3,2];case 1:if(l.sent(),this.isBufferActionRunning=!1,!this.isBufferUpdating)return[2,this.dequeueBufferAction()];l.label=2;case 2:return[2]}}))}))},Buffer.prototype.addBufferAction=function(t){this.bufferActionsQueue.push(t),this.isBufferUpdating||asAsync(this.dequeueBufferAction())},Buffer.prototype.addSegment=function(t){var n=this;this.addBufferAction((function(){return __awaiter(n,void 0,void 0,(function(){var n,l,d,p;return __generator(this,(function(h){switch(h.label){case 0:if(n=this.segments,!(l=n[t]))return[2];h.label=1;case 1:return h.trys.push([1,3,,4]),[4,l.load()];case 2:d=h.sent();try{this.sourceBuffer.appendBuffer(d),this.currentBufferIndex=t,this.isOverBufferLimit=!1}catch(f){"QuotaExceededError"===f.name?this.isOverBufferLimit=!0:Pt.warn("Error appending to source buffer",f)}return[3,4];case 3:return p=h.sent(),Pt.error("Error loading segment",p),[3,4];case 4:return[2]}}))}))}))},Buffer.prototype.removeToTime=function(t){var n=this;this.addBufferAction((function(){return n.sourceBuffer.remove(0,t),new Promise((function(t){return t()}))}))},Buffer}(),ia=nr.mediaPlaybackError,na=function(n){function AudioPlayer(t){var l=n.call(this,t)||this;return l.currentAudioTrack=void 0,l.currentTextTrack=void 0,l.textTracks=[],l.audioTracks=[],l.mediaPlayerType="audio",l}return __extends(AudioPlayer,n),Object.defineProperty(AudioPlayer.prototype,"_targetElement",{get:function(){return this.audio},enumerable:!0,configurable:!0}),AudioPlayer.prototype.initializeExtension=function(){return __awaiter(this,void 0,void 0,(function(){var t=this;return __generator(this,(function(n){switch(n.label){case 0:return this.extension=new zo(this.audio,'audio/mp4;codecs="mp4a.40.2"'),[4,this.extension.initializeKeySystem()];case 1:return n.sent(),this.extension.addEventListener(tn.playbackLicenseError,(function(n){t._licenseError(),t._dispatcher.publish(ia,n)})),this.extension.addEventListener(tn.playbackSessionError,(function(n){t._dispatcher.publish(ia,new ke(ke.MEDIA_SESSION,n))})),[2]}}))}))},AudioPlayer.prototype.initializeMediaElement=function(){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(n){return(t=function(){var t=St.pop();return t?Pt.debug("dom-helpers: retrieving audio tag, "+St.length+" remain"):(Pt.debug("dom-helpers: no available audio tags, creating one"),t=document.createElement("audio")),t}()).autoplay=!1,t.id="apple-music-player",t.controls=!1,t.muted=!1,t.playbackRate=1,t.preload="metadata",t.volume=1,this.audio=t,document.body.appendChild(t),Pt.debug("initializedMediaElement",t),[2]}))}))},AudioPlayer.prototype.isPlayerSupported=function(){return!0},AudioPlayer.prototype._stopMediaElement=function(){var t,l;return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(d){switch(d.label){case 0:return[4,n.prototype._stopMediaElement.call(this)];case 1:return d.sent(),null===(t=this.manifest)||void 0===t||t.stop(),null===(l=this._buffer)||void 0===l||l.stop(),[2]}}))}))},AudioPlayer.prototype.playItemFromEncryptedSource=function(n,l){return void 0===l&&(l=!1),__awaiter(this,void 0,void 0,(function(){var d,p,h,f=this;return __generator(this,(function(y){switch(y.label){case 0:return d=this._paused&&!l,n.playRawAssetURL?(n.playbackType=t.PlaybackType.unencryptedFull,this.nowPlayingItem=n,[2,this._playAssetURL(n.assetURL,d)]):(this.extension.initiated=l,this.extension.setMediaItem(n),n.playbackType=t.PlaybackType.encryptedFull,this.nowPlayingItem=n,n.state=pr.loading,[4,ta.load(n,!1)]);case 1:return p=y.sent(),this.manifest=p,n.isLiveRadioStation||(this.extension.extURI=p.extURI),n.state=pr.ready,this.extension.isFairplay?[2,this._playAssetURL(n.assetURL,d)]:[3,2];case 2:return this._buffer&&this._buffer.remove(),h=new MediaSource,[4,this._playAssetURL(window.window.URL.createObjectURL(h),!0)];case 3:y.sent(),h.addEventListener("sourceopen",(function(l){if(window.window.URL.revokeObjectURL(f._targetElement.src),0===h.activeSourceBuffers.length&&(f._buffer=new ra({duration:n.playbackDuration/1e3,mediaSource:h,manifest:p}),!d&&f.playbackState!==t.PlaybackStates.paused))return f._playMedia()})),y.label=4;case 4:return[2]}}))}))},AudioPlayer.prototype.setPresentationMode=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,Promise.resolve()]}))}))},AudioPlayer}(zn),oa=function(t){function MediaExtensionStub(n){var l=t.call(this,n)||this;return l.audioTracks=[],l.textTracks=[],l.extURI="",l.hasMediaKeySupport=!0,l.initiated=!0,l.isFairplay=!0,l.hasMediaKeySupport=!0,l.hasMediaSession=!0,l}return __extends(MediaExtensionStub,t),MediaExtensionStub.prototype.cancelPendingRenewal=function(){},MediaExtensionStub.prototype.destroy=function(t){},MediaExtensionStub.prototype.setMediaItem=function(t){},MediaExtensionStub.prototype.initializeKeySystem=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this.session=new $o,[2]}))}))},MediaExtensionStub}(he),aa=function(){function PlayerStub(n){this.bitrate=t.PlaybackBitrate.STANDARD,this.audioTracks=[],this.canSupportDRM=!1,this.currentBufferedProgress=0,this.currentPlaybackDuration=0,this.currentPlaybackProgress=0,this.currentPlaybackTime=0,this.currentPlaybackTimeRemaining=0,this.formattedCurrentPlaybackDuration={hours:0,minutes:0},this.isPlaying=!1,this.isPrimaryPlayer=!0,this.isReady=!1,this.paused=!1,this.playbackRate=NaN,this.playbackState=t.PlaybackStates.none,this.playbackTargetAvailable=!1,this.playbackTargetIsWireless=!1,this.previewOnly=!1,this.textTracks=[],this.extension=new oa([]),this.hasAuthorization=!0,this.isDestroyed=!1,this._volume=1,this._dispatcher=n.services.dispatcher,this.windowHandlers=new Pn(this)}return Object.defineProperty(PlayerStub.prototype,"hasMediaElement",{get:function(){return!0},enumerable:!0,configurable:!0}),Object.defineProperty(PlayerStub.prototype,"isEngagedInPlayback",{get:function(){return!this.paused},enumerable:!0,configurable:!0}),Object.defineProperty(PlayerStub.prototype,"volume",{get:function(){return this._volume},set:function(t){this._volume=t,this._dispatcher.publish(nr.playbackVolumeDidChange,new Event("volumeChange"))},enumerable:!0,configurable:!0}),PlayerStub.prototype.destroy=function(){},PlayerStub.prototype.dispatch=function(){},PlayerStub.prototype.exitFullscreen=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.initialize=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.isPaused=function(){return this.paused},PlayerStub.prototype.mute=function(){},PlayerStub.prototype.newSeeker=function(){return new gn(this)},PlayerStub.prototype.pause=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.play=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.playItemFromEncryptedSource=function(t,n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.playItemFromUnencryptedSource=function(t,n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.preload=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.prepareToPlay=function(t,n,l){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.seekToTime=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.requestFullscreen=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.setPresentationMode=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.showPlaybackTargetPicker=function(){},PlayerStub.prototype.stop=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.stopMediaAndCleanup=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2]}))}))},PlayerStub.prototype.supportsPictureInPicture=function(){return!1},PlayerStub.prototype.tsidChanged=function(){},PlayerStub}(),sa=function(){function MediaSessionManager(t,n){this.capabilities=t,this.dispatcher=n,this.session=navigator.mediaSession,this.session&&(this.dispatcher.subscribe(nr.nowPlayingItemDidChange,this.onNowPlayingItemDidChange),this.dispatcher.subscribe(nr.capabilitiesChanged,this.onCapabilitiesChanged),this._setMediaSessionHandlers())}return MediaSessionManager.prototype.onCapabilitiesChanged=function(){this._resetHandlers(),this._setMediaSessionHandlers()},MediaSessionManager.prototype.onNowPlayingItemDidChange=function(t,n){var l=n.item;this._setMediaSessionMetadata(l)},MediaSessionManager.prototype._setMediaSessionMetadata=function(t){var n,l;this.session&&"MediaMetadata"in window&&t&&(this.session.metadata=new window.MediaMetadata({title:t.title,artist:null!==(n=t.artistName)&&void 0!==n?n:null===(l=t.attributes)||void 0===l?void 0:l.showTitle,album:t.albumName,artwork:t.artwork?[96,128,192,256,384,512].map((function(n){return{src:formatArtworkURL(t.artwork,n,n),sizes:n+"x"+n,type:"image/jpeg"}})):[]}))},MediaSessionManager.prototype._setMediaSessionHandlers=function(){var t=this;this.session&&(this._resetHandlers(),this.session.setActionHandler("play",(function(){var n;return null===(n=t.controller)||void 0===n?void 0:n.play()})),this.capabilities.canPause?this.session.setActionHandler("pause",(function(){var n;return null===(n=t.controller)||void 0===n?void 0:n.pause()})):this.session.setActionHandler("pause",(function(){var n;return null===(n=t.controller)||void 0===n?void 0:n.stop()})),this.capabilities.canSeek&&(this.session.setActionHandler("seekforward",(function(){var n;return null===(n=t.controller)||void 0===n?void 0:n.seekForward()})),this.session.setActionHandler("seekbackward",(function(){var n;return null===(n=t.controller)||void 0===n?void 0:n.seekBackward()}))),this.capabilities.canSkipToNextItem&&this.session.setActionHandler("nexttrack",(function(){var n;return null===(n=t.controller)||void 0===n?void 0:n.skipToNextItem()})),this.capabilities.canSkipToPreviousItem&&this.session.setActionHandler("previoustrack",(function(){var n;return null===(n=t.controller)||void 0===n?void 0:n.skipToPreviousItem()})))},MediaSessionManager.prototype._resetHandlers=function(){this.session&&(this.session.setActionHandler("play",void 0),this.session.setActionHandler("pause",void 0),this.session.setActionHandler("seekforward",void 0),this.session.setActionHandler("seekbackward",void 0),this.session.setActionHandler("nexttrack",void 0),this.session.setActionHandler("previoustrack",void 0))},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],MediaSessionManager.prototype,"onCapabilitiesChanged",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],MediaSessionManager.prototype,"onNowPlayingItemDidChange",null),MediaSessionManager}();!function(t){t[t.PAUSE=0]="PAUSE",t[t.EDIT_QUEUE=1]="EDIT_QUEUE",t[t.SEEK=2]="SEEK",t[t.REPEAT=3]="REPEAT",t[t.SHUFFLE=4]="SHUFFLE",t[t.SKIP_NEXT=5]="SKIP_NEXT",t[t.SKIP_PREVIOUS=6]="SKIP_PREVIOUS",t[t.SKIP_TO_ITEM=7]="SKIP_TO_ITEM"}(ea||(ea={}));var ua=function(){function Capabilities(t){this._dispatcher=t,this._checkCapability=function(t){return!1},this._mediaSession=new sa(this,t)}return Object.defineProperty(Capabilities.prototype,"controller",{set:function(t){this._mediaSession.controller=t},enumerable:!0,configurable:!0}),Capabilities.prototype.updateChecker=function(t){this._checkCapability!==t&&(this._checkCapability=t,this._dispatcher.publish(nr.capabilitiesChanged))},Object.defineProperty(Capabilities.prototype,"canEditPlaybackQueue",{get:function(){return this._checkCapability(ea.EDIT_QUEUE)},enumerable:!0,configurable:!0}),Object.defineProperty(Capabilities.prototype,"canPause",{get:function(){return this._checkCapability(ea.PAUSE)},enumerable:!0,configurable:!0}),Object.defineProperty(Capabilities.prototype,"canSeek",{get:function(){return this._checkCapability(ea.SEEK)},enumerable:!0,configurable:!0}),Object.defineProperty(Capabilities.prototype,"canSetRepeatMode",{get:function(){return this._checkCapability(ea.REPEAT)},enumerable:!0,configurable:!0}),Object.defineProperty(Capabilities.prototype,"canSetShuffleMode",{get:function(){return this._checkCapability(ea.SHUFFLE)},enumerable:!0,configurable:!0}),Object.defineProperty(Capabilities.prototype,"canSkipToNextItem",{get:function(){return this._checkCapability(ea.SKIP_NEXT)},enumerable:!0,configurable:!0}),Object.defineProperty(Capabilities.prototype,"canSkipToMediaItem",{get:function(){return this._checkCapability(ea.SKIP_TO_ITEM)},enumerable:!0,configurable:!0}),Object.defineProperty(Capabilities.prototype,"canSkipToPreviousItem",{get:function(){return this._checkCapability(ea.SKIP_PREVIOUS)},enumerable:!0,configurable:!0}),Capabilities}(),isArrayOf=function(t,n){return Array.isArray(t)&&(0===t.length||n(t[0]))};function isLive(t){return!!t&&!!t.attributes&&!!t.attributes.isLive}function isStream$1(t){var n=!!t&&!!t.attributes&&!!t.attributes.playParams&&t.attributes.playParams.format;return void 0!==n&&"stream"===n}function isLiveRadioStation(t){return isLive(t)&&isStream$1(t)}function isBroadcastRadio(t){return isLive(t)&&isStream$1(t)&&void 0!==t.attributes.stationProviderName&&"Shoutcast"===t.attributes.streamingRadioSubType}function getFilterFromFlags(t){var n=t.includes("radio-live"),l=t.includes("radio-aod"),d=t.includes("radio-broadcast");return function(t){return(!n||n&&!isLiveRadioStation(t))&&(!l||l&&!function(t){return!isLive(t)&&isStream$1(t)&&"Episode"===t.attributes.streamingRadioSubType}(t))&&(!d||d&&!isBroadcastRadio(t))}}var ca={album:"albums",albums:"albums",artist:"artists",artists:"artists",song:"songs",songs:"songs"};var loadLiveRadioAssets=function(t,n,l){return __awaiter(void 0,void 0,void 0,(function(){var d,p,h,f,y,v,g,_,m,b,P,k;return __generator(this,(function(T){switch(T.label){case 0:return d=new Headers({Authorization:"Bearer "+n,Accept:"application/json","Content-Type":"application/json","X-Apple-Music-User-Token":""+l}),p=__assign(__assign({},t.playParams),{keyFormat:"web"}),h=urlEncodeParameters(p),f=ur.urls.mediaApi+"/play/assets?"+h,[4,fetch(f,{method:"GET",headers:d})];case 1:if(500!==(y=T.sent()).status)return[3,2];throw(_=new ke(ke.SERVER_ERROR)).data=t,_;case 2:if(403!==y.status)return[3,7];v=void 0,T.label=3;case 3:return T.trys.push([3,5,,6]),[4,y.json()];case 4:return v=T.sent(),v=null===(P=null==v?void 0:v.errors)||void 0===P?void 0:P[0],[3,6];case 5:return T.sent(),[3,6];case 6:throw g="40303"===(null==v?void 0:v.code)?ke.SUBSCRIPTION_ERROR:ke.ACCESS_DENIED,(_=new ke(g,null!==(k=null==v?void 0:v.title)&&void 0!==k?k:null==v?void 0:v.detail)).data=t,_;case 7:if(!y.ok)throw(_=new ke(ke.CONTENT_UNAVAILABLE)).data=t,_;T.label=8;case 8:return[4,y.json()];case 9:return m=T.sent(),b=m.results.assets[0],Pt.debug("media-item: loaded data from "+f+": "+JSON.stringify(b)),[2,b]}}))}))},prepareMediaAPIItem=function(t,n,l){return __awaiter(void 0,void 0,void 0,(function(){return __generator(this,(function(d){switch(d.label){case 0:return t.isLiveRadioStation?[4,prepareLiveRadioForEncryptedPlayback(t,n,l)]:[3,2];case 1:return d.sent(),[3,4];case 2:return[4,prepareItemWithMZPlay(t,n,l)];case 3:d.sent(),d.label=4;case 4:return[2]}}))}))},prepareLiveRadioForEncryptedPlayback=function(t,n,l){return __awaiter(void 0,void 0,void 0,(function(){var d,p,h,f,y,v,g,_,m,b;return __generator(this,(function(P){switch(P.label){case 0:if(!ur.features["playready-live-radio"]&&ln===et.PLAYREADY&&"video"!==t.attributes.mediaKind&&!ur.features["mse-live-radio"])throw new ke(ke.CONTENT_UNSUPPORTED,"LIVE_RADIO");return[4,loadLiveRadioAssets(t,n,l)];case 1:d=P.sent(),t.updateWithLoadedKeys({"hls-key-cert-url":d.fairPlayKeyCertificateUrl,"hls-key-server-url":d.keyServerUrl,"widevine-cert-url":d.widevineKeyCertificateUrl}),P.label=2;case 2:return P.trys.push([2,4,,5]),[4,fetch(d.url)];case 3:return p=P.sent(),[3,5];case 4:throw P.sent(),(h=new ke(ke.CONTENT_UNAVAILABLE)).data=t,h;case 5:return[4,p.text()];case 6:for(f=P.sent(),y=/^#EXT-X-STREAM-INF:.*BANDWIDTH=(\d+),CODECS="(.*)"\s*\n(.*$)/gim;v=y.exec(f);)g=__read(v,4),g[0],_=g[1],m=g[2],b=g[3],/^http(s)?:\/\//.test(b)||(b=rewriteLastUrlPath(d.url,b)),t.assets.push({bandwidth:Number(_),codec:m,URL:b});return[2]}}))}))},prepareItemWithMZPlay=function(t,n,l){return __awaiter(void 0,void 0,void 0,(function(){var d,p,h,f,y,v,g,_,m;return __generator(this,(function(b){switch(b.label){case 0:return Pt.debug("mk: loadWithMZPlay",t.playParams),"podcast-episodes"===t.type?(t.assetURL=t.attributes.assetUrl,[2]):[4,hasMusicSubscription()];case 1:return b.sent()?(d=t.playParams.id,p=new Headers({Authorization:"Bearer "+n,Accept:"application/json","Content-Type":"application/json","X-Apple-Music-User-Token":""+l}),h={salableAdamId:d},t.isCloudItem&&(h={},t.playParams.purchasedId&&(h.purchaseAdamId=t.playParams.purchasedId),t.playParams.catalogId&&(h.subscriptionAdamId=t.playParams.catalogId),(f=/^a\.(\d+)$/).test(d)?h.subscriptionAdamId=d.replace(f,"$1"):ae(d)&&(h.universalLibraryId=d)),[4,fetch(ur.urls.webPlayback,{method:"POST",body:JSON.stringify(h),headers:p})]):[2];case 2:return[4,b.sent().text()];case 3:return y=b.sent(),(v=JSON.parse(y))&&v.songList?(_=__read(v.songList,1),m=_[0],t.updateFromSongList(m),[2]):(g=ke.serverError(v),t.updateFromLoadError(g),Pt.debug("mk: prepareItemWithMZPlay - rejecting with error",g),[2,Promise.reject(g)])}}))}))};function isStringNotEmpty(t){return!function(t){return void 0===t||""===t.trim()}(t)}var la;function transform$1(t){return transform({"attributes.albumName":"metadata.playlistName","attributes.artistName":"metadata.artistName","attributes.artwork":function(){var n=get(t,"artworkURL");if(n)return function(t){var n=t.split("/").pop(),l=__read$1(!!n&&n.match(/\d+/g)||["100","100"],2),d=l[0],p=l[1];return{width:parseInt(d,10),height:parseInt(p,10),url:t.replace(d+"x"+p,"{w}x{h}")}}(n)},"attributes.composerName":"metadata.composerName","attributes.contentRating":function(){if(1===get(t,"metadata.explicit"))return"explicit"},"attributes.discNumber":function(){return get(t,"metadata.discNumber")||1},"attributes.durationInMillis":"metadata.duration","attributes.genreNames":function(){return[get(t,"metadata.genre")]},"attributes.isrc":function(){var n=get(t,"metadata.xid");if(n)return n.replace(/^([^:]+):isrc:/,"$1")},"attributes.name":"metadata.itemName","attributes.playParams.id":"metadata.itemId","attributes.playParams.kind":"metadata.kind","attributes.previews":function(){return[{url:get(t,"previewURL")}]},"attributes.releaseDate":"metadata.releaseDate","attributes.trackNumber":"metadata.trackNumber",assetURL:"URL",albumId:function(){return""+get(t,"metadata.playlistId")},artistId:function(){return""+get(t,"metadata.artistId")},cloudId:"metadata.cloud-id",id:function(){return""+get(t,"metadata.itemId")},flavor:"flavor",type:"metadata.kind"},t)}var da,pa=new st("dev-mk-debug");!function(t){t[t.none=0]="none",t[t.loading=1]="loading",t[t.ready=2]="ready",t[t.playing=3]="playing",t[t.ended=4]="ended",t[t.unavailable=5]="unavailable",t[t.restricted=6]="restricted",t[t.error=7]="error",t[t.unsupported=8]="unsupported"}(da||(da={}));var ha=da.none,fa=da.loading,ya=da.ready,va=da.playing,ga=da.ended,_a=da.unavailable,ma=da.restricted,ba=da.error,Pa=da.unsupported,ka=((la={})[ha]={allowed:[fa],unknown:[ga,_a,ma,ba,Pa]},la[fa]={allowed:[ya,ma,ba,Pa],unknown:[]},la[ya]={allowed:[va],unknown:[ba]},la[va]={allowed:[ga,ba],unknown:[_a,ma,Pa]},la[ga]={allowed:[],unknown:[]},la[_a]={allowed:[],unknown:[]},la[ma]={allowed:[],unknown:[]},la[ba]={allowed:[],unknown:[]},la[Pa]={allowed:[],unknown:[]},la),toName=function(t){return da[t]},createMediaItemStateGuard=function(t){void 0===t&&(t=ha);var n={current:t,set:function(t){var l=n.current;if(!function(t,n){return ka[t].allowed.includes(n)}(l,t)){var d=function(t,n){return ka[t].unknown.includes(n)}(l,t);pa.debug("MediaItem.state was changed from "+toName(l)+" to "+toName(t),d?"but it is unknown whether it should be allowed or not.":"and it should not be happening")}n.current=t}};return n},Ta=nr.mediaItemStateDidChange,Sa=nr.mediaItemStateWillChange,Aa=function(n){function MediaItem(l){void 0===l&&(l={});var d=n.call(this,[Ta,Sa])||this;d.bingeWatching=!1,d.hlsMetadata={},d.playbackType=t.PlaybackType.none,d._assets=[],d._state=createMediaItemStateGuard(),Pt.debug("mk: creating Media Item with options:",l);return l.id&&l.attributes?(Object.assign(d,l),d.type=d.playParams&&d.playParams.kind?d.playParams.kind:d.type||"song"):(d.id=l.id||generateUUID(),d.type=l.type||"song",d.attributes={playParams:{id:d.id,kind:d.type}}),d._context=l.context||{},l.container?d._container=l.container:l.containerId&&l.containerType&&(d._container={id:l.containerId,type:l.containerType}),d}return __extends(MediaItem,n),Object.defineProperty(MediaItem.prototype,"albumInfo",{get:function(){var t=this.albumName,n=this.artistName,l=[];return n&&l.push(n),t&&l.push(t),l.join(" - ")},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"albumName",{get:function(){return this.attributes.albumName},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"artistName",{get:function(){return this.attributes.genreNames&&this.attributes.genreNames.indexOf("Classical")>-1&&this.attributes.composerName?this.attributes.composerName:this.attributes.artistName},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"artwork",{get:function(){var t,n;return null!==(t=this.attributes.artwork)&&void 0!==t?t:null===(n=this.attributes.images)||void 0===n?void 0:n.coverArt16X9},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"artworkURL",{get:function(){if(this.artwork&&this.artwork.url)return this.artwork.url},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"assets",{get:function(){return this._assets},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"canPlay",{get:function(){return this.isPlayable&&this.isReady},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"container",{get:function(){return this._container},set:function(t){this._container=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"contentRating",{get:function(){return this.attributes.contentRating},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"context",{get:function(){return this._context},set:function(t){this._context=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"discNumber",{get:function(){return this.attributes.discNumber},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"hasContainerArtwork",{get:function(){return this.container&&this.container.attributes&&this.container.attributes.artwork&&this.container.attributes.artwork.url},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"hasPlaylistContainer",{get:function(){return this.container&&"playlists"===this.container.type&&this.container.attributes},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isLiveRadioStation",{get:function(){return isLiveRadioStation(this)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"info",{get:function(){return this.title+" - "+this.albumInfo},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isCloudItem",{get:function(){return this.playParams&&this.playParams.isLibrary||ae(this.id)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isCloudUpload",{get:function(){return-1===this._songId},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isExplicitItem",{get:function(){return"explicit"===this.contentRating},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isLoading",{get:function(){return this.state===pr.loading},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isPlayableMediaType",{get:function(){return-1!==ur.supportedMediaTypes.indexOf(this.type)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isPlayable",{get:function(){return!!this.isLiveRadioStation||!!this.isPlayableMediaType&&(this.needsPlayParams?!!this.playParams:this.isUTS?this.attributes.isEntitledToPlay:!!this.attributes.assetUrl)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isPlaying",{get:function(){return this.state===pr.playing},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isPreparedToPlay",{get:function(){if("song"===this.type)return!!this._assets&&!!this.keyURLs&&!!this._songId;if(this.isUTS){var t=isStringNotEmpty(this.assetURL),n=!!(this.keyURLs&&isStringNotEmpty(this.keyURLs["hls-key-cert-url"])&&isStringNotEmpty(this.keyURLs["hls-key-server-url"])&&isStringNotEmpty(this.keyURLs["widevine-cert-url"]));return t&&n}return!!isStringNotEmpty(this.assetURL)||this.playRawAssetURL&&!!isStringNotEmpty(this.attributes.assetUrl)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isrc",{get:function(){return this.attributes.isrc},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isReady",{get:function(){return this.state===pr.ready},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isRestricted",{get:function(){return this.state===pr.restricted},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isUTS",{get:function(){return["Episode","Movie","MusicMovie","Show","Vod"].includes(this.type)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"isUnavailable",{get:function(){return this.state===pr.unavailable},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"needsPlayParams",{get:function(){return["musicVideo","song"].includes(this.type)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"normalizedType",{get:function(){return t=this.type,(n=ca[t])||(n=t.replace(/_|[A-Z]/g,(function(t,n){return"_"===t?"-":(t=t.toLowerCase(),0===n?t:"-"+t)})),t.endsWith("y")?n=n.substring(0,n.length-1)+"ies":n.endsWith("s")||(n+="s"),ca[t]=n,n);var t,n},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"playbackData",{set:function(t){if(void 0!==t){this.previewURL&&(t.previewURL=this.previewURL);var n=transform$1(t);this.artwork&&n.artwork&&delete n.artwork,n.id!==this.id&&delete n.id,this.playParams&&n.attributes.playParams&&(n.attributes.playParams=this.playParams),Object.assign(this,n),Pt.debug("media-item: item merged with playbackData",this),this.state=pr.ready}},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"playbackDuration",{get:function(){return this.attributes.durationInMillis||this.attributes.durationInMilliseconds},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"playlistArtworkURL",{get:function(){return this.hasPlaylistContainer&&this.hasContainerArtwork?get(this,"container.attributes.artwork.url"):this.artworkURL},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"playlistName",{get:function(){return this.hasPlaylistContainer?get(this,"container.attributes.name"):this.albumName},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"playParams",{get:function(){return this.attributes.playParams},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"playRawAssetURL",{get:function(){return!(!this.isCloudUpload&&!ur.unencryptedPlaybackTypes[this.type])},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"previewURL",{get:function(){return get(this,"attributes.previews.0.url")||get(this,"attributes.trailers.0.assets.hlsUrl")||get(this,"attributes.movieClips.0.hlsUrl")},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"rating",{get:function(){return this.attributes.rating},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"releaseDate",{get:function(){if(this._releaseDate)return this._releaseDate;if(this.attributes&&(this.attributes.releaseDate||this.attributes.releaseDateTime)){var t=this.attributes.releaseDate||this.attributes.releaseDateTime;return this._releaseDate=/^\d{4}-\d{1,2}-\d{1,2}/.test(t)?new Date(t):void 0,this._releaseDate}},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"songId",{get:function(){return this._songId&&-1!==this._songId?this._songId:this.id},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"state",{get:function(){return this._state.current},set:function(t){var n={oldState:this._state.current,state:t};this._stateWillChange&&this._stateWillChange(this),this.dispatchEvent(Sa,n),this._state.set(t),this._stateDidChange&&this._stateDidChange(this),this.dispatchEvent(Ta,n)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"title",{get:function(){return this.attributes.name||this.attributes.title},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItem.prototype,"trackNumber",{get:function(){return this.attributes.trackNumber},enumerable:!0,configurable:!0}),MediaItem.prototype.beginMonitoringStateDidChange=function(t){this._stateDidChange=t},MediaItem.prototype.beginMonitoringStateWillChange=function(t){this._stateWillChange=t},MediaItem.prototype.endMonitoringStateDidChange=function(){this._stateDidChange=void 0},MediaItem.prototype.endMonitoringStateWillChange=function(){this._stateWillChange=void 0},MediaItem.prototype.isEqual=function(t){return this.id===t.id&&this.type===t.type&&this.attributes===t.attributes},MediaItem.prototype.prepareToPlay=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l,d;return __generator(this,(function(p){switch(p.label){case 0:return n=t.store,l=n.developerToken,d=n.userToken,void 0===l||void 0===d?[2,Promise.reject(new ke(ke.AUTHORIZATION_ERROR,"Unable to prepare media item for play."))]:this.isPreparedToPlay?(Pt.warn("media-item: item is prepared to play"),[2]):(Pt.debug("media-item: item.prepareToPlay playParams",this.playParams),this.state=pr.loading,this.isUTS?[4,(h=this,f=t.utsAPI,__awaiter(void 0,void 0,void 0,(function(){var t,n,l,d,p,y,v,g;return __generator(this,(function(_){switch(_.label){case 0:return[4,f.viewProductPersonalized({id:h.id,reload:!0})];case 1:return t=_.sent(),h.playables=null!==(v=null==t?void 0:t.playables)&&void 0!==v?v:null===(g=null==t?void 0:t.currentEpisode)||void 0===g?void 0:g.playables,h.channels=null==t?void 0:t.channels,hasPlayables(h)?(void 0!==(n=getDefaultPlayable(h))&&(h.ageGatePolicy=n.ageGatePolicy,h.playEvent=n.playEvent),0===(l=h.playables.reduce((function(t,n){return void 0!==n.assets&&t.push(n.assets),t}),[])).length?[2]:(d=__read(l,1),p=d[0],y=p.hlsUrl,ur.features.xtrick&&(y=addQueryParams(y,{xtrick:!0})),ur.features.isWeb&&(y=addQueryParams(y,{webbrowser:!0})),h.bingeWatching&&(y=addQueryParams(y,{bingeWatching:!0}),h.bingeWatching=!1),h.updateWithLoadedAssets(l,y),h.updateWithLoadedKeys({"hls-key-cert-url":p.fpsCertificateUrl,"hls-key-server-url":p.fpsKeyServerUrl,"widevine-cert-url":p.wideVineCertificateUrl},p.fpsKeyServerQueryParameters),[4,fetchHLSMetadata(h)])):[2];case 2:return _.sent(),h.state=pr.ready,[2]}}))})))]:[3,2]);case 1:return p.sent(),[3,4];case 2:return[4,prepareMediaAPIItem(this,l,d)];case 3:p.sent(),p.label=4;case 4:return[2]}var h,f}))}))},MediaItem.prototype.resetState=function(){this.endMonitoringStateWillChange(),this.endMonitoringStateDidChange(),this.state=pr.none},MediaItem.prototype.restrict=function(){this.isExplicitItem&&(this.state=pr.restricted,this._removePlayableData())},MediaItem.prototype.notSupported=function(){this.state=pr.unsupported,this._removePlayableData()},MediaItem.prototype.updateFromLoadError=function(t){switch(t.errorCode){case ke.CONTENT_RESTRICTED:this.state=pr.restricted;break;case ke.CONTENT_UNAVAILABLE:this.state=pr.unavailable;break;default:this.state=pr.error}},MediaItem.prototype.updateFromSongList=function(t){"musicVideo"===this.type?this.updateWithLoadedAssets(void 0,t["hls-playlist-url"]):this.updateWithLoadedAssets(t.assets),this._songId=t.songId,this.updateWithLoadedKeys({"hls-key-cert-url":t["hls-key-cert-url"],"hls-key-server-url":t["hls-key-server-url"],"widevine-cert-url":t["widevine-cert-url"]})},MediaItem.prototype.updateWithLoadedKeys=function(t,n){this.keyURLs=t,n&&(this.keyServerQueryParameters=n)},MediaItem.prototype.updateWithLoadedAssets=function(t,n){t&&(this._assets=t),n&&(this.assetURL=n)},MediaItem.prototype._removePlayableData=function(){var t,n,l;null===(t=this.attributes)||void 0===t||delete t.playParams,null===(n=this.attributes)||void 0===n||delete n.previews,null===(l=this.attributes)||void 0===l||delete l.trailers},MediaItem}(he);var wa={condition:function(){return!0},toOptions:function(t,n,l){return[__assign(__assign({},t),{context:l})]}},Ia={condition:function(t){var n;return"stations"===t.type&&(null===(n=t.attributes)||void 0===n?void 0:n.isLive)},toOptions:function(t,n,l){return[__assign(__assign({},t),{context:l,container:{attributes:t.attributes,id:t.id,type:t.type,name:null==l?void 0:l.featureName}})]}},hasRelationship=function(t){return function(n){var l,d;return!!(null===(d=null===(l=n.relationships)||void 0===l?void 0:l[t])||void 0===d?void 0:d.data)}},typeIs=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return function(n){var l=n.type;return t.includes(l)}},withBagPrefix=function(t){if(void 0!==t&&""!==t){var n=ur.prefix;return n?n+":"+t:t}},getContainerName$1=function(t,n){var l,d;return null!==(d=null!=n?n:null===(l=null==t?void 0:t.container)||void 0===l?void 0:l.name)&&void 0!==d?d:Te.SONG},Ea={toOptions:function(t,n,l){var d=__assign(__assign({id:t.id},n),{name:withBagPrefix(getContainerName$1(t,null==l?void 0:l.featureName))});return[{relationships:t.relationships,attributes:t.attributes,id:t.id,type:t.type,container:d,context:l}]},condition:typeIs("songs","library-songs","music-videos")},parseAssets=function(t){var n=t.type,l=t.attributes.assetTokens;return n.includes("udio")?function(t){if(void 0!==t)return t[__read(Object.keys(t),1)[0]]}(l):function(t){if(void 0!==t){var n=Object.keys(t);return t[n[n.length-1]]}}(l)},Ra={condition:typeIs("uploaded-audios","uploadedAudio","uploaded-videos","uploadedVideo"),toOptions:function(t,n,l){var d,p,h=__assign(__assign({},t),{context:l,attributes:__assign(__assign({},t.attributes),{assetUrl:parseAssets(t),playParams:null!==(p=null===(d=null==t?void 0:t.attributes)||void 0===d?void 0:d.playParams)&&void 0!==p?p:{id:t.id,kind:t.type}})});return void 0!==n&&(h.container=n),void 0!==(null==l?void 0:l.featureName)&&(h.container=__assign(__assign({},h.container),{name:null==l?void 0:l.featureName})),[h]}},Oa={toOptions:function(t,n,l){return t.relationships.episodes.data.map((function(t){return __assign(__assign({},t),{context:l})}))},condition:hasRelationship("episodes")},Ca=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var l in n)n.hasOwnProperty(l)&&(t[l]=n[l])};function __extends$4(t,n){function __(){this.constructor=t}Ca(t,n),t.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}var Ma=Object.assign||function(t){for(var n,l=1,d=arguments.length;l<d;l++)for(var p in n=arguments[l])Object.prototype.hasOwnProperty.call(n,p)&&(t[p]=n[p]);return t};function __decorate$2(t,n,l,d){var p,h=arguments.length,f=h<3?n:null===d?d=Object.getOwnPropertyDescriptor(n,l):d;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)f=Reflect.decorate(t,n,l,d);else for(var y=t.length-1;y>=0;y--)(p=t[y])&&(f=(h<3?p(f):h>3?p(n,l,f):p(n,l))||f);return h>3&&f&&Object.defineProperty(n,l,f),f}function __metadata$2(t,n){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(t,n)}function __awaiter$4(t,n,l,d){return new(l||(l=Promise))((function(p,h){function fulfilled(t){try{step(d.next(t))}catch(e){h(e)}}function rejected(t){try{step(d.throw(t))}catch(e){h(e)}}function step(t){t.done?p(t.value):new l((function(n){n(t.value)})).then(fulfilled,rejected)}step((d=d.apply(t,n||[])).next())}))}function __generator$4(t,n){var l,d,p,h,f={label:0,sent:function(){if(1&p[0])throw p[1];return p[1]},trys:[],ops:[]};return h={next:verb(0),throw:verb(1),return:verb(2)},"function"==typeof Symbol&&(h[Symbol.iterator]=function(){return this}),h;function verb(h){return function(y){return function(h){if(l)throw new TypeError("Generator is already executing.");for(;f;)try{if(l=1,d&&(p=d[2&h[0]?"return":h[0]?"throw":"next"])&&!(p=p.call(d,h[1])).done)return p;switch(d=0,p&&(h=[0,p.value]),h[0]){case 0:case 1:p=h;break;case 4:return f.label++,{value:h[1],done:!1};case 5:f.label++,d=h[1],h=[0];continue;case 7:h=f.ops.pop(),f.trys.pop();continue;default:if(!(p=f.trys,(p=p.length>0&&p[p.length-1])||6!==h[0]&&2!==h[0])){f=0;continue}if(3===h[0]&&(!p||h[1]>p[0]&&h[1]<p[3])){f.label=h[1];break}if(6===h[0]&&f.label<p[1]){f.label=p[1],p=h;break}if(p&&f.label<p[2]){f.label=p[2],f.ops.push(h);break}p[2]&&f.ops.pop(),f.trys.pop();continue}h=n.call(t,f)}catch(e){h=[6,e],d=0}finally{l=p=0}if(5&h[0])throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}([h,y])}}}function __read$4(t,n){var l="function"==typeof Symbol&&t[Symbol.iterator];if(!l)return t;var d,p,h=l.call(t),f=[];try{for(;(void 0===n||n-- >0)&&!(d=h.next()).done;)f.push(d.value)}catch(ba){p={error:ba}}finally{try{d&&!d.done&&(l=h.return)&&l.call(h)}finally{if(p)throw p.error}}return f}function __spread$4(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(__read$4(arguments[n]));return t}function formatRatingsContentType(t,n){return ae(n)&&!/^library-/.test(t)?"library-"+t:t}function makeRequest(t,n,l,d){return void 0===d&&(d={}),__awaiter$4(this,void 0,void 0,(function(){var p,h,f,y,v,g,_,m,b,P,k,T,S,A,w,I,E,R,O=this;return __generator$4(this,(function(C){switch(C.label){case 0:h=n,f=l&&l.ids,d=Object.assign({},d),y=d.shouldCacheResults,v=void 0===y||y,g=d.returnRawJSONApiRecords,_=void 0!==g&&g,m=d.isPersonalized,b=void 0!==m&&m,P=d.includePagination,k=void 0===P?t.defaultIncludePaginationMetadata:P,T=d.includeResponseMeta,S=void 0!==T&&T,delete d.shouldCacheResults,delete d.returnRawJSONApiRecords,delete d.isPersonalized,delete d.includePagination,delete d.includeResponseMeta,"string"==typeof f&&(h=n+"/"+encodeURIComponent(f),l&&delete l.ids),C.label=1;case 1:return C.trys.push([1,3,,4]),(k||S)&&(d.useRawResponse=!0),[4,t.request(h,l,d)];case 2:return p=C.sent(),[3,4];case 3:return"status"in(A=C.sent())?404===A.status?[2,Promise.reject(new ke(ke.CONTENT_UNAVAILABLE,"The requested content is not available."))]:[2,Promise.reject(ke.responseError(A))]:[2,Promise.reject(ke.internalError(A))];case 4:if(C.trys.push([4,10,,11]),w=p.results||p.data||p,"object"==typeof p&&"results"in p&&"meta"in p&&(w.meta=p.meta),0===w.length)return[2,Promise.reject(new ke(ke.CONTENT_UNAVAILABLE,"The requested content is not available."))];C.label=5;case 5:return C.trys.push([5,8,,9]),b&&t.userToken&&f?(f=Array.isArray(f)?f:[f],f=Array.from(new Set(f)),[4,Promise.all(f.map((function(l,d){return __awaiter$4(O,void 0,void 0,(function(){var p;return __generator$4(this,(function(h){switch(h.label){case 0:return[4,t.request(n+"/"+l,{fields:"inLibrary"})];case 1:return p=h.sent(),function(t,n){t.map((function(t,l){var d,p,h,f,y=n[l];if((null==t?void 0:t.attributes)&&(null==y?void 0:y.attributes)&&Object.keys(y.attributes).forEach((function(n){t.attributes[n]=y.attributes[n]})),(null===(p=null===(d=null==t?void 0:t.relationships)||void 0===d?void 0:d.tracks)||void 0===p?void 0:p.data)&&(null===(f=null===(h=null==y?void 0:y.relationships)||void 0===h?void 0:h.tracks)||void 0===f?void 0:f.data)){var v=y.relationships.tracks.data;t.relationships.tracks.data.forEach((function(t,n){var l=v[n];(null==t?void 0:t.attributes)&&(null==l?void 0:l.attributes)&&Object.keys(l.attributes).forEach((function(n){t.attributes[n]=l.attributes[n]}))}))}}))}([w[d]],p),[2]}}))}))})))]):[3,7];case 6:C.sent(),C.label=7;case 7:return[3,9];case 8:return C.sent(),[3,9];case 9:if(I=_?w:t.parseResultData(v,w),!k&&!S)return[2,I];if("results"in p){for(E in p.results)"meta"!==E&&(I[E]=paginateResultSet(p.results[E],I[E],t,l,d));return[2,I]}return[2,paginateResultSet(p,I,t,l,d)];case 10:return R=C.sent(),[2,Promise.reject(ke.parseError(R))];case 11:return[2]}}))}))}function paginateResultSet(t,n,l,d,p){var h,f;void 0===p&&(p={}),p.includePagination=!0;var y=Object.assign({},p);return delete y.offset,t.next&&(h=function(){return makeRequest(l,formatPaginatedUrl(l.url,t.next),d,y)}),t.previous&&(f=function(){return makeRequest(l,formatPaginatedUrl(l.url,t.previous),d,y)}),{data:n,next:h,previous:f,meta:t.meta}}function mapRequestResult(t,n){return"data"in t?(t.data=n(t.data),t):n(t)}function formatPaginatedUrl(t,n){var l=new window.window.URL(t).pathname,d=new RegExp("^"+l+"/");return n.replace(d,"")}var Da,getFeatureName=function(t,n){if(n)return n;var l,d=(void 0===(l=t.relationships.tracks.data)&&(l=[]),0!==l.length&&l.filter((function(t){var n=t.attributes;return!!n&&(n.workName||n.movementName||n.movementCount||n.movementNumber)})).length>0);return"albums"===t.type||"library-albums"===t.type?d?Te.ALBUM_CLASSICAL:Te.ALBUM:"playlists"===t.type||"library-playlists"===t.type?d?Te.PLAYLIST_CLASSICAL:Te.PLAYLIST:void 0},La=[{toOptions:function(t,n,l){var d={attributes:t.attributes,id:t.id,type:t.type,name:withBagPrefix(getFeatureName(t,null==l?void 0:l.featureName))};return t.relationships.tracks.data.map((function(t){return{attributes:t.attributes,id:t.id,type:t.type,container:d,context:l}}))},condition:hasRelationship("tracks")},Oa,Ea,Ia,Ra],isMediaAPIResource=function(t){return t&&void 0!==t.id&&void 0!==t.type},isMediaItem=function(t){return t&&void 0!==t.id},isMPMediaItem=function(t){return t&&void 0!==t.contentId&&void 0!==t.metadata&&void 0!==t.metadata.itemId&&void 0!==t.metadata.itemType},isQueueItems=function(t){return t&&t.items&&Array.isArray(t.items)},isQueueLoaded=function(t){return t&&t.loaded},isQueueURLOption=function(t){return t&&t.url},descriptorToMediaItems=function(t){return isQueueItems(t)||isQueueLoaded(t)?((n=isQueueLoaded(t)?loadedDescriptorToMediaItem(t):unloadedDescriptorToMediaItem(t)).forEach((function(n){return n.context=__assign(__assign({},t.context),n.context)})),n):[];var n},unloadedDescriptorToMediaItem=function(t){var n=t.items;return isArrayOf(n,isMPMediaItem)?n.map((function(t){return new Aa(function(t){var n=transform({id:"metadata.itemId",type:"metadata.itemType","attributes.contentRating":function(){if(1===get(t,"metadata.isExplicit"))return"explicit"},"attributes.playParams":function(){return 0!==get(t,"metadata.isPlayable")&&{id:get(t,"metadata.itemId"),kind:get(t,"metadata.itemType")}},"container.id":"metadata.containerId","container.name":"metadata.containerName","container.type":"metadata.containerType"},t);return __assign({attributes:{}},n)}(t))})):isArrayOf(n,isMediaItem)?n.map((function(t){return new Aa(t)})):[]},loadedDescriptorToMediaItem=function(t){var n=[],l=t.loaded,d=t.container,p=t.context;return void 0===l?[]:isArrayOf(l,isDataRecord)?(l.forEach((function(t){n.push.apply(n,__spread(dataRecordToMediaItems(t,d,p)))})),n):isArrayOf(l,isMediaAPIResource)?(l.forEach((function(t){n.push.apply(n,__spread(resourceToMediaItem(t,d,p)))})),n):isDataRecord(l)?dataRecordToMediaItems(l,d,p):isMediaAPIResource(l)?resourceToMediaItem(l,d,p):[]},dataRecordToMediaItems=function(t,n,l){void 0===l&&(l={});var d=t.serialize().data;return resourceToMediaItem(d,n,l)},resourceToMediaItem=function(t,n,l){return void 0===l&&(l={}),Pt.debug("_resourceToMediaItem",t),function(t,n,l){var d,p,h,f;return void 0===l&&(l={}),n=null!==(h=null===(p=null===(d=n)||void 0===d?void 0:d.serialize)||void 0===p?void 0:p.call(d).data)&&void 0!==h?h:n,(null!==(f=La.find((function(d){return d.condition(t,n,l)})))&&void 0!==f?f:wa).toOptions(t,n,l).map((function(t){return new Aa(t)}))}(t,n,l)},Na=function(){function BaseModifiableQueue(){this.canModifyQueue=!1}return BaseModifiableQueue.prototype.append=function(t){Pt.warn("Append is not supported for this type of playback")},BaseModifiableQueue.prototype.clear=function(){Pt.warn("Clear is not supported for this type of playback")},BaseModifiableQueue.prototype.prepend=function(t,n){Pt.warn("Prepend is not supported for this type of playback")},BaseModifiableQueue}(),xa=function(){function ModifiableQueue(t){this.canModifyQueue=!0,this.queue=t}return ModifiableQueue.prototype.append=function(t){var n=descriptorToMediaItems(t);this.queue.splice(this.queue.length,0,n)},ModifiableQueue.prototype.clear=function(){this.queue.length&&(this.queue.splice(0,this.queue.length),this.queue.reset())},ModifiableQueue.prototype.prepend=function(t,n){void 0===n&&(n=!1);var l=descriptorToMediaItems(t),d=(this.queue.position<0?0:this.queue.position)+1;n&&this.queue.splice(d,this.queue.length),this.queue.splice(d,0,l)},ModifiableQueue}();(Da=t.PlayerRepeatMode||(t.PlayerRepeatMode={}))[Da.none=0]="none",Da[Da.one=1]="one",Da[Da.all=2]="all";var Ua,Ba=function(){function BaseRepeatable(){this.canSetRepeatMode=!1}return Object.defineProperty(BaseRepeatable.prototype,"repeatMode",{get:function(){return t.PlayerRepeatMode.none},set:function(t){t!==this.repeatMode&&Pt.warn("setting repeatMode is not supported in this playback method")},enumerable:!0,configurable:!0}),BaseRepeatable}(),ja=function(){function Repeatable(n){this.dispatcher=n,this.canSetRepeatMode=!0,this._mode=t.PlayerRepeatMode.none}return Object.defineProperty(Repeatable.prototype,"repeatMode",{get:function(){return this._mode},set:function(n){n in t.PlayerRepeatMode&&n!==this._mode&&(this._mode=n,this.dispatcher.publish(nr.repeatModeDidChange,this._mode))},enumerable:!0,configurable:!0}),Repeatable}(),Fa=function(){function BaseSeekable(t){this.mediaItemPlayback=t,this.canSeek=!1}return BaseSeekable.prototype.getSeekSeconds=function(t){return Pt.warn("Seeking by predetermined amounts are not supported in this playback method"),{BACK:0,FORWARD:0}},BaseSeekable.prototype.seekBackward=function(t){Pt.warn("seekBackward is not supported in this playback method")},BaseSeekable.prototype.seekForward=function(t){Pt.warn("seekForward is not supported in this playback method")},BaseSeekable.prototype.seekToTime=function(t,n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return Pt.warn("seekToTime is not supported in this playback method"),[2]}))}))},BaseSeekable}(),Ka=function(){function Seekable(t,n){this._dispatcher=t,this.mediaItemPlayback=n,this.canSeek=!0}return Seekable.prototype.getSeekSeconds=function(t){return function(t){switch(t.type){case"uploaded-videos":case"uploadedVideo":case"musicVideo":return{FORWARD:10,BACK:10};default:return{FORWARD:30,BACK:15}}}(t)},Seekable.prototype.seekBackward=function(t){return void 0===t&&(t=this._seekToBeginning),__awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return void 0===this.mediaItemPlayback.nowPlayingItem?(Pt.warn("Cannot seekBackward when nowPlayingItem is not yet set."),[2]):(n=this.mediaItemPlayback.currentPlaybackTime-this.getSeekSeconds(this.mediaItemPlayback.nowPlayingItem).BACK)<0?[4,t.call(this)]:[3,2];case 1:return l.sent(),[2];case 2:return[4,this.seekToTime(n,zi.Interval)];case 3:return l.sent(),[2]}}))}))},Seekable.prototype.seekForward=function(t){return void 0===t&&(t=this._seekToEnd),__awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return void 0===this.mediaItemPlayback.nowPlayingItem?(Pt.warn("Cannot seekForward when nowPlayingItem is not yet set."),[2]):(n=this.mediaItemPlayback.currentPlaybackTime+this.getSeekSeconds(this.mediaItemPlayback.nowPlayingItem).FORWARD)>this.mediaItemPlayback.currentPlaybackDuration?[4,t.call(this)]:[3,2];case 1:return l.sent(),[2];case 2:return[4,this.seekToTime(n,zi.Interval)];case 3:return l.sent(),[2]}}))}))},Seekable.prototype.seekToTime=function(t,n){return void 0===n&&(n=zi.Manual),__awaiter(this,void 0,void 0,(function(){var l,d;return __generator(this,(function(p){switch(p.label){case 0:return l=this.mediaItemPlayback.currentPlaybackTime,d=Math.min(Math.max(0,t),this.mediaItemPlayback.currentPlaybackDuration-1),[4,this.mediaItemPlayback.seekToTime(d,n)];case 1:return p.sent(),this._dispatcher.publish(er.playbackSeek,{startPosition:l,position:d,seekReasonType:n}),[2]}}))}))},Seekable.prototype._seekToBeginning=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,this.seekToTime(0,zi.Interval)];case 1:return t.sent(),[2]}}))}))},Seekable.prototype._seekToEnd=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,this.seekToTime(this.mediaItemPlayback.currentPlaybackDuration,zi.Interval)];case 1:return t.sent(),[2]}}))}))},Seekable}();!function(t){t[t.off=0]="off",t[t.songs=1]="songs"}(Ua||(Ua={}));var Va,$a="Shuffling is not supported in this playback method.",Ha=function(){function BaseShuffler(){this.canSetShuffleMode=!1}return Object.defineProperty(BaseShuffler.prototype,"shuffle",{set:function(t){Pt.warn($a)},enumerable:!0,configurable:!0}),Object.defineProperty(BaseShuffler.prototype,"shuffleMode",{get:function(){return Ua.off},set:function(t){Pt.warn($a)},enumerable:!0,configurable:!0}),BaseShuffler.prototype.checkAndReshuffle=function(t){Pt.warn($a)},BaseShuffler}(),za=function(){function Shuffler(t,n){var l=n.dispatcher;this.controller=t,this.canSetShuffleMode=!0,this.mode=Ua.off,this._unshuffledIDs=[],this.dispatcher=l,this.dispatcher.subscribe(er.queueModified,this.queueModifiedHandler),this._queue=t.queue}return Object.defineProperty(Shuffler.prototype,"queue",{get:function(){return this._queue},set:function(t){this._queue=t,this._unshuffledIDs=t.items.map((function(t){return t.id})),this.checkAndReshuffle(!1)},enumerable:!0,configurable:!0}),Shuffler.prototype.queueModifiedHandler=function(t,n){var l,d=n.start,p=n.added,h=n.removed;if(h.length>0){var f=h.map((function(t){return t.id}));this._unshuffledIDs=this._unshuffledIDs.filter((function(t){return!f.includes(t)}))}p.length>0&&(l=this._unshuffledIDs).splice.apply(l,__spread([d,0],p.map((function(t){return t.id}))))},Object.defineProperty(Shuffler.prototype,"shuffle",{set:function(t){this.shuffleMode=t?Ua.songs:Ua.off},enumerable:!0,configurable:!0}),Object.defineProperty(Shuffler.prototype,"shuffleMode",{get:function(){return this.mode},set:function(t){t!==this.shuffleMode&&t in Ua&&(Pt.debug("mk: set shuffleMode from "+this.shuffleMode+" to "+t),this.mode=t,this.mode===Ua.songs?this.shuffleQueue():this.unshuffleQueue(),this.controller.nowPlayingItem&&(this._queue.position=this._queue.indexForItem(this.controller.nowPlayingItem.id)),this.dispatcher.publish(nr.shuffleModeDidChange,this.shuffleMode))},enumerable:!0,configurable:!0}),Shuffler.prototype.checkAndReshuffle=function(t){void 0===t&&(t=!1),this.shuffleMode===Ua.songs&&this.shuffleQueue(t)},Shuffler.prototype.shuffleQueue=function(t){void 0===t&&(t=!0);for(var n=this._queue.items.length,l=__spread(this._queue.items);n--;){var d=Math.floor(n*Math.random()),p=l[d];l[d]=l[n],l[n]=p}this._queue.replaceQueueItems(l,t)},Shuffler.prototype.unshuffleQueue=function(t){void 0===t&&(t=!0);var n=[],l=this._unshuffledIDs.reduce((function(t,n,l){return t[n]=l,t}),{}),d=[];this._queue.items.forEach((function(t){var p=l[t.id];void 0===p&&d.push(t),n[p]=t})),n=n.filter(Boolean),this._queue.replaceQueueItems(n.concat(d),t)},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[String,Object]),__metadata("design:returntype",void 0)],Shuffler.prototype,"queueModifiedHandler",null),Shuffler}();!function(t){t.continuous="continuous",t.serial="serial"}(Va||(Va={}));var Wa,Ya=nr.queueItemsDidChange,qa=function(){function PlaybackController(t){this._context={},this.onPlaybackStateDidChange=this.onPlaybackStateDidChange.bind(this),this._services=t.services,this._playerOptions=t,this.storekit=t.storekit,this._skipIntro=new mr({controller:this,services:t.services}),this._upNext=new br({controller:this,services:t.services}),this._rollMonitor=new _r({controller:this,services:t.services}),this._queueModifier=new Na,this._shuffler=new Ha,this._seekable=new Fa(this._mediaItemPlayback),this._repeatable=new Ba}return Object.defineProperty(PlaybackController.prototype,"context",{get:function(){return this._context},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"continuous",{get:function(){return this._continuous||this.hasAuthorization},set:function(t){this._continuous=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"currentBufferedProgress",{get:function(){return this._mediaItemPlayback.currentBufferedProgress},set:function(t){this._mediaItemPlayback.currentBufferedProgress=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"currentPlaybackProgress",{set:function(t){this._mediaItemPlayback.currentPlaybackProgress=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"_dispatcher",{get:function(){return this._services.dispatcher},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"formattedCurrentPlaybackDuration",{get:function(){return this._mediaItemPlayback.formattedCurrentPlaybackDuration},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"hasAuthorization",{get:function(){return hasAuthorization(this.storekit)},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"isPlaying",{get:function(){return this._mediaItemPlayback.isPlaying},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"isPrimaryPlayer",{get:function(){return this._mediaItemPlayback.isPrimaryPlayer},set:function(t){this._mediaItemPlayback.isPrimaryPlayer=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"isReady",{get:function(){return this._mediaItemPlayback.isReady},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"_mediaItemPlayback",{get:function(){return this._services.mediaItemPlayback},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"nowPlayingItem",{get:function(){return this._mediaItemPlayback.nowPlayingItem},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"nowPlayingItemIndex",{get:function(){return this.queue?this.queue.position:-1},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"queue",{get:function(){return this._queue},set:function(t){this._prepareQueue(t),this._queue=t,this._shuffler.queue=this._queue,this._queueModifier.queue=this._queue,this._dispatcher.publish(Ya,t.items)},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"repeatMode",{get:function(){return this._repeatable.repeatMode},set:function(t){this._repeatable.repeatMode=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"seekSeconds",{get:function(){var t=this.nowPlayingItem;if(void 0!==t)return this._seekable.getSeekSeconds(t)},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"shuffle",{set:function(t){this._shuffler.shuffle=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"shuffleMode",{get:function(){return this._shuffler.shuffleMode},set:function(t){this._shuffler.shuffleMode=t},enumerable:!0,configurable:!0}),Object.defineProperty(PlaybackController.prototype,"storekit",{get:function(){return this._storekit},set:function(n){var l=this;n&&(n.addEventListener(Xt.authorizationStatusWillChange,(function(n){var d=n.authorizationStatus,p=n.newAuthorizationStatus;return __awaiter(l,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return this.isPlaying?d>$t.DENIED&&p<$t.RESTRICTED?[4,this.stop({endReasonType:t.PlayActivityEndReasonType.PLAYBACK_SUSPENDED,userInitiated:!1})]:[3,2]:[3,4];case 1:return n.sent(),[3,4];case 2:return[4,this.stop({userInitiated:!1})];case 3:n.sent(),n.label=4;case 4:return[2]}}))}))})),this._storekit=n)},enumerable:!0,configurable:!0}),PlaybackController.prototype.append=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return[4,this._dataForQueueOptions(t)];case 1:return n=l.sent(),this._queueModifier.append(n),[2,this.queue]}}))}))},PlaybackController.prototype._dataForQueueOptions=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,__assign(__assign({},t),{context:this.context})]}))}))},PlaybackController.prototype.clear=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this._queueModifier.clear(),[2,this.queue]}))}))},PlaybackController.prototype.changeToMediaAtIndex=function(t){return void 0===t&&(t=0),__awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return[4,this.stop()];case 1:return l.sent(),[4,this._changeToMediaAtIndex(t,!0)];case 2:return(n=l.sent())&&this._dispatcher.publish(er.playbackPlay,{item:n,position:0}),[2]}}))}))},PlaybackController.prototype.changeToMediaItem=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){return-1===(n=this.queue.indexForItem(t))?[2,Promise.reject(new ke(ke.MEDIA_DESCRIPTOR))]:[2,this.changeToMediaAtIndex(n)]}))}))},PlaybackController.prototype.activate=function(){Pt.debug("mk: base controller - activate"),this._dispatcher.unsubscribe(nr.playbackStateDidChange,this.onPlaybackStateDidChange),this._dispatcher.subscribe(nr.playbackStateDidChange,this.onPlaybackStateDidChange),this._skipIntro.activate(),this._upNext.activate(),this._rollMonitor.activate()},PlaybackController.prototype.deactivate=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,this.stop()];case 1:return t.sent(),this._dispatcher.unsubscribe(nr.playbackStateDidChange,this.onPlaybackStateDidChange),this._skipIntro.deactivate(),this._upNext.deactivate(),this._rollMonitor.deactivate(),[2]}}))}))},PlaybackController.prototype.destroy=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,this.deactivate()];case 1:return t.sent(),[2]}}))}))},PlaybackController.prototype.hasCapabilities=function(t){switch(t){case ea.SEEK:return this._seekable.canSeek;case ea.REPEAT:return this._repeatable.canSetRepeatMode;case ea.SHUFFLE:return this._shuffler.canSetShuffleMode;case ea.EDIT_QUEUE:return this._queueModifier.canModifyQueue;case ea.PAUSE:case ea.SKIP_NEXT:case ea.SKIP_TO_ITEM:return!0;case ea.SKIP_PREVIOUS:default:return!1}},PlaybackController.prototype.pause=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,this._mediaItemPlayback.pause(t)]}))}))},PlaybackController.prototype.play=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this.nowPlayingItem?[2,this._mediaItemPlayback.play()]:!this._queue||this._queue.isEmpty?[2]:this.nowPlayingItemIndex>=0?[2,this.changeToMediaAtIndex(this.nowPlayingItemIndex)]:-1!==this.queue.nextPlayableItemIndex?[2,this.changeToMediaAtIndex(this.queue.nextPlayableItemIndex)]:[2]}))}))},PlaybackController.prototype.playSingleMediaItem=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return[4,fetchHLSMetadata(t)];case 1:return l.sent(),this._dispatcher.publish(nr.queueItemsDidChange,[t]),[4,this._mediaItemPlayback.startMediaItemPlayback(t,!0)];case 2:return(n=l.sent())&&this._dispatcher.publish(er.playbackPlay,{item:n,position:0,userInitiated:!0}),[2]}}))}))},PlaybackController.prototype.onPlaybackStateDidChange=function(n,l){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return l.state!==t.PlaybackStates.ended?[2]:this.continuous||this.repeatMode===t.PlayerRepeatMode.one?(this._dispatcher.publish(er.applicationActivityIntent,{endReasonType:t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS,userInitiated:!1}),[4,this._next()]):[3,2];case 1:n.sent(),n.label=2;case 2:return[2]}}))}))},PlaybackController.prototype.preload=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._mediaItemPlayback.preload()]}))}))},PlaybackController.prototype.prepend=function(t,n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return[4,this._dataForQueueOptions(t)];case 1:return l=d.sent(),this._queueModifier.prepend(l,n),[2,this.queue]}}))}))},PlaybackController.prototype.prepareToPlay=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,this._mediaItemPlayback.prepareToPlay(t)]}))}))},PlaybackController.prototype.showPlaybackTargetPicker=function(){this._mediaItemPlayback.showPlaybackTargetPicker()},PlaybackController.prototype.seekBackward=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._seekable.seekBackward()]}))}))},PlaybackController.prototype.seekForward=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._seekable.seekForward(this.skipToNextItem.bind(this))]}))}))},PlaybackController.prototype.skipToNextItem=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._next(!0)]}))}))},PlaybackController.prototype.getNewSeeker=function(){return this._mediaItemPlayback.getNewSeeker()},PlaybackController.prototype.seekToTime=function(t,n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){switch(l.label){case 0:return[4,this._seekable.seekToTime(t,n)];case 1:return l.sent(),[2]}}))}))},PlaybackController.prototype.setQueue=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this.extractGlobalValues(t)];case 1:return n.sent(),[4,this._mediaItemPlayback.stop()];case 2:return n.sent(),[2,this.returnQueueForOptions(t)]}}))}))},PlaybackController.prototype.extractGlobalValues=function(t){var n;return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){return this._context=null!==(n=t.context)&&void 0!==n?n:{},void 0!==(l=t.featureName)&&(Pt.warn("featureName is deprecated, pass it inside context"),this._context.featureName=l),[2]}))}))},PlaybackController.prototype.stop=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this._mediaItemPlayback.stop(t)];case 1:return n.sent(),[2]}}))}))},PlaybackController.prototype._changeToMediaAtIndex=function(t,n){return void 0===t&&(t=0),void 0===n&&(n=!1),__awaiter(this,void 0,void 0,(function(){var l,d;return __generator(this,(function(p){switch(p.label){case 0:return this.queue.isEmpty?[2]:(this.queue.position=t,(l=this.queue.item(this.queue.position))?[4,this._mediaItemPlayback.startMediaItemPlayback(l,n)]:[2]);case 1:return(d=p.sent())||l.state!==pr.unsupported?[3,3]:[4,this.skipToNextItem()];case 2:return p.sent(),[2];case 3:return[2,d]}}))}))},PlaybackController.prototype._next=function(n){return void 0===n&&(n=!1),__awaiter(this,void 0,void 0,(function(){var l,d,p,h;return __generator(this,(function(f){switch(f.label){case 0:return this.queue.isEmpty?[2]:(l=this._mediaItemPlayback,this.queue.nextPlayableItemIndex<0?(Pt.debug("controller/index._next no next item available, stopping playback"),[4,this.stop({userInitiated:n})]):[3,2]);case 1:return f.sent(),l.playbackState=t.PlaybackStates.completed,[2];case 2:return d=this.isPlaying,p=l.currentPlaybackTime,[4,this._changeToMediaAtIndex(this.queue.nextPlayableItemIndex,n)];case 3:return h=f.sent(),this._notifySkip(d,h,{userInitiated:n,position:p,direction:t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS}),[2,h]}}))}))},PlaybackController.prototype._notifySkip=function(n,l,d){var p=d.userInitiated,h=d.direction,f=d.position;n?l?this._dispatcher.publish(er.playbackSkip,{item:l,userInitiated:p,direction:h,position:f}):this._dispatcher.publish(er.playbackStop,{userInitiated:p,position:f}):l&&this._dispatcher.publish(er.playbackPlay,__assign({item:l,position:0},p?{endReasonType:t.PlayActivityEndReasonType.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM}:{}))},PlaybackController.prototype._prepareQueue=function(t){Pt.debug("mk: _prepareQueue"),this.hasAuthorization&&(t.isRestricted=this.storekit.restrictedEnabled||!1),t.repeatable=this._repeatable},PlaybackController}(),parseQueueURLOption=function(t){if(isQueueURLOption(t)){var n=formattedMediaURL(t.url),l=n.contentId,d=n.kind,p=n.storefrontId;t[d]=l,ar.storefrontId=p,delete t.url,Pt.debug("parseQueueURLOption",t)}},Ga=nr.queueItemsDidChange,Qa=nr.queuePositionDidChange,Ja=function(){function Queue(t){this._itemIDs=[],this._items=[],this._isRestricted=!1,this._nextPlayableItemIndex=-1,this._position=-1,this._dispatcher=t.services.dispatcher,t.descriptor&&(this._items=descriptorToMediaItems(t.descriptor),this._reindex(),this.position=this._getStartItemPosition(t.descriptor.startWith))}return Object.defineProperty(Queue.prototype,"isEmpty",{get:function(){return 0===this.length},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"isRestricted",{get:function(){return this._isRestricted},set:function(t){this._isRestricted=t,this._isRestricted&&this._items&&(this._items=this._items.map((function(t){return t.restrict(),t})))},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"items",{get:function(){return this._items},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"length",{get:function(){return this._items.length},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"nextPlayableItem",{get:function(){if(-1!==this.nextPlayableItemIndex)return this.item(this.nextPlayableItemIndex)},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"nextPlayableItemIndex",{get:function(){return this._nextPlayableItemIndex=this._getNextPlayableItemIndex(),this._nextPlayableItemIndex},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"position",{get:function(){return this._position},set:function(t){this._updatePosition(t)},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"previousPlayableItem",{get:function(){if(void 0!==this.previousPlayableItemIndex)return this.item(this.previousPlayableItemIndex)},enumerable:!0,configurable:!0}),Object.defineProperty(Queue.prototype,"previousPlayableItemIndex",{get:function(){if(void 0===this._previousPlayableItemIndex)for(var t=this.position-1;t>-1;){var n=this.item(t);if(this._isItemPlayable(n)){this._previousPlayableItemIndex=t;break}t--}return this._previousPlayableItemIndex},enumerable:!0,configurable:!0}),Queue.prototype.indexForItem=function(t){return("string"==typeof t?this._itemIDs:this._items).indexOf(t)},Queue.prototype.item=function(t){return this._items&&this._items[t]},Queue.prototype.remove=function(t){if(logDeprecation("remove",{message:"The queue remove function has been deprecated"}),t===this.position)throw new ke(ke.INVALID_ARGUMENTS);this.splice(t,1)},Queue.prototype.splice=function(t,n,l){var d,p;void 0===l&&(l=[]);var h=(d=this._items).splice.apply(d,__spread([t,n],l));return(p=this._itemIDs).splice.apply(p,__spread([t,n],l.map((function(t){return t.id})))),this._dispatcher.publish(er.queueModified,{start:t,added:l,removed:h}),this._dispatcher.publish(Ga,this.items),h},Queue.prototype.replaceQueueItems=function(t,n){void 0===n&&(n=!0),this._isSameItems(t)?(this._items=t,this._reindex(),n&&this._dispatcher.publish(Ga,t)):Pt.warn("Cannot use replaceQueueItems with different items.")},Queue.prototype.reset=function(){var t=this.position;this._position=-1,this._dispatcher.publish(Qa,{oldPosition:t,position:this.position})},Queue.prototype._isSameItems=function(t){if(t.length!==this.length)return!1;var n,l,d=t.map((function(t){return t.id})).sort(),p=__spread(this._itemIDs).sort();try{n=JSON.stringify(d),l=JSON.stringify(p)}catch(e){return!1}return n===l},Queue.prototype._reindex=function(){this._items&&(this._itemIDs=this._items.map((function(t){return t.id})))},Queue.prototype._updatePosition=function(t){if(t!==this._position){var n=this._position;this._position=this._getNextPlayableItemIndex(t),this._previousPlayableItemIndex=void 0,this._dispatcher.publish(Qa,{oldPosition:n,position:this._position})}},Queue.prototype._getNextPlayableItemIndex=function(n){var l;void 0===n&&(n=this.position+1);for(var d=n;d<this.length;){var p=this.item(d);if(this._isItemPlayable(p))return d;d++}if((null===(l=this.repeatable)||void 0===l?void 0:l.repeatMode)===t.PlayerRepeatMode.all)for(d=0;d<=n;){p=this.item(d);if(this._isItemPlayable(p))return d;d++}return-1},Queue.prototype._getStartItemPosition=function(t){if(void 0===t)return-1;if("object"==typeof t&&"id"in t&&(t=t.id),"string"==typeof t)return this.indexForItem(t);var n=parseInt(""+t,10);return n>=0&&n<this.length?n:-1},Queue.prototype._isItemPlayable=function(t){return(null==t?void 0:t.isPlayable)||(null==t?void 0:t.previewURL)},Queue}(),Xa=function(){function StationTrackLoader(t,n,l,d){var p=l.dispatcher,h=l.logger,f=l.apiManager;void 0===d&&(d={}),this.queue=t,this.station=n,this.context=d,this.isActive=!1,this.dispatcher=p,this.logger=h,this.apiManager=f}return StationTrackLoader.prototype.activate=function(){this.dispatcher.unsubscribe(nr.queuePositionDidChange,this.checkLoadMore),this.dispatcher.subscribe(nr.queuePositionDidChange,this.checkLoadMore),this.isActive=!0},StationTrackLoader.prototype.deactivate=function(){this.dispatcher.unsubscribe(nr.queuePositionDidChange,this.checkLoadMore),this.isActive=!1},StationTrackLoader.prototype.start=function(){return this.isActive||this.activate(),this.loadNextTracks()},StationTrackLoader.prototype.checkLoadMore=function(){if(!(this.queue.isEmpty||this.queue.nextPlayableItemIndex>=0))return this.loadNextTracks()},StationTrackLoader.prototype.loadNextTracks=function(){var t,n;return __awaiter(this,void 0,void 0,(function(){var l,d;return __generator(this,(function(p){switch(p.label){case 0:return[4,null===(t=this.apiManager.mediaAPI)||void 0===t?void 0:t.nextStationTracks(this.station.id)];case 1:if(0===(l=null!==(n=p.sent())&&void 0!==n?n:[]).length)throw this.logger.warn("No track data is available for the current station",{stationId:this.station.id}),new ke(ke.CONTENT_UNAVAILABLE,"No track data is available for the current station.");return d=descriptorToMediaItems({context:this.context,loaded:l,container:this.station}),this.queue.splice(this.queue.length,0,d),[2]}}))}))},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],StationTrackLoader.prototype,"checkLoadMore",null),StationTrackLoader}();!function(t){t.artist="artist",t.song="song",t.station="station",t.radioStation="radioStation"}(Wa||(Wa={}));var isIdentityQueue=function(t){return t&&void 0!==t.identity},isLiveStationQueue=function(t){return t&&void 0!==t.station&&!0===t.isLive},isLiveQueue=function(t){return isIdentityQueue(t)||isLiveStationQueue(t)},Za=function(t){function ContinuousPlaybackController(n){var l=t.call(this,n)||this;return l.type=Va.continuous,l._isLive=!1,l._continuous=!0,l}return __extends(ContinuousPlaybackController,t),Object.defineProperty(ContinuousPlaybackController.prototype,"continuous",{get:function(){return!0},set:function(t){if(!0!==t)throw new ke(ke.UNSUPPORTED_ERROR,"Continuous playback cannot be disabled for station queues.")},enumerable:!0,configurable:!0}),Object.defineProperty(ContinuousPlaybackController.prototype,"context",{get:function(){return __assign({featureName:Te.STATION},this._context)},enumerable:!0,configurable:!0}),Object.defineProperty(ContinuousPlaybackController.prototype,"isLive",{get:function(){return this._isLive},set:function(t){t!==this._isLive&&(this._isLive=t,this._dispatcher.publish(nr.capabilitiesChanged))},enumerable:!0,configurable:!0}),ContinuousPlaybackController.prototype.changeToMediaItem=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this.generateMethodNotAvailable("changeToMediaItem"),[2]}))}))},ContinuousPlaybackController.prototype.hasCapabilities=function(n){switch(n){case ea.PAUSE:case ea.SKIP_NEXT:return!this.isLive;case ea.SKIP_PREVIOUS:case ea.SKIP_TO_ITEM:return!1;default:return t.prototype.hasCapabilities.call(this,n)}},ContinuousPlaybackController.prototype.pause=function(n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){return this.isLive?(this.generateMethodNotAvailable("pause"),[2]):[2,t.prototype.pause.call(this,n)]}))}))},ContinuousPlaybackController.prototype.skipToPreviousItem=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this.generateMethodNotAvailable("skipToPreviousItem"),[2]}))}))},ContinuousPlaybackController.prototype._dataForQueueOptions=function(n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return[4,t.prototype._dataForQueueOptions.call(this,n)];case 1:return l=d.sent(),this.isLive&&(l.loaded=this.station),[2,l]}}))}))},ContinuousPlaybackController.prototype.returnQueueForOptions=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l,d;return __generator(this,(function(p){switch(p.label){case 0:return this.isLive=isLiveQueue(t),this.isLive?isIdentityQueue(t)?[4,this.loadStationByIdentity(t.identity)]:[3,2]:[3,5];case 1:return n=p.sent(),[3,4];case 2:return isLiveStationQueue(t)?[4,this.loadStationByStationId(t.station)]:[3,4];case 3:n=p.sent(),p.label=4;case 4:return[3,7];case 5:return[4,this.loadStationByStationId(this.generateStationId(t))];case 6:n=p.sent(),p.label=7;case 7:return void 0===n?[2,Promise.reject(new ke(ke.UNSUPPORTED_ERROR,"Cannot load requested station"))]:(this.station=n,d={services:{dispatcher:this._dispatcher}},[4,this._dataForQueueOptions(t)]);case 8:return d.descriptor=p.sent(),l=d,this.queue=new Ja(l),this.isLive?[3,10]:(this.trackLoader=new Xa(this.queue,n,{dispatcher:this._dispatcher,logger:Pt,apiManager:this._services.apiManager},this.context),[4,this.trackLoader.start()]);case 9:p.sent(),p.label=10;case 10:return this._seekable=this.isLive?new Fa(this._mediaItemPlayback):new Ka(this._dispatcher,this._mediaItemPlayback),[2,this.queue]}}))}))},ContinuousPlaybackController.prototype.getNewSeeker=function(){return this.hasCapabilities(ea.SEEK)?t.prototype.getNewSeeker.call(this):new vn},ContinuousPlaybackController.prototype.skipToNextItem=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return this.isLive?(this.generateMethodNotAvailable("skipToNextItem"),[2]):[2,t.prototype.skipToNextItem.call(this)]}))}))},ContinuousPlaybackController.prototype.generateMethodNotAvailable=function(t){Pt.warn(t+" is not supported for this type of playback")},ContinuousPlaybackController.prototype.generateStationId=function(t){var n;if(isQueueURLOption(t)){var l=formattedMediaURL(t.url),d=l.contentId,p=l.kind,h=l.storefrontId;t[p]=d,ar.storefrontId=h,n=p}var f=t;if(f.artist)return"ra."+f.artist;if(f.song)return"ra."+f.song;if(f.station)return f.station;if(f.radioStation)return f.radioStation;throw new ke(ke.UNSUPPORTED_ERROR,n?n+" is not a supported option. Use setQueue instead.":"Unsupported options specified for setStationQueue. You may want setQueue instead.")},ContinuousPlaybackController.prototype.loadStationByIdentity=function(t){var n,l;return __awaiter(this,void 0,void 0,(function(){var d;return __generator(this,(function(p){switch(p.label){case 0:return[4,null===(l=null===(n=this._services.apiManager)||void 0===n?void 0:n.mediaAPI)||void 0===l?void 0:l.stations(void 0,{filter:{identity:t}})];case 1:return[2,(d=p.sent())&&d[0]]}}))}))},ContinuousPlaybackController.prototype.loadStationByStationId=function(t){var n,l;return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(d){return[2,null===(l=null===(n=this._services.apiManager)||void 0===n?void 0:n.mediaAPI)||void 0===l?void 0:l.station(t)]}))}))},ContinuousPlaybackController.prototype.activate=function(){t.prototype.activate.call(this),this.trackLoader&&this.trackLoader.activate()},ContinuousPlaybackController.prototype.deactivate=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,t.prototype.deactivate.call(this)];case 1:return n.sent(),this.trackLoader&&this.trackLoader.deactivate(),[2]}}))}))},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Number]),__metadata("design:returntype",Boolean)],ContinuousPlaybackController.prototype,"hasCapabilities",null),ContinuousPlaybackController}(qa);function loadRelationshipData(t,n,l,d){return void 0===d&&(d={}),__awaiter(this,void 0,void 0,(function(){var p,h,f,y;return __generator(this,(function(v){switch(v.label){case 0:return void 0===n?[2,l]:(void 0===d.limit&&(d.limit=100),void 0===d.offset&&(d.offset=0),p=n.relationship,h=n.method,f=t[h].bind(t),isDataRecord(l)?(void 0===l[p]&&l.setProperty(p,[],"relationships"),y=l[p]):(l.relationships=l.relationships||{},void 0===l.relationships[p]&&Object.defineProperty(l.relationships,p,{value:{data:[]},enumerable:!0}),y=l.relationships[p].data),[4,recursiveRelationshipLoad(f,[l.id,p,d],y)]);case 1:return v.sent(),[2,l]}}))}))}var es,ts,recursiveRelationshipLoad=function(t,n,l){return __awaiter(void 0,void 0,void 0,(function(){var d,p,h,f,y,v,g;return __generator(this,(function(_){switch(_.label){case 0:if(d=__read(n,3),p=d[0],h=d[1],f=d[2],(y=l.length)>0&&y<f.limit+f.offset)return[2,l];(v=__assign({},f)).offset=y,_.label=1;case 1:return _.trys.push([1,3,,4]),[4,t(p,h,v)];case 2:return g=_.sent(),[3,4];case 3:return _.sent(),[2,l];case 4:return l.push.apply(l,__spread(g)),g.length<v.limit?[2,l]:[2,recursiveRelationshipLoad(t,n,l)]}}))}))},getNamedQueueOptions=function(t,n){var l=[],d=t.namedQueueOptions;for(var p in n)Object.keys(d).includes(p)&&l.push([p,d[p]]);return l},loadNamedQueueData=function(t,n,l){return __awaiter(void 0,void 0,void 0,(function(){var d,p,h,f,y,v,g,_;return __generator(this,(function(m){switch(m.label){case 0:return d=__read(l,2),p=d[0],h=d[1],f=n[p],y=Array.isArray(f),v=y?""+f[0]:""+f,[4,t.getAPIForItem(v)];case 1:return[4,(g=m.sent())[h.apiMethod](f,n.parameters)];case 2:return _=m.sent(),y?[3,4]:[4,loadRelationshipData(g,h.relationshipMethod,_)];case 3:m.sent(),m.label=4;case 4:return[2,_]}}))}))},rs=function(){function PercentageWatcher(t,n,l){this.dispatcher=t,this.callback=n,this.percentage=l,this.threshold=-1}return PercentageWatcher.prototype.startMonitor=function(){this.dispatcher.unsubscribe(nr.playbackDurationDidChange,this.updateThreshold),this.dispatcher.unsubscribe(nr.playbackTimeDidChange,this.handleTimeChange),this.dispatcher.subscribe(nr.playbackDurationDidChange,this.updateThreshold),this.dispatcher.subscribe(nr.playbackTimeDidChange,this.handleTimeChange)},PercentageWatcher.prototype.stopMonitor=function(){this.dispatcher.unsubscribe(nr.playbackDurationDidChange,this.updateThreshold),this.dispatcher.unsubscribe(nr.playbackTimeDidChange,this.handleTimeChange),this.threshold=-1},PercentageWatcher.prototype.handleTimeChange=function(t,n){var l=n.currentPlaybackDuration,d=n.currentPlaybackTime;return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return this.threshold<0&&this.updateThreshold(t,{duration:l}),d<this.threshold?[2]:(this.stopMonitor(),[4,this.callback(d,this)]);case 1:return n.sent(),[2]}}))}))},PercentageWatcher.prototype.updateThreshold=function(t,n){var l=n.duration;this.threshold=l*this.percentage},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",Promise)],PercentageWatcher.prototype,"handleTimeChange",null),__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",void 0)],PercentageWatcher.prototype,"updateThreshold",null),PercentageWatcher}(),is=function(t){function Preloader(n){var l=t.call(this,n)||this;return l.watchers=[new rs(l.dispatcher,l.handlePlaybackThreshold,.3)],l}return __extends(Preloader,t),Preloader.prototype.handlePlaybackThreshold=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,this.playbackController.prepareToPlay(this._next,!0)];case 1:return t.sent(),[2]}}))}))},Preloader.prototype.shouldMonitor=function(){if(!t.prototype.shouldMonitor.call(this))return!1;if(!this.playbackController.hasAuthorization)return!1;var n=this.getNextPlayableItem();return void 0!==n&&!n.isPreparedToPlay},Preloader.prototype.startMonitor=function(){this._next=this.getNextPlayableItem(),t.prototype.startMonitor.call(this)},Preloader.prototype.clearMonitor=function(){t.prototype.clearMonitor.call(this),this._next=void 0},Preloader.prototype.getNextPlayableItem=function(){return this.playbackController.queue.nextPlayableItem},Preloader}(vr),ns=nr.queueIsReady;!function(t){t.album="album",t.musicVideo="musicVideo",t.playlist="playlist",t.song="song",t.episode="episode",t.podcast="podcast",t.uploadedAudio="uploadedAudio",t.uploadedVideo="uploadedVideo"}(es||(es={})),function(t){t.albums="albums",t.musicVideos="musicVideos",t.playlists="playlists",t.songs="songs",t.episodes="episodes",t.podcasts="podcasts",t.uploadedAudio="uploadedAudios",t.uploadedVideo="uploadedVideos"}(ts||(ts={}));var as=function(n){function SerialPlaybackController(t){var l=n.call(this,t)||this;l.type=Va.serial,l._queue=new Ja(t),l._repeatable=new ja(l._dispatcher);var d={controller:l,services:t.services};return l._seekable=new Ka(l._dispatcher,l._mediaItemPlayback),l._preloader=new is(d),l._shuffler=new za(l,{dispatcher:l._dispatcher}),l._queueModifier=new xa(l._queue),l}return __extends(SerialPlaybackController,n),SerialPlaybackController.prototype.activate=function(){n.prototype.activate.call(this),this._preloader.activate()},SerialPlaybackController.prototype.deactivate=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,n.prototype.deactivate.call(this)];case 1:return t.sent(),this._preloader.deactivate(),[2]}}))}))},SerialPlaybackController.prototype.hasCapabilities=function(t){return t===ea.SKIP_PREVIOUS||n.prototype.hasCapabilities.call(this,t)},SerialPlaybackController.prototype.prepareToPlay=function(n,l){return void 0===l&&(l=!1),__awaiter(this,void 0,void 0,(function(){var d=this;return __generator(this,(function(p){return Pt.debug("mk: SerialController - prepareToPlay - ",{item:n,preload:l}),n.isPlayable?[2,this._mediaItemPlayback.prepareToPlay(n).catch((function(n){var p=!l&&-1===[ke.DEVICE_LIMIT,ke.STREAM_UPSELL].indexOf(n.errorCode);if(d.continuous&&p)return d._dispatcher.publish(er.applicationActivityIntent,{endReasonType:t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS,userInitiated:!1}),d._next();throw n}))]:[2]}))}))},SerialPlaybackController.prototype.returnQueueForOptions=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l;return __generator(this,(function(d){switch(d.label){case 0:return parseQueueURLOption(t),void 0!==t.startPosition&&(logDeprecation("startPosition",{message:"startPosition has been deprecated in favor of startWith"}),void 0===t.startWith&&(t.startWith=t.startPosition)),[4,this._dataForQueueOptions(t)];case 1:if(n=d.sent(),l={services:{dispatcher:this._dispatcher},descriptor:n},void 0!==t.shuffleMode&&(this.shuffleMode=t.shuffleMode),this.queue=new Ja(l),0===this.queue.length)throw Pt.warn("No item data is available for the current media queue",t),new ke(ke.CONTENT_UNAVAILABLE,"No item data is available for the current media queue.");return this._dispatcher.publish(ns,this.queue.items),[2,this.queue]}}))}))},SerialPlaybackController.prototype.skipToPreviousItem=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._previous(!0)]}))}))},SerialPlaybackController.prototype._dataForQueueOptions=function(t){return __awaiter(this,void 0,void 0,(function(){var l,d,p,h,f;return __generator(this,(function(y){switch(y.label){case 0:return l=t,void 0!==(d=function(t,n){var l=getNamedQueueOptions(t,n);if(l.length>1)throw new ke(ke.UNSUPPORTED_ERROR,"Queues with multiple media types are not supported.");if(0!==l.length){var d=__read(l,1)[0],p=__read(d,2),h=p[0],f=p[1];if(Array.isArray(n[h])!==f.isPlural)throw new ke(ke.UNSUPPORTED_ERROR,f.isPlural?"Queue option "+h+" must be an array of id values":"Queue option "+h+" must be a single id value");return d}}(this._services.apiManager.apiService,t))?[3,2]:(p=[{}],[4,n.prototype._dataForQueueOptions.call(this,t)]);case 1:return[2,__assign.apply(void 0,[__assign.apply(void 0,p.concat([y.sent()])),l])];case 2:return h=l,[4,loadNamedQueueData(this._services.apiManager.apiService,t,d)];case 3:return h.loaded=y.sent(),f=[{}],[4,n.prototype._dataForQueueOptions.call(this,t)];case 4:return[2,__assign.apply(void 0,[__assign.apply(void 0,f.concat([y.sent()])),l])]}}))}))},SerialPlaybackController.prototype._next=function(l){return void 0===l&&(l=!1),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(d){switch(d.label){case 0:return this.queue.isEmpty||this.repeatMode!==t.PlayerRepeatMode.one?[3,2]:[4,this.play()];case 1:return d.sent(),[2,this.nowPlayingItem];case 2:return[2,n.prototype._next.call(this,l)]}}))}))},SerialPlaybackController.prototype._previous=function(n){return void 0===n&&(n=!1),__awaiter(this,void 0,void 0,(function(){var l,d,p,h;return __generator(this,(function(f){switch(f.label){case 0:return this.queue.isEmpty||-1===(l=this.queue).previousPlayableItemIndex?[2]:(d=this.isPlaying,p=this._mediaItemPlayback.currentPlaybackTime,[4,this._changeToMediaAtIndex(l.previousPlayableItemIndex,n)]);case 1:return h=f.sent(),this._notifySkip(d,h,{userInitiated:n,direction:t.PlayActivityEndReasonType.TRACK_SKIPPED_BACKWARDS,position:p}),[2,h]}}))}))},SerialPlaybackController.prototype._prepareQueue=function(t){n.prototype._prepareQueue.call(this,t),this._shuffler.checkAndReshuffle()},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Number]),__metadata("design:returntype",Boolean)],SerialPlaybackController.prototype,"hasCapabilities",null),SerialPlaybackController}(qa);function playMediaItem(n,l,d,p){return __awaiter(this,void 0,void 0,(function(){var h,f,y,v,g;return __generator(this,(function(_){switch(_.label){case 0:return h=l.isPaused()&&!d,Pt.debug("playMediaItem",n,h),[4,shouldPlayPreview(n,l)];case 1:return f=_.sent(),Pt.debug("mk: shouldPreview",f),f?(l.canSupportDRM||l.dispatch(nr.drmUnsupported,{item:n}),n.playbackType=t.PlaybackType.preview,l.nowPlayingItem=n,[4,l.playItemFromUnencryptedSource(n.previewURL,h)]):[3,3];case 2:return _.sent(),[2,n];case 3:return function(t){return!(!t.playRawAssetURL||!t.attributes.assetUrl)}(n)?(Pt.debug("shouldPlayRawAsset",n),n.playbackType=t.PlaybackType.unencryptedFull,l.nowPlayingItem=n,[4,l.playItemFromUnencryptedSource(n.attributes.assetUrl,h)]):[3,5];case 4:return _.sent(),[2,n];case 5:if(!isBroadcastRadio(n))return[3,8];if(!ur.features["broadcast-radio"])throw(y=new ke(ke.CONTENT_UNAVAILABLE)).data=n,y;return[4,loadLiveRadioAssets(n,p.store.developerToken,p.store.userToken)];case 6:return v=_.sent(),n.playbackType=t.PlaybackType.unencryptedFull,l.nowPlayingItem=n,[4,l.playItemFromUnencryptedSource(v.url,h)];case 7:return _.sent(),[2,n];case 8:if(!n||!n.isPlayable)return[2,Promise.reject(new ke(ke.MEDIA_PLAYBACK,"Not Playable"))];_.label=9;case 9:return _.trys.push([9,11,,12]),[4,prepareForEncryptedPlayback(n,l,p)];case 10:return _.sent(),[3,12];case 11:return g=_.sent(),Pt.error("prepareForEncryptedPlayback Error: userInitiated "+d),d?[2,Promise.reject(g)]:(l.dispatch(nr.mediaPlaybackError,g),[2]);case 12:return[4,handleAgeGate(n)];case 13:return _.sent(),Pt.debug("About to play item as encrypted",n),[4,l.playItemFromEncryptedSource(n,d)];case 14:return _.sent(),[2,n]}}))}))}function shouldPlayPreview(t,n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return t.previewURL?n.previewOnly?[2,!0]:t.playRawAssetURL?[2,!1]:(l=!t.isUTS)?[4,hasMusicSubscription()]:[3,2]:[2,!1];case 1:l=!d.sent(),d.label=2;case 2:return l?[2,!0]:[2,!hasAuthorization()||!n.canSupportDRM||!t.isPlayable]}}))}))}function prepareForEncryptedPlayback(t,n,l){return __awaiter(this,void 0,void 0,(function(){var d,p;return __generator(this,(function(h){switch(h.label){case 0:if(Pt.debug("prepareForEncryptedPlayback"),!hasAuthorization())return n.destroy(),[2,Promise.reject(new ke(ke.AUTHORIZATION_ERROR,"Unable to prepare for playback."))];h.label=1;case 1:return h.trys.push([1,3,,4]),[4,l.store.validateAgeVerification(t)];case 2:return h.sent(),[3,4];case 3:return(d=h.sent()).errorCode===ke.CONTENT_RESTRICTED&&t.restrict(),n.destroy(),[2,Promise.reject(d)];case 4:return h.trys.push([4,6,,14]),[4,t.prepareToPlay(l)];case 5:return h.sent(),[3,14];case 6:return p=h.sent(),[ke.AUTHORIZATION_ERROR].includes(p.errorCode)?[4,l.store.storekit.revokeUserToken()]:[3,8];case 7:return h.sent(),[3,13];case 8:if(p.errorCode!==ke.TOKEN_EXPIRED)return[3,13];h.label=9;case 9:return h.trys.push([9,12,,13]),[4,l.store.storekit.renewUserToken()];case 10:return h.sent(),[4,t.prepareToPlay(l)];case 11:return h.sent(),t.playbackData=_playbackDataForItem(t,n),[2,t];case 12:return h.sent(),[3,13];case 13:return p?(n.destroy(),[2,Promise.reject(p)]):[3,14];case 14:return t.playbackData=_playbackDataForItem(t,n),[2,t]}}))}))}function _playbackDataForItem(n,l){if(Pt.debug("mk: _playbackDataForItem",n),n.isCloudUpload)return n.assets[0];if("musicVideo"!==n.type){if(!n.isLiveRadioStation)return __read(n.assets.filter((function(t){var n;if(!("flavor"in t))return!1;var d=new RegExp("\\d{1,2}\\:(c"+(l.extension.isFairplay?"bc":"tr")+"p)(\\d{2,3})","i"),p=d.test(t.flavor),h=null!==(n=t.flavor.match(d))&&void 0!==n?n:[];return p&&parseInt(h[2],0)<=l.bitrate})),1)[0];var d=n.assets.reduce((function(t,n){var l=n.bandwidth;return t[l]||(t[l]=[]),t[l].push(n),t}),{}),p=Object.keys(d).sort((function(t,n){return parseInt(t,10)-parseInt(n,10)})),h=l.bitrate===t.PlaybackBitrate.STANDARD?p[0]:p[p.length-1];n.assetURL=d[h][0].URL}}function handleAgeGate(t){return new Promise((function(n,l){var d=t.ageGatePolicy;if(!d||!d.age||!d.frequencyInMinutes)return Pt.debug("No ageGatePolicy. Resolving handleAgeGate()"),n();var p=window.localStorage.ageGatePolicyAge,h=window.localStorage.ageGatePolicyExpiration;if(p&&h&&parseInt(h,10)>Date.now()&&parseInt(p,10)>=d.age)return n();vt.clientDialog({okButtonString:"Yes",okButtonAction:function(){return localStorage.setItem("ageGatePolicyAge",d.age.toString()),localStorage.setItem("ageGatePolicyExpiration",(Date.now()+60*d.frequencyInMinutes*1e3).toString()),n()},cancelButtonString:"No",cancelButtonAction:function(){return l(new ke("AGE_GATE","Age Gate Declined"))},explanation:"This content may not be appropriate for ages younger than "+d.age+".",message:"Are you "+d.age+" or older?"}).present()}))}function getPlayerType(t){var n,l;switch(null==t?void 0:t.type){case"movie":case"musicVideo":case"musicMovie":case"trailer":case"tvEpisode":case"uploadedVideo":case"uploaded-videos":case"music-videos":case"music-movies":case"tv-episodes":return"video";case"podcast-episodes":return"audio";default:return null!==(l=null===(n=null==t?void 0:t.attributes)||void 0===n?void 0:n.mediaKind)&&void 0!==l?l:"audio"}}var ss,us=function(){function Factory(t){this._playersByType={},this._playerOptions=t}return Factory.prototype.getPlayerForMediaItem=function(t,n,l){return __awaiter(this,void 0,void 0,(function(){var d,p,h;return __generator(this,(function(f){switch(f.label){case 0:if(Pt.debug("mk: getPlayerForMediaItem",t,n),d=getPlayerType(t),(null==(p=this._playersByType[d])?void 0:p.isDestroyed)&&(Pt.debug("mk: existingPlayer was previously destroyed. Removing from factory."),p=void 0,delete this._playersByType[d]),p&&p===l)return[2,l];if(p)return this._applyPlayerState(p,n),[2,p];switch(d){case"audio":h=new na(this._playerOptions),this._playersByType[d]=h;break;case"video":h=new Vo(this._playerOptions);break;default:throw new Error("Invalid player type requested: "+d)}return[4,h.initialize()];case 1:return f.sent(),this._applyPlayerState(h,n),[2,h]}}))}))},Factory.prototype.destroy=function(){Object.values(this._playersByType).forEach((function(t){return t.destroy()}))},Factory.prototype._applyPlayerState=function(t,n){return n?(Pt.debug("_applyPlayerState",n),Object.keys(n).forEach((function(l){void 0!==t[l]&&(t[l]=n[l])})),t):t},Factory}(),cs=nr.playerTypeDidChange,ls=tn.playbackLicenseError,ds=function(){function MediaItemPlayback(t){this.playerState={playbackRate:1,volume:1},this._previewOnly=!1,this._dispatcher=t.services.dispatcher,this._apiManager=t.services.apiManager,this._playerFactory=new us(t),this._currentPlayer=new aa(t),this._dispatcher.subscribe(ls,this.onPlaybackLicenseError)}return Object.defineProperty(MediaItemPlayback.prototype,"currentPlaybackTime",{get:function(){return this._currentPlayer.currentPlaybackTime},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"currentPlaybackTimeRemaining",{get:function(){return this._currentPlayer.currentPlaybackTimeRemaining},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"audioTracks",{get:function(){return this._currentPlayer.audioTracks},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"currentAudioTrack",{get:function(){return this._currentPlayer.currentAudioTrack},set:function(t){this._currentPlayer.currentAudioTrack=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"currentPlaybackDuration",{get:function(){return this._currentPlayer.currentPlaybackDuration},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"currentBufferedProgress",{get:function(){return this._currentPlayer.currentBufferedProgress},set:function(t){this._currentPlayer.currentBufferedProgress=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"currentPlaybackProgress",{get:function(){return this._currentPlayer.currentPlaybackProgress},set:function(t){this._currentPlayer.currentPlaybackProgress=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"currentTextTrack",{get:function(){return this._currentPlayer.currentTextTrack},set:function(t){this._currentPlayer.currentTextTrack=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"canSupportDRM",{get:function(){return this._currentPlayer.canSupportDRM},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"previewOnly",{get:function(){return this._previewOnly},set:function(t){this._previewOnly=t,this._currentPlayer&&(this._currentPlayer.previewOnly=t)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"formattedCurrentPlaybackDuration",{get:function(){return this._currentPlayer.formattedCurrentPlaybackDuration},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"isPlaying",{get:function(){return this._currentPlayer.isPlaying},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"isPrimaryPlayer",{get:function(){return this._currentPlayer.isPrimaryPlayer},set:function(t){this._currentPlayer.isPrimaryPlayer=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"isReady",{get:function(){return this._currentPlayer.isReady},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"nowPlayingItem",{get:function(){return this._currentPlayer.nowPlayingItem},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"playbackRate",{get:function(){return this._currentPlayer.playbackRate},set:function(t){this._updatePlayerState("playbackRate",t)},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"playbackState",{get:function(){return this._currentPlayer.playbackState},set:function(t){this._currentPlayer.playbackState=t},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"playbackTargetAvailable",{get:function(){return this._currentPlayer.playbackTargetAvailable},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"playbackTargetIsWireless",{get:function(){return this._currentPlayer.playbackTargetIsWireless},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"textTracks",{get:function(){return this._currentPlayer.textTracks},enumerable:!0,configurable:!0}),Object.defineProperty(MediaItemPlayback.prototype,"volume",{get:function(){return this._currentPlayer.volume},set:function(t){this._updatePlayerState("volume",t)},enumerable:!0,configurable:!0}),MediaItemPlayback.prototype.destroy=function(){var t;this._playerFactory.destroy(),null===(t=this._dispatcher)||void 0===t||t.unsubscribe(ls,this.onPlaybackLicenseError)},MediaItemPlayback.prototype.exitFullscreen=function(){return this._currentPlayer.exitFullscreen()},MediaItemPlayback.prototype.getNewSeeker=function(){return this._currentPlayer.newSeeker()},MediaItemPlayback.prototype.mute=function(){this._volumeAtMute=this.volume,this.volume=0},MediaItemPlayback.prototype.pause=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,this._currentPlayer.pause(t)]}))}))},MediaItemPlayback.prototype.play=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._currentPlayer.play()]}))}))},MediaItemPlayback.prototype.preload=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._currentPlayer.preload()]}))}))},MediaItemPlayback.prototype.prepareToPlay=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,prepareForEncryptedPlayback(t,this._currentPlayer,this._apiManager)]}))}))},MediaItemPlayback.prototype.requestFullscreen=function(t){return this._currentPlayer.requestFullscreen(t)},MediaItemPlayback.prototype.showPlaybackTargetPicker=function(){this._currentPlayer.showPlaybackTargetPicker()},MediaItemPlayback.prototype.seekToTime=function(t,n){return void 0===n&&(n=zi.Manual),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){switch(l.label){case 0:return[4,this._currentPlayer.seekToTime(t,n)];case 1:return l.sent(),[2]}}))}))},MediaItemPlayback.prototype.setPresentationMode=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,this._currentPlayer.setPresentationMode(t)]}))}))},MediaItemPlayback.prototype.startMediaItemPlayback=function(t,n){var l,d,p;return void 0===n&&(n=!1),__awaiter(this,void 0,void 0,(function(){var h,f,y,v,g=this;return __generator(this,(function(_){switch(_.label){case 0:return Pt.debug("MediaItemPlayback: startMediaItemPlayback",t),(null===(d=null===(l=t.container)||void 0===l?void 0:l.attributes)||void 0===d?void 0:d.requiresSubscription)?[4,hasMusicSubscription()]:[3,2];case 1:if(!(_.sent()||!1))throw(h=new ke(ke.SUBSCRIPTION_ERROR)).data=t,h;_.label=2;case 2:return[4,this._getPlayerForMediaItem(t)];case 3:return f=_.sent(),[4,this.setCurrentPlayer(f)];case 4:if(_.sent(),!(null===(p=this._currentPlayer)||void 0===p?void 0:p.hasMediaElement))return Pt.warn("MediaItemPlayback: Could not play media of type "+t.type+", marking item as unsupported and skipping."),t.notSupported(),[2];_.label=5;case 5:return _.trys.push([5,7,,8]),t.beginMonitoringStateDidChange((function(t){var n;return null===(n=g._dispatcher)||void 0===n?void 0:n.publish(nr.mediaItemStateDidChange,t)})),t.beginMonitoringStateWillChange((function(t){var n;return null===(n=g._dispatcher)||void 0===n?void 0:n.publish(nr.mediaItemStateWillChange,t)})),[4,playMediaItem(t,this._currentPlayer,n,this._apiManager)];case 6:return y=_.sent(),this._currentPlayback={item:t,userInitiated:n},[2,y];case 7:throw v=_.sent(),Pt.error(v),v;case 8:return[2]}}))}))},MediaItemPlayback.prototype.stop=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return[4,this._currentPlayer.stop(t)];case 1:return n.sent(),[2]}}))}))},MediaItemPlayback.prototype.unmute=function(){this.volume>0||(this.volume=this._volumeAtMute||1,this._volumeAtMute=void 0)},MediaItemPlayback.prototype._getPlayerForMediaItem=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return Pt.debug("MediaItemPlayback:  _getPlayerForMediaItem",t.id),[4,this._playerFactory.getPlayerForMediaItem(t,this.playerState,this._currentPlayer)];case 1:return(n=l.sent()).previewOnly=this._previewOnly,[2,n]}}))}))},MediaItemPlayback.prototype.setCurrentPlayer=function(t){var n;return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){switch(l.label){case 0:return this._currentPlayer===t?[2]:(Pt.debug("MediaItemPlayback: setting currentPlayer",t),[4,this._currentPlayer.stop()]);case 1:return l.sent(),this._currentPlayer=t,null===(n=this._dispatcher)||void 0===n||n.publish(cs,{player:t}),[2]}}))}))},MediaItemPlayback.prototype.onPlaybackLicenseError=function(t,n){return __awaiter(this,void 0,void 0,(function(){var t,l,d;return __generator(this,(function(p){switch(p.label){case 0:return n.errorCode!==ke.PLAYREADY_CBC_ENCRYPTION_ERROR?[3,3]:(Pt.warn("MediaItemPlayback: PLAYREADY_CBC_ENCRYPTION_ERROR...retrying with different key system"),[4,this.stop()]);case 1:return p.sent(),(t=this._currentPlayback)?(l=t.item,d=t.userInitiated,l.resetState(),[4,this.startMediaItemPlayback(l,d)]):[3,3];case 2:p.sent(),p.label=3;case 3:return[2]}}))}))},MediaItemPlayback.prototype._updatePlayerState=function(t,n){this.playerState[t]=n,this._currentPlayer[t]=n},__decorate([Bind(),__metadata("design:type",Function),__metadata("design:paramtypes",[Object,Object]),__metadata("design:returntype",Promise)],MediaItemPlayback.prototype,"onPlaybackLicenseError",null),MediaItemPlayback}();!function(t){t.UTS="uts-api",t.MEDIA="media-api"}(ss||(ss={}));var ps,hs=function(){function APIServiceManager(t,n){this.store=t,this._dispatcher=n,this._apisByType={}}return Object.defineProperty(APIServiceManager.prototype,"api",{get:function(){return this.getApiByType(this._defaultAPI)},enumerable:!0,configurable:!0}),Object.defineProperty(APIServiceManager.prototype,"apiService",{get:function(){if(void 0!==this._defaultAPI)return this._apisByType[this._defaultAPI];Pt.error("There is no API instance configured")},enumerable:!0,configurable:!0}),Object.defineProperty(APIServiceManager.prototype,"mediaAPI",{get:function(){return this.getApiByType(ss.MEDIA)},enumerable:!0,configurable:!0}),Object.defineProperty(APIServiceManager.prototype,"utsAPI",{get:function(){return this.getApiByType(ss.UTS)},enumerable:!0,configurable:!0}),APIServiceManager.prototype.getApiByType=function(t){var n;if(void 0!==t&&(n=this._apisByType[t]),void 0===n||void 0===n.api)throw new ke(ke.CONFIGURATION_ERROR,"There is no API instance configured for the requested type: "+t);return n.api},Object.defineProperty(APIServiceManager.prototype,"defaultApiType",{set:function(t){this._defaultAPI=t},enumerable:!0,configurable:!0}),APIServiceManager.prototype.registerAPIService=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l,d,p,h,f;return __generator(this,(function(y){switch(y.label){case 0:return n=t.apiType,l=t.configureFn,d=t.options,p=d.apiOptions||{},void 0===this._defaultAPI&&(this._defaultAPI=n),h=this._apisByType,f=n,[4,l.call(this,{apiOptions:p,store:this.store,dispatcher:this._dispatcher})];case 1:return h[f]=y.sent(),[2]}}))}))},APIServiceManager}(),fs=function(){function BitrateCalculator(n,l){var d,p;void 0===l&&(l=t.PlaybackBitrate.STANDARD),this._downlinkSamples=[],this._bitrate=l,this._dispatcher=n,void 0!==(null===(p=null===(d=null===window||void 0===window?void 0:window.navigator)||void 0===d?void 0:d.connection)||void 0===p?void 0:p.downlink)&&this._recalculateBitrate(100*(window.navigator.connection.downlink||0))}return Object.defineProperty(BitrateCalculator.prototype,"bitrate",{get:function(){return this._bitrate},set:function(t){this._bitrate!==t&&(this._bitrate=t,this._dispatcher.publish(nr.playbackBitrateDidChange,{bitrate:t}))},enumerable:!0,configurable:!0}),BitrateCalculator.prototype._calculateAverageDownlink=function(){return 0===this._downlinkSamples.length?0:this._downlinkSamples.reduce((function(t,n){return t+n}),0)/this._downlinkSamples.length||0},BitrateCalculator.prototype._recalculateBitrate=function(n){Pt.debug("_recalculateBitrate",n),this._downlinkSamples.push(n),this._calculateAverageDownlink()>t.PlaybackBitrate.STANDARD?(Pt.debug("setting bitrate to",t.PlaybackBitrate.HIGH),this.bitrate=t.PlaybackBitrate.HIGH):(Pt.debug("setting bitrate to",t.PlaybackBitrate.STANDARD),this.bitrate=t.PlaybackBitrate.STANDARD)},BitrateCalculator}();!function(t){t[t.ACCURATE=0]="ACCURATE",t[t.ROUND=1]="ROUND"}(ps||(ps={}));var ys,vs=function(){function TimingAccuracy(t){void 0===t&&(t=!1),this.mode=t?ps.ACCURATE:ps.ROUND}return TimingAccuracy.prototype.time=function(t){return void 0===t&&(t=0),this.mode===ps.ROUND?Math.round(t):t},TimingAccuracy}(),gs=[ke.AGE_VERIFICATION,ke.CONTENT_EQUIVALENT,ke.CONTENT_RESTRICTED,ke.CONTENT_UNAVAILABLE,ke.CONTENT_UNSUPPORTED,ke.SERVER_ERROR,ke.SUBSCRIPTION_ERROR,ke.UNSUPPORTED_ERROR];(ys=t.PlaybackMode||(t.PlaybackMode={}))[ys.PREVIEW_ONLY=0]="PREVIEW_ONLY",ys[ys.MIXED_CONTENT=1]="MIXED_CONTENT",ys[ys.FULL_PLAYBACK_ONLY=2]="FULL_PLAYBACK_ONLY";var _s=function(){function MKInstance(n,l){if(void 0===l&&(l={}),this.privateEnabled=!1,this.siriInitiated=!1,this.sourceType=Ne.MUSICKIT,this.version="2.2044.10",this._bag=ur,this._playbackControllers={},this._playbackErrorDialog=!0,this._playbackMode=t.PlaybackMode.MIXED_CONTENT,"string"!=typeof n)throw new Error("MusicKit was initialized without an developerToken.");Object.assign(ur.features,function(t){void 0===t&&(t=[]);var n={};return t.forEach((function(t){"-"===t.charAt(0)?(t=t.substr(1),n[t]=!1):n[t]=!0})),n}(l.features)),this.context={};var d=new Ue;this.capabilities=new ua(d);var p=new vs(!!ur.features["player-accurate-timing"]),h=new fs(d,l.bitrate);this._services={dispatcher:d,timing:p,bitrateCalculator:h},void 0!==l.playActivityAPI&&(this._services.playActivity=new Ar(l.playActivityAPI,d)),l.services=this._services,this._configureLogger(l),ur.app=l.app||{},ur.store=new ge({filter:getFilterFromFlags(l.storeFilterTypes||[])}),Object.assign(ur.urls,l.urls||{});var f=function(t,n){return ar=new cr(t,n)}(n,l);this._services.apiManager=new hs(f,d);var y=new ds(this._createPlayerControllerOptions());if(this._services.mediaItemPlayback=y,l.sourceType&&(this.sourceType=l.sourceType),this._initializeEventHandling(),l.bitrate&&(this.bitrate=l.bitrate),l.prefix&&/^(?:web|preview)$/.test(l.prefix)&&(this.prefix=ur.prefix=l.prefix),l.suppressErrorDialog&&(this._playbackErrorDialog=!l.suppressErrorDialog),void 0!==l.playbackMode&&(this.playbackMode=l.playbackMode),this.privateEnabled=l.privateEnabled||!1,this.siriInitiated=l.siriInitiated||!1,this.id=generateUUID(),Pt.log("MusicKit JS Version: "+this.version),Pt.debug("Link Parameters",l.linkParameters),Pt.log("InstanceId",this.id),ur.app&&Pt.debug("App",ur.app),l.userToken){var v=l.userToken;"function"==typeof v?ar.dynamicMusicUserToken=v:this.musicUserToken=v}}return Object.defineProperty(MKInstance.prototype,"developerToken",{get:function(){return ar.developerToken},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"api",{get:function(){return this._services.apiManager.api},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"audioTracks",{get:function(){return this._mediaItemPlayback.audioTracks},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"authorizationStatus",{get:function(){return ar.authorizationStatus},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"bitrate",{get:function(){return this._services.bitrateCalculator.bitrate},set:function(t){this._services.bitrateCalculator.bitrate=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"browserSupportsPictureInPicture",{get:function(){return function(){if(_t)return Pt.warn("dom-helpers: Browser checks are not supported in Node environments"),!1;var t=kt,n=t&&t.webkitSupportsPresentationMode&&"function"==typeof t.webkitSetPresentationMode,l=document.pictureInPictureEnabled;return!(!n&&!l)}()},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"browserSupportsVideoDrm",{get:function(){return!!ln},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"cid",{get:function(){return(2===this.realm||this.sourceType!==Ne.MUSICKIT)&&ar.cid},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"continuous",{get:function(){return this._playbackController.continuous},set:function(t){this._playbackController.continuous=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"currentAudioTrack",{get:function(){return this._mediaItemPlayback.currentAudioTrack},set:function(t){this._mediaItemPlayback.currentAudioTrack=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"currentPlaybackDuration",{get:function(){return this._mediaItemPlayback.currentPlaybackDuration},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"currentPlaybackProgress",{get:function(){return this._mediaItemPlayback.currentPlaybackProgress},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"currentPlaybackTime",{get:function(){return this._mediaItemPlayback.currentPlaybackTime},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"currentPlaybackTimeRemaining",{get:function(){return this._mediaItemPlayback.currentPlaybackTimeRemaining},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"currentTextTrack",{get:function(){return this._mediaItemPlayback.currentTextTrack},set:function(t){this._mediaItemPlayback.currentTextTrack=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"isAuthorized",{get:function(){return ar.isAuthorized},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"isPlaying",{get:function(){return this._playbackController.isPlaying},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"isRestricted",{get:function(){return ar.isRestricted},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"musicUserToken",{get:function(){return ar.musicUserToken},set:function(t){t&&ar.musicUserToken===t||(ar.musicUserToken=t)},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"needsGDPR",{get:function(){return ar.needsGDPR},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"nowPlayingItem",{get:function(){return this._mediaItemPlayback.nowPlayingItem},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"nowPlayingItemIndex",{get:function(){return this._playbackController.nowPlayingItemIndex},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"playbackMode",{get:function(){return this._playbackMode},set:function(n){if(-1!==Object.values(t.PlaybackMode).indexOf(n)){this._playbackMode=n;var l=n===t.PlaybackMode.PREVIEW_ONLY,d=this._services.mediaItemPlayback;d&&(d.previewOnly=l)}},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"playbackRate",{get:function(){return this._mediaItemPlayback.playbackRate},set:function(t){this._mediaItemPlayback.playbackRate=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"playbackState",{get:function(){return this._mediaItemPlayback.playbackState},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"playbackTargetAvailable",{get:function(){return this._mediaItemPlayback.playbackTargetAvailable},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"playbackTargetIsWireless",{get:function(){return this._mediaItemPlayback.playbackTargetIsWireless},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"previewOnly",{get:function(){return this.playbackMode===t.PlaybackMode.PREVIEW_ONLY},set:function(n){this.playbackMode=n?t.PlaybackMode.PREVIEW_ONLY:t.PlaybackMode.MIXED_CONTENT},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"queue",{get:function(){return this._playbackController.queue},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"queueIsEmpty",{get:function(){return this._playbackController.queue.isEmpty},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"realm",{get:function(){return ar.realm},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"repeatMode",{get:function(){return this._playbackController.repeatMode},set:function(t){this._playbackController.repeatMode=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"requestUserToken",{set:function(t){ar.requestUserToken=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"restrictedEnabled",{get:function(){return ar.restrictedEnabled},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"seekSeconds",{get:function(){return this._playbackController.seekSeconds},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"services",{get:function(){return this._services},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"shuffle",{set:function(t){this._playbackController.shuffle=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"shuffleMode",{get:function(){return this._playbackController.shuffleMode},set:function(t){this._playbackController.shuffleMode=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"storefrontCountryCode",{get:function(){return ar.storefrontCountryCode},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"subscribeURL",{get:function(){return ar.subscribeURL},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"subscribeFamilyURL",{get:function(){return ar.subscribeFamilyURL},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"subscribeIndividualURL",{get:function(){return ar.subscribeIndividualURL},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"subscribeStudentURL",{get:function(){return ar.subscribeStudentURL},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"textTracks",{get:function(){return this._mediaItemPlayback.textTracks},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"videoContainerElement",{get:function(){return this.context.videoContainerElement},set:function(t){this.context.videoContainerElement=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"volume",{get:function(){return this._mediaItemPlayback.volume},set:function(t){this._mediaItemPlayback.volume=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"storefrontId",{get:function(){return ar.storefrontId},set:function(t){ar.storefrontId=t},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"_mediaItemPlayback",{get:function(){return this._services.mediaItemPlayback},enumerable:!0,configurable:!0}),Object.defineProperty(MKInstance.prototype,"_playbackController",{get:function(){if(void 0!==this._playbackControllerInternal)return this._playbackControllerInternal;Pt.debug("setting _playbackController");var t=this._getPlaybackControllerByType(Va.serial);return this._playbackController=t,t},set:function(t){this._playbackControllerInternal=t,this._playbackControllerInternal.activate(),this.capabilities.updateChecker(this._playbackControllerInternal.hasCapabilities),this.capabilities.controller=this._playbackControllerInternal},enumerable:!0,configurable:!0}),MKInstance.prototype.addEventListener=function(t,n,l){void 0===l&&(l={}),adaptAddEventListener(this._services.dispatcher,t,n,l)},MKInstance.prototype.authorize=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this.deferPlayback(),[2,ar.authorize()]}))}))},MKInstance.prototype.canAuthorize=function(){return this._mediaItemPlayback.canSupportDRM&&!this.isAuthorized},MKInstance.prototype.canUnauthorize=function(){return this._mediaItemPlayback.canSupportDRM&&this.isAuthorized},MKInstance.prototype.changeToMediaAtIndex=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:return n.sent(),this._signalChangeItemIntent(),[4,this._playbackController.changeToMediaAtIndex(t)];case 2:return n.sent(),[2]}}))}))},MKInstance.prototype.changeToMediaItem=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return Pt.debug("instance.changeToMediaItem",t),this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:return n.sent(),this._signalChangeItemIntent(),[4,this._playbackController.changeToMediaItem(t)];case 2:return n.sent(),[2]}}))}))},MKInstance.prototype.changeUserStorefront=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return this.storefrontId=t,[2]}))}))},MKInstance.prototype.cleanup=function(){var n;return __awaiter(this,void 0,void 0,(function(){var l,d,p=this;return __generator(this,(function(h){switch(h.label){case 0:null===(n=this._services.mediaItemPlayback)||void 0===n||n.destroy(),this._signalIntent({endReasonType:t.PlayActivityEndReasonType.EXITED_APPLICATION}),l=Object.keys(this._playbackControllers).map((function(t){return p._playbackControllers[t].destroy()})),h.label=1;case 1:return h.trys.push([1,3,,4]),[4,Promise.all(l)];case 2:return h.sent(),[3,4];case 3:return d=h.sent(),Pt.error("Error cleaning up controller",d),[3,4];case 4:return this._services.dispatcher.clear(),[2]}}))}))},MKInstance.prototype.configure=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return[4,ar.storekit.whenAuthCompleted];case 1:return l.sent(),n=t.map(this._services.apiManager.registerAPIService,this._services.apiManager),[4,Promise.all(n)];case 2:return l.sent(),[4,this._configurePlayActivity()];case 3:return l.sent(),[2]}}))}))},MKInstance.prototype.deferPlayback=function(){Pt.debug("deferPlayback",this._playbackControllerInternal),deferPlayback()},MKInstance.prototype.getApiByType=function(t){var n;return null===(n=this._services.apiManager)||void 0===n?void 0:n.getApiByType(t)},MKInstance.prototype.me=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,ar.storekit.me()];case 1:return[2,t.sent()];case 2:return t.sent(),[2,Promise.reject(new ke(ke.AUTHORIZATION_ERROR,"Unauthorized"))];case 3:return[2]}}))}))},MKInstance.prototype.musicSubcriptionOffers=function(){return ar.storekit.musicSubscriptionOffers(this.storefrontId)},MKInstance.prototype.hasMusicSubscription=function(){return hasMusicSubscription(ar.storekit)},MKInstance.prototype.mute=function(){return this._mediaItemPlayback.mute()},MKInstance.prototype.pause=function(n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:if(!this._isPlaybackSupported())return[2];d.label=1;case 1:return d.trys.push([1,3,,4]),this._signalIntent({endReasonType:t.PlayActivityEndReasonType.PLAYBACK_MANUALLY_PAUSED}),[4,this._playbackController.pause(n)];case 2:return d.sent(),[3,4];case 3:return l=d.sent(),this._handlePlaybackError(l),[3,4];case 4:return[2,Promise.resolve()]}}))}))},MKInstance.prototype.play=function(){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(n){switch(n.label){case 0:return Pt.debug("instance.play()"),this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:n.sent(),n.label=2;case 2:return n.trys.push([2,4,,5]),[4,this._playbackController.play()];case 3:return n.sent(),[3,5];case 4:return t=n.sent(),this._handlePlaybackError(t),[3,5];case 5:return[2,Promise.resolve()]}}))}))},MKInstance.prototype.playMediaItem=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return Pt.debug("mk: playMediaItem",t),this.deferPlayback(),[2,this._playbackController.playSingleMediaItem(t)]}))}))},MKInstance.prototype.playNext=function(t,n){return void 0===n&&(n=!1),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){return this._isPlaybackSupported()?this._playbackController.queue?(this.deferPlayback(),[2,this._playbackController.prepend(t,n)]):[2,this.setQueue(t)]:[2]}))}))},MKInstance.prototype.playLater=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return this._isPlaybackSupported()?this._playbackController.queue?(this.deferPlayback(),[2,this._playbackController.append(t)]):[2,this.setQueue(t)]:[2]}))}))},MKInstance.prototype.clearQueue=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,this._playbackController.clear()]}))}))},MKInstance.prototype.removeEventListener=function(t,n){!function(t,n,l){for(var d,p=getCallbacksForName(n),h=p.length-1;h>=0;h--){var f=__read(p[h],2),y=f[0],v=f[1];if(y===l){d=v,p.splice(h,1);break}}d&&t.unsubscribe(n,d)}(this._services.dispatcher,t,n)},MKInstance.prototype.shouldDisplayPrivacyLink=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,ar.shouldDisplayPrivacyLink(t)]}))}))},MKInstance.prototype.exitFullscreen=function(){return this._mediaItemPlayback.exitFullscreen()},MKInstance.prototype.requestFullscreen=function(t){return this._mediaItemPlayback.requestFullscreen(t)},MKInstance.prototype.getNewSeeker=function(){return this._playbackController.getNewSeeker()},MKInstance.prototype.seekToTime=function(t,n){return void 0===n&&(n=zi.Manual),__awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:d.sent(),d.label=2;case 2:return d.trys.push([2,4,,5]),[4,this._playbackController.seekToTime(t,n)];case 3:return d.sent(),[3,5];case 4:return l=d.sent(),this._handlePlaybackError(l),[3,5];case 5:return[2,Promise.resolve()]}}))}))},MKInstance.prototype.setQueue=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return Pt.debug("instance.setQueue()",t),this._isPlaybackSupported()?this._isStationQueueOptions(t)?(Pt.warn("setQueue options contained a station queue request. Changing to setStationQueue mode."),[2,this.setStationQueue(t)]):(this._signalChangeItemIntent(),this.deferPlayback(),[4,this._updatePlaybackController(this._getPlaybackControllerByType(Va.serial))]):(Pt.warn("Playback is not supported"),[2]);case 1:return l.sent(),[4,this._playbackController.setQueue(t)];case 2:return n=l.sent(),void 0!==t.repeatMode&&(this._playbackController.repeatMode=t.repeatMode),t.autoplay?[4,this.play()]:[3,4];case 3:l.sent(),l.label=4;case 4:return[2,n]}}))}))},MKInstance.prototype.setStationQueue=function(t){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return this._isPlaybackSupported()?[4,this._validateAuthorization(!0)]:[2];case 1:return l.sent(),this._signalChangeItemIntent(),this.deferPlayback(),parseQueueURLOption(t),[4,this._updatePlaybackController(this._getPlaybackControllerByType(Va.continuous))];case 2:return l.sent(),n=this._playbackController.setQueue(t),t.autoplay?[4,this.play()]:[3,4];case 3:l.sent(),l.label=4;case 4:return[2,n]}}))}))},MKInstance.prototype.setPresentationMode=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return[2,this._mediaItemPlayback.setPresentationMode(t)]}))}))},MKInstance.prototype.skipToNextItem=function(){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:l.sent(),this._signalIntent({endReasonType:t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS,direction:t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS}),l.label=2;case 2:return l.trys.push([2,4,,5]),[4,this._playbackController.skipToNextItem()];case 3:return l.sent(),[3,5];case 4:return n=l.sent(),this._handlePlaybackError(n),[3,5];case 5:return[2]}}))}))},MKInstance.prototype.skipToPreviousItem=function(){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:l.sent(),this._signalIntent({endReasonType:t.PlayActivityEndReasonType.TRACK_SKIPPED_BACKWARDS,direction:t.PlayActivityEndReasonType.TRACK_SKIPPED_BACKWARDS}),l.label=2;case 2:return l.trys.push([2,4,,5]),[4,this._playbackController.skipToPreviousItem()];case 3:return l.sent(),[3,5];case 4:return n=l.sent(),this._handlePlaybackError(n),[3,5];case 5:return[2]}}))}))},MKInstance.prototype.seekForward=function(){return __awaiter(this,void 0,void 0,(function(){var n;return __generator(this,(function(l){switch(l.label){case 0:return this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:l.sent(),l.label=2;case 2:return l.trys.push([2,4,,5]),this._signalIntent({endReasonType:t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS,direction:t.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS}),[4,this._playbackController.seekForward()];case 3:return l.sent(),[3,5];case 4:return n=l.sent(),this._handlePlaybackError(n),[3,5];case 5:return[2]}}))}))},MKInstance.prototype.seekBackward=function(){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(n){switch(n.label){case 0:return this._isPlaybackSupported()?[4,this._validateAuthorization()]:[2];case 1:n.sent(),n.label=2;case 2:return n.trys.push([2,4,,5]),[4,this._playbackController.seekBackward()];case 3:return n.sent(),[3,5];case 4:return t=n.sent(),this._handlePlaybackError(t),[3,5];case 5:return[2]}}))}))},MKInstance.prototype.showPlaybackTargetPicker=function(){this._playbackController.showPlaybackTargetPicker()},MKInstance.prototype.stop=function(t){var n;return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:if(!this._isPlaybackSupported())return[2];this._signalIntent({endReasonType:null==t?void 0:t.endReasonType,userInitiated:null===(n=null==t?void 0:t.userInitiated)||void 0===n||n}),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,this._playbackController.stop(t)];case 2:return d.sent(),[3,4];case 3:return l=d.sent(),this._handlePlaybackError(l),[3,4];case 4:return[2]}}))}))},MKInstance.prototype.resetSubscribeViewEligibility=function(){ar.storekit.resetSubscribeViewEligibility()},MKInstance.prototype.unauthorize=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return[2,ar.unauthorize()]}))}))},MKInstance.prototype.unmute=function(){return this._mediaItemPlayback.unmute()},MKInstance.prototype._createPlayerControllerOptions=function(){return{services:this._services,context:this.context,privateEnabled:this.privateEnabled,siriInitiated:this.siriInitiated,storekit:null==ar?void 0:ar.storekit}},MKInstance.prototype._getPlaybackControllerByType=function(t){var n,l=this._playbackControllers[t];if(l)return l;switch(t){case Va.serial:n=new as(this._createPlayerControllerOptions());break;case Va.continuous:n=new Za(this._createPlayerControllerOptions());break;default:throw new ke(ke.UNSUPPORTED_ERROR,"Unsupported controller requested: "+t)}return this._playbackControllers[t]=n,n},MKInstance.prototype._handlePlaybackError=function(t){if(Pt.error("mediaPlaybackError",t),gs.includes(t.name))throw t;this._playbackErrorDialog&&!_t&&vt.presentError(t)},MKInstance.prototype._initializeEventHandling=function(){var n=this;[nr.authorizationStatusDidChange,nr.needsGDPRDidChange,nr.storefrontCountryCodeDidChange,nr.storefrontIdentifierDidChange,nr.userTokenDidChange,nr.eligibleForSubscribeView].forEach((function(t){ar.storekit.addEventListener(t,(function(l){return n._services.dispatcher.publish(t,l)}))})),ar.storekit.addEventListener(nr.userTokenDidChange,(function(){n._configurePlayActivity().catch()})),this._services.dispatcher.subscribe(nr.mediaPlaybackError,(function(t,l){return n._handlePlaybackError(l)})),this._services.dispatcher.subscribe(nr.playbackStateDidChange,(function(l,d){d.state===t.PlaybackStates.paused&&(Pt.debug("mk: playbackStateDidChange callback - calling storekit.presentSubscribeViewForEligibleUsers"),ar.storekit.presentSubscribeViewForEligibleUsers({state:d.state,item:n.nowPlayingItem},!1))}))},MKInstance.prototype._configureLogger=function(t){t.debug&&(Pt.enabled=!0,Pt.level=parseInt(t.logLevel,10)||1)},MKInstance.prototype._configurePlayActivity=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return void 0===this._services.playActivity?[2]:[4,this._services.playActivity.configure(this,{services:this._services})];case 1:return t.sent(),[2]}}))}))},MKInstance.prototype._isPlaybackSupported=function(){return!_t||(Pt.warn("Media playback is not supported in Node environments."),!1)},MKInstance.prototype._isStationQueueOptions=function(t){return parseQueueURLOption(t),!(!function(t){return!!t&&(!!isLiveQueue(t)||(!!isQueueURLOption(t)||Object.keys(Wa).some((function(n){return void 0!==t[n]}))))}(t)||function(t){return!!t&&(!!isQueueURLOption(t)||(!!isQueueItems(t)||Object.keys(es).concat(Object.keys(ts)).some((function(n){return void 0!==t[n]}))))}(t))},MKInstance.prototype._updatePlaybackController=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return Pt.debug("mk: _updatePlaybackController",t),this._playbackControllerInternal===t?[2]:this._playbackControllerInternal?[4,this._playbackControllerInternal.deactivate()]:[3,2];case 1:n.sent(),n.label=2;case 2:return this._playbackController=t,[2]}}))}))},MKInstance.prototype._signalChangeItemIntent=function(){this._signalIntent({endReasonType:t.PlayActivityEndReasonType.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM})},MKInstance.prototype._signalIntent=function(t){this.services.dispatcher.publish(er.userActivityIntent,__assign({userInitiated:!0},t))},MKInstance.prototype._validateAuthorization=function(n){return void 0===n&&(n=!1),__awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){switch(l.label){case 0:return n||this.playbackMode===t.PlaybackMode.FULL_PLAYBACK_ONLY?void 0!==this._playbackControllerInternal&&this._playbackControllerInternal.isReady?[3,2]:[4,this.authorize()]:[2];case 1:l.sent(),l.label=2;case 2:return[2]}}))}))},MKInstance}(),ms="undefined"!=typeof window&&"undefined"!=typeof document,bs=!1,Ps=[];function cleanupInstances(){return __awaiter(this,void 0,void 0,(function(){var t;return __generator(this,(function(n){switch(n.label){case 0:return t=Ps.map((function(t){return t.cleanup()})),[4,Promise.all(t)];case 1:return n.sent(),Ps=[],[2]}}))}))}function dispatchDocumentEvent(t){if(!_t){var n=document.createEvent("Event");n.initEvent(t,!0,!0),setTimeout((function(){return document.dispatchEvent(n)}))}}function configure$1(t,n){return void 0===n&&(n=_s),__awaiter(this,void 0,void 0,(function(){var l,d,p,h;return __generator(this,(function(f){switch(f.label){case 0:if(!t)throw new ke(ke.INVALID_ARGUMENTS,"configuration required");if(l={},d=t.developerToken,p=t.mergeQueryParams,!d)throw new ke(ke.CONFIGURATION_ERROR,"Missing developer token");return p&&ms&&window.location&&(l.linkParameters=__assign(__assign({},t.linkParameters||{}),parseQueryParams(window.location.href))),[4,findKeySystemPreference()];case 1:return f.sent(),h=new n(d,__assign(__assign({},t),l)),bs?[3,3]:[4,cleanupInstances()];case 2:f.sent(),f.label=3;case 3:return Ps.push(h),dispatchDocumentEvent(nr.configured),[2,h]}}))}))}if(ms){dispatchDocumentEvent(nr.loaded);var ks=function(){function meta(t){if(!_t){var n=document.head.querySelector("meta[name="+t+"]");return(null==n?void 0:n.content)||void 0}}var t,n=meta("apple-music-developer-token")||meta("JWT"),l=meta("apple-music-app-build")||meta("version"),d=meta("apple-music-app-name"),p=meta("apple-music-app-version");return(n||l||d||p)&&(t={},n&&(t.developerToken=n),(l||d||p)&&(t.app={},l&&(t.app.build=l),d&&(t.app.name=d),p&&(t.app.version=p))),t}(),Ts=/interactive|complete|loaded/.test(document.readyState);ks&&ks.developerToken&&!Ts&&0===Ps.length&&(ks.declarativeMarkup=!0,document.addEventListener("DOMContentLoaded",(function(){return configure$1(ks)})))}var Ss={HIDE:"none",SHOW:""},As=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return setTimeout(t,16)},ws=function(){function DOMSupport(t,n){var l=this;if(void 0===n&&(n=Ss),this.elements=t,this.classes=n,_t||"function"!=typeof MutationObserver||!t)return this.elements=void 0,void(this.identifiers=[]);this.identifiers=Object.keys(t),this.identifiers.forEach((function(n){for(var d=l._nodesForDefinitionId(n),p=0;p<d.length;++p){var h=d[p];l.attach(h,t[n])}})),new MutationObserver(this._mutationDidOccur.bind(this)).observe(document.body,{attributes:!0,childList:!0,subtree:!0})}return DOMSupport.prototype.attach=function(t,n){void 0===n&&(n=this.elements[t.id]),!t.innerText&&n.defaultText&&(t.innerText=n.defaultText),n.click&&t.addEventListener("mouseup",n.click),this._renderDefinition(t,n)},DOMSupport.prototype.detach=function(t,n){void 0===n&&(n=this.elements[t.id]),n&&n.click&&t.removeEventListener("mouseup",n.click)},DOMSupport.prototype.update=function(t){var n=this;void 0===t&&(t=this.identifiers),this.elements&&As((function(){t.forEach((function(t){for(var l=n.elements[t],d=n._nodesForDefinitionId(t),p=0;p<d.length;++p){var h=d[p];l&&h&&n._renderDefinition(h,l)}}))}))},DOMSupport.prototype._mutationDidOccur=function(t){var n=this;t.forEach((function(t){if("attributes"===t.type){var l=n.elements[t.attributeName];l&&n.attach(t.target,l)}for(var _loop_1=function(l){var d=t.addedNodes[l];if(!d.id&&!d.dataset)return"continue";d.id&&n.elements[d.id]&&n.attach(d,n.elements[d.id]),n.identifiers.forEach((function(t){d.getAttribute(t)&&n.attach(d,n.elements[t])}))},d=0;d<t.addedNodes.length;++d)_loop_1(d);for(var _loop_2=function(l){var d=t.removedNodes[l];if(!d.id&&!d.dataset)return"continue";d.id&&n.elements[d.id]&&n.detach(d,n.elements[d.id]),n.identifiers.forEach((function(t){d.getAttribute(t)&&n.detach(d,n.elements[t])}))},p=0;p<t.removedNodes.length;++p)_loop_2(p)}))},DOMSupport.prototype._nodesForDefinitionId=function(t){var n=/^data-/.test(t)?"["+t+"]":"#"+t;return document.querySelectorAll(n)},DOMSupport.prototype._renderDefinition=function(t,n){var l=this,d="function"==typeof n.enabled?n.enabled(t):n.enabled||!0,p="function"==typeof n.display?n.display(t):n.display||!0;As((function(){d?t.removeAttribute("disabled"):t.setAttribute("disabled",!0),t.style.display=p?l.classes.SHOW:l.classes.HIDE,p&&0===t.children.length&&n.content&&(t.innerText=n.content(t))}))},DOMSupport}(),Is="apple-music-now-playing";function isPlayingContainerOrItem(t,n){if(!t||!n)return!1;if(lr.test(t)){var l=formattedMediaURL(t).contentId;l&&(t=l)}return t===n.id||n.container&&n.container.id===t}var Es;!function(t){t.JSON="application/json",t.FORM="application/x-www-form-urlencoded"}(Es||(Es={}));var Rs=function(t){function TokenSession(n,l,d){var p=t.call(this,n,d)||this;return p._developerToken=new wt(l),p.headers.set("Authorization","Bearer "+p.developerToken),d=d||{},p.userToken=d.userToken,p.userToken&&p.headers.set("Media-User-Token",p.userToken),p}return __extends$1(TokenSession,t),Object.defineProperty(TokenSession.prototype,"developerToken",{get:function(){return this._developerToken.token},enumerable:!0,configurable:!0}),TokenSession}(function(){function URLSession(t,n){if(this.prefix="",this.method="GET",this.url=t,(n=n||{}).storage&&n.underlyingStorage)throw new Error("only pass storage OR underlyingStorage in sessionOptions to URLSession");var l=n.underlyingStorage||{};this.storage=n.storage||new Ze(l),this.ttl=n.ttl||3e5,this._fetch=n.fetch||fetch.bind(window),this._fetchOptions=ne({},n.fetchOptions),this.headers=this._fetchOptions.headers||new Headers,delete this._fetchOptions.headers}return URLSession.prototype.clearCacheForRequest=function(t,n){"object"==typeof t&&(n=t,t=void 0);var l=this.constructURL(t,n);this.clearCacheItems([l])},URLSession.prototype.request=function(t,n,l){return __awaiter$1(this,void 0,void 0,(function(){var d,p,h,f,y,v,g,_,m,b;return __generator$1(this,(function(P){switch(P.label){case 0:return l||"object"!=typeof t||(l=n||{},n=t,t=void 0),l=ne(ne({method:this.method,headers:this.headers,reload:!1},this._fetchOptions),l),d={},"object"==typeof l.queryParameters?(d=l.queryParameters,delete l.queryParameters):"GET"===l.method&&(d=n),p=this.constructURL(t,d),h=l.method,f=l.reload,y=void 0!==f&&f,v=l.useRawResponse,l.headers=this.buildHeaders(l),delete l.reload,delete l.useRawResponse,"GET"===h&&!y&&(g=this.getCacheItem(p))?[2,Promise.resolve(g)]:(n&&Object.keys(n).length&&("POST"===h||"PUT"===h)&&(l.body=l.body||n,l.contentType===Es.FORM?(l.body=urlEncodeParameters(l.body),l.headers.set("Content-Type",Es.FORM)):(l.body=JSON.stringify(l.body),l.headers.set("Content-Type",Es.JSON))),[4,this._fetch(p,l)]);case 1:if(!(_=P.sent()).ok)return[2,Promise.reject(_)];P.label=2;case 2:return P.trys.push([2,4,,5]),[4,_.json()];case 3:return m=P.sent(),[3,5];case 4:return P.sent(),m={},[3,5];case 5:return m.errors?[2,Promise.reject(m.errors)]:(b=v?m:m.results||m.data||m,"GET"===h&&this.setCacheItem(p,b),[2,b])}}))}))},URLSession.prototype.buildHeaders=function(t){var n=void 0===t?{}:t,l=n.headers,d=n.reload,p=void 0!==d&&d;void 0===l&&(l=this.headers);var h=function(t){return new t.constructor(t)}(l);return p&&h.set("Cache-Control","no-cache"),h},URLSession.prototype.constructURL=function(t,n){var l=t?this.url+"/"+t:this.url,d=urlEncodeParameters(n);return d&&(l=l+(-1===l.indexOf("?")?"?":"&")+d),l},URLSession.prototype.clearCacheItems=function(t,n){var l=this;void 0===n&&(n=!0),t?t.forEach((function(t){return l._removeCacheItemsMatching(l._key(t),n)})):this._removeCacheItemsMatching(this.prefix,!1)},URLSession.prototype.getCacheItem=function(t){var n=""+this.prefix+this.prefix+"cache-mut",l=this.storage.getItem(n)||null,d=this.headers.get("Music-User-Token")||this.headers.get("Media-User-Token")||null;d!==l&&(this.clearCacheItems(),null===d?this.storage.removeItem(n):this.storage.setItem(n,d));var p=this._key(t),h=this.storage.getItem(p);if(h){var f=JSON.parse(h),y=f.x,v=f.d;if(y>Date.now())return v;this.storage.removeItem(p)}},URLSession.prototype.setCacheItem=function(t,n,l){void 0===l&&(l=this.ttl);var d=this._key(t);this.storage.removeItem(d),this.storage.setItem(d,JSON.stringify({x:Date.now()+l,d:n}))},URLSession.prototype._removeCacheItemsMatching=function(t,n){var l=this,d=new RegExp("^"+t+(n?"$":"")),p=this.storage.constructor===Ze?this.storage._data:this.storage;Object.keys(p).forEach((function(t){d.test(t)&&l.storage.removeItem(t)}))},URLSession.prototype._key=function(t){var n=function(t){try{var n=__read$1(t.split("?",2),2),l=n[0],d=n[1];if(void 0===d)return l;var p=d.split("&").map((function(t){return t.split("=",2)})),h=__spread$1(Array(p.length).keys());return h.sort((function(t,n){var l=p[t],d=p[n];return l<d?-1:l>d?1:t-n})),l+"?"+h.map((function(t){return p[t]})).map((function(t){var n=__read$1(t,2),l=n[0],d=n[1];return void 0!==d?l+"="+d:l})).join("&")}catch(e){return t}}(t).toLowerCase().replace(this.url,"");return""+this.prefix+n.replace(/[^-_0-9a-z]{1,}/g,".")},URLSession}()),ChunkedIdApi=function(t,n){return void 0===n&&(n=1e3),function(l,d,p){if(void 0===p||"function"!=typeof p.value)throw new TypeError("Only methods can be decorated with @ChunkedIdApi, but "+d+" is not a method.");return{configurable:!0,get:function(){var l=p.value;function chunkedIdApi(){for(var d=[],p=0;p<arguments.length;p++)d[p]=arguments[p];return __awaiter$4(this,void 0,void 0,(function(){var p,h,f,y,v,g,_,m,b,P,k,T,S,A;return __generator$4(this,(function(w){switch(w.label){case 0:if(!(p=d[t])||!Array.isArray(p))return[3,2];if(h=p[0].length||20,f=Math.floor(n/h),!((y=Math.ceil(p.length/f))>1))return[3,2];for(v=d.slice(0,t),g=d.slice(t+1),_=[],m=0,b=1;b<=y;b++)P=Math.min(b*f,p.length),k=p.slice(m,P),T=__spread$4(v,[k],g),_.push(l.apply(this,T)),m+=f;return[4,Promise.all(_)];case 1:return S=w.sent(),[2,(A=[]).concat.apply(A,S)];case 2:return[2,l.apply(this,d)]}}))}))}return Object.defineProperty(this,d,{value:chunkedIdApi,configurable:!0,writable:!0}),chunkedIdApi}}}};function transformParameters(t,n){if(void 0===n&&(n=25),t)return t.limit&&(t.limit=t.limit>n?n:t.limit),t}function transformStoreData(t){var n=Object.assign({},t),l=n.href;return void 0!==l&&(delete n.href,n.attributes=Ma(Ma({},n.attributes),{href:l})),n}function transformTrackParameters(t){return t.map((function(t){return"string"==typeof t?{id:t,type:"songs"}:{id:t.id,type:t.type||"songs"}}))}function transformDescriptorsToIdMap(t){var n,l,d={};if(!t)return d;try{for(var p=function(t){var n="function"==typeof Symbol&&t[Symbol.iterator],l=0;return n?n.call(t):{next:function(){return t&&l>=t.length&&(t=void 0),{value:t&&t[l++],done:!t}}}}(t),h=p.next();!h.done;h=p.next()){var f=h.value;if(f){var y=f.type,v=f.id;y in d||(d[y]=[]),d[y].push(v)}}}catch(g){n={error:g}}finally{try{h&&!h.done&&(l=p.return)&&l.call(p)}finally{if(n)throw n.error}}return d}var Os=["extend","include","l","platform","views"],Cs=function(){function LocalDataStore(t){void 0===t&&(t={}),this.enableDataStore=!1,t.features&&t.features.hasOwnProperty("api-data-store")&&(this.enableDataStore=!!t.features["api-data-store"]),this.enableDataStore&&(this._store=t.store||new ge,this._store.mapping=transformStoreData)}return Object.defineProperty(LocalDataStore.prototype,"hasDataStore",{get:function(){return this.enableDataStore&&void 0!==this._store},enumerable:!0,configurable:!0}),LocalDataStore.prototype.delete=function(t,n){this.hasDataStore&&this._store.remove(t,n)},LocalDataStore.prototype.read=function(t,n,l,d){d||"function"!=typeof l||(d=l,l=void 0);var p={},h=!1;if(l&&(h=Object.keys(l).some((function(t){return/^(fields|extend)/.test(t)})),l.views&&(p.views=l.views),l.include&&(p.relationships=l.include)),this.hasDataStore&&!h){var f=[];l&&(f=Object.keys(l).reduce((function(t,n){return-1===Os.indexOf(n)&&t.push([n,l[n]]),t}),f));var y=void 0;if(y=f&&1===f.length?this._store.query(f[0][0],f[0][1]):this._store.peek(t,n,p),Array.isArray(y)){if(!l&&y.length)return y}else if(y)return y}if("function"==typeof d)return d()},LocalDataStore.prototype.write=function(t){var n=this;return this._prepareDataForDataStore(t,(function(t){return n._store.save(t)}))},LocalDataStore.prototype.parse=function(t){var n=this;return this._prepareDataForDataStore(t,(function(t){return n._store.populateDataRecords(t,{})}))},LocalDataStore.prototype._prepareDataForDataStore=function(t,n){return this.hasDataStore?Array.isArray(t)?n({data:t}):Object.keys(t).reduce((function(l,d){var p=t[d];return p.hasOwnProperty("data")&&(l[d]=n({data:p.data})),"meta"===d&&(l[d]=t[d]),l}),{}):t},LocalDataStore}();function dasherize(t){return t.replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()}function makeAlbumKey(t){var n;return(null===(n=t.artwork)||void 0===n?void 0:n.url)+""+t.artistName+""+t.name}var Ms,Ds,Ls=function(){function ServerLedger(t,n,l){this._data=this._initData(),this._catalogApi=n,this._storageKey="mk-server-ledger:"+(t||""),this._sessionStorage=l||("undefined"!=typeof sessionStorage?sessionStorage:void 0),this.load()}return ServerLedger.prototype._initData=function(){return{lastTimestamp:0,albums:{added:Object.create(null),removed:Object.create(null)},playlists:{added:Object.create(null),removed:Object.create(null)}}},ServerLedger.prototype._checkTimestamp=function(){var t=this._data.lastTimestamp;t&&t+24e5<Date.now()&&(this._data=this._initData(),this._sessionStorage&&this._sessionStorage.removeItem(this._storageKey))},ServerLedger.prototype.added=function(t){var n=this;this.load();var l=null==t?void 0:t.playlists,d=null==t?void 0:t.albums;return l||d?(l&&l.forEach((function(t){var l=Date.now();n._data.playlists.added[t]=l,n._data.lastTimestamp=l})),d&&d.forEach((function(t){var l=Date.now();n._data.albums.added[t]=l,n._data.lastTimestamp=l})),this.save(),t):t},ServerLedger.prototype.removed=function(t){var n=this;this.load();var l=null==t?void 0:t.playlists;return l?(ensureArray(l).forEach((function(t){if(0!==t.indexOf("pl.")){var l=Date.now();n._data.playlists.removed[t]=l,n._data.lastTimestamp=l}})),this.save(),t):t},ServerLedger.prototype.reconcile=function(t,n,l,d,p){var h,f;return __awaiter$4(this,void 0,void 0,(function(){var p,y,v,g,_,m,b,P,k,T,S,A,w,I,E,R,O,C,M=this;return __generator$4(this,(function(D){switch(D.label){case 0:if(this._checkTimestamp(),!(p=n.data||n)||!Array.isArray(p)||Array.isArray(l))return[2,n];if(y=this._data.albums.added,v=this._data.playlists.removed,g=this._data.playlists.added,_=[],m=d&&!d.offset||!!l&&(void 0===l.offset||0===l.offset),b=!1,"all"!==t&&"playlists"!==t)return[3,2];for(w=p.length-1;w>=0;w--)I=p[w],E=null===(h=I.playParams)||void 0===h?void 0:h.globalId,"library-playlists"===I.type&&(v[I.id]?p.splice(w,1):E&&g[E]&&(delete g[E],b=!0,m||p.splice(w,1)));return m&&this._catalogApi&&(P=Object.keys(g)).length?[4,this._catalogApi.playlists(P)]:[3,2];case 1:k=D.sent(),_.splice.apply(_,__spread$4([0,0],k)),D.label=2;case 2:return!this._catalogApi||"all"!==t&&"albums"!==t?[3,4]:(T=Object.keys(y)).length?[4,this._catalogApi.albums(T)]:[3,4];case 3:for(S=D.sent(),A=Object.create(null),S.forEach((function(t,n){var l=makeAlbumKey(t);A[l]={catalogId:T[n],album:t}})),w=p.length-1;w>=0;w--)I=p[w],E=null===(f=I.playParams)||void 0===f?void 0:f.globalId,"library-albums"===I.type&&(R=makeAlbumKey(I),(O=A[R])&&(delete y[O.catalogId],b=!0,m?delete A[R]:p.splice(w,1)));m&&(C=Object.keys(A).map((function(t){return A[t].album}))).length&&_.splice.apply(_,__spread$4([0,0],C)),D.label=4;case 4:return b&&this.save(),m&&_.length&&(_.sort((function(t,n){var l=M._data.albums.added[t.id]||M._data.playlists.added[t.id]||0;return(M._data.albums.added[n.id]||M._data.playlists.added[n.id]||0)-l})),p.splice.apply(p,__spread$4([0,0],_))),[2,n]}}))}))},ServerLedger.prototype.load=function(){if(this._sessionStorage){var t=this._sessionStorage.getItem(this._storageKey);if(t)try{this._data=JSON.parse(t),this._data.albums&&this._data.playlists||(this._data=this._initData())}catch(e){this._data||(this._data=this._initData())}else this._data=this._initData()}},ServerLedger.prototype.save=function(){if(this._sessionStorage){var t=this._data,n=0===Object.keys(t.albums.added).length&&0===Object.keys(t.albums.removed).length&&0===Object.keys(t.playlists.added).length&&0===Object.keys(t.playlists.removed).length;try{if(n)this._sessionStorage.getItem(this._storageKey)&&this._sessionStorage.removeItem(this._storageKey);else{var l=JSON.stringify(this._data);this._sessionStorage.setItem(this._storageKey,l)}}catch(e){}}},ServerLedger}(),Ns="me/library",xs=function(t){function Library(n,l,d,p,h,f){void 0===p&&(p={});var y=t.call(this,n,l,Ma(Ma({},f),{userToken:d}))||this;return y._last=0,y._store=new Cs(p),y._serverLedger=new Ls(d,h),y.defaultIncludePaginationMetadata=p.features&&p.features.hasOwnProperty("api-pagination-metadata"),y}return __extends$4(Library,t),Library.prototype.add=function(t){return __awaiter$4(this,void 0,void 0,(function(){var n,l,d,p,h,f;return __generator$4(this,(function(y){switch(y.label){case 0:if(n=transformKeys(t,dasherize),(l=Date.now())-this._last<1e3)return[2,Promise.reject(new ke(ke.QUOTA_EXCEEDED))];d=new Headers({Authorization:"Bearer "+this.developerToken,"Music-User-Token":this.userToken}),p=Object.keys(n).map((function(t){return"ids["+t+"]="+n[t].join(",")})).join("&"),y.label=1;case 1:return y.trys.push([1,3,,4]),[4,fetch(this.url+"/"+Ns+"?"+p,{method:"POST",headers:d})];case 2:return(h=y.sent()).ok?(this._last=l,[2,this._serverLedger.added(n)]):[2,Promise.reject(ke.responseError(h))];case 3:return f=y.sent(),[2,Promise.reject(ke.responseError(f))];case 4:return[2]}}))}))},Library.prototype.remove=function(t){return __awaiter$4(this,void 0,void 0,(function(){var n,l,d,p,h,f;return __generator$4(this,(function(y){switch(y.label){case 0:if(!this.developerToken||!this.userToken)return[2,Promise.reject("Invalid tokens")];n=new Headers({Authorization:"Bearer "+this.developerToken,"Music-User-Token":this.userToken}),l=transformKeys(t,dasherize),d=Object.keys(l)[0],p=Object.values(l)[0],y.label=1;case 1:return y.trys.push([1,3,,4]),[4,fetch(this.url+"/"+Ns+"/"+d+"/"+p,{method:"DELETE",headers:n})];case 2:return(h=y.sent()).ok?[2,this._serverLedger.removed(l)]:[2,Promise.reject(ke.responseError(h))];case 3:return f=y.sent(),[2,Promise.reject(ke.responseError(f))];case 4:return[2]}}))}))},Library.prototype.album=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource("albums",t,n,l)]}))}))},Library.prototype.albumRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection("albums/"+t+"/"+n,void 0,l,d)]}))}))},Library.prototype.albums=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){switch(p.label){case 0:return[4,this.collection("albums",t,n,Ma(Ma({},l),{shouldCacheResults:!1}))];case 1:return d=p.sent(),[2,this._serverLedger.reconcile("albums",d,t,n,l)]}}))}))},Library.prototype.artist=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource("artists",t,n,l)]}))}))},Library.prototype.artistRelationship=function(t,n,l,d){return void 0===n&&(n="albums"),__awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection("artists/"+t+"/"+n,void 0,l,d)]}))}))},Library.prototype.artists=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection("artists",t,n,l)]}))}))},Library.prototype.createPlaylist=function(t,n){return void 0===t&&(t={}),__awaiter$4(this,void 0,void 0,(function(){var l,d,p,h,f,y,v,g,_;return __generator$4(this,(function(m){switch(m.label){case 0:d=t.name,p=t.description,h=t.tracks,f=transformTrackParameters(void 0===h?[]:h),y={attributes:{name:d,description:p},relationships:{tracks:{data:f}}},v=JSON.stringify(y),m.label=1;case 1:return m.trys.push([1,3,,4]),[4,this.request(Ns+"/playlists",n,{body:v,method:"POST"})];case 2:return l=m.sent(),[3,4];case 3:return g=m.sent(),[2,Promise.reject(ke.responseError(g))];case 4:try{return _=__read$4(this._store.write(l),1),[2,_[0]]}catch(ba){return[2,Promise.reject(ke.parseError(ba))]}return[2]}}))}))},Library.prototype.deletePlaylist=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){var l,d;return __generator$4(this,(function(p){switch(p.label){case 0:l=Ns+"/playlists/"+t,p.label=1;case 1:return p.trys.push([1,3,,4]),[4,this.request(l,n,{method:"DELETE"})];case 2:return p.sent(),[3,4];case 3:return d=p.sent(),[2,Promise.reject(ke.responseError(d))];case 4:return this.purgePlaylistFromCaches(t),[2]}}))}))},Library.prototype.editPlaylist=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d,p,h;return __generator$4(this,(function(f){switch(f.label){case 0:d=JSON.stringify({attributes:n}),f.label=1;case 1:return f.trys.push([1,3,,4]),[4,this.request(Ns+"/playlists/"+t,l,{body:d,method:"PATCH"})];case 2:return f.sent(),[3,4];case 3:return p=f.sent(),[2,Promise.reject(ke.responseError(p))];case 4:try{return h=n,"library-playlists",this._store.write({data:[{type:"library-playlists",id:t,attributes:h}]}),[2,n]}catch(ba){return[2,Promise.reject(ke.parseError(ba))]}return[2]}}))}))},Library.prototype.updatePlaylistTracklist=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){switch(l.label){case 0:return[4,this.putPlaylistTracklisting(t,n,"PUT")];case 1:return l.sent(),this.purgePlaylistFromCaches(t),[2]}}))}))},Library.prototype.appendTracksToPlaylist=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){switch(l.label){case 0:return[4,this.putPlaylistTracklisting(t,n,"POST")];case 1:return l.sent(),this.purgePlaylistFromCaches(t),[2]}}))}))},Library.prototype.playlistFolder=function(t,n,l){return this.resource("playlist-folders",t,n,l)},Library.prototype.playlistFolders=function(t,n,l){return this.collection("playlist-folders",t,n,l)},Library.prototype.playlistFoldersRoot=function(t,n){return t=Ma(Ma({},t),{filter:Ma(Ma({},null==t?void 0:t.filter),{identity:"playlistsroot"})}),this.playlistFolders(void 0,t,n)},Library.prototype.playlistFolderChildren=function(t,n,l){var d="playlist-folders/"+t+"/children";return this.collection(d,void 0,n,l)},Library.prototype.musicVideo=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource("music-videos",t,n,l)]}))}))},Library.prototype.musicVideos=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection("music-videos",t,n,l)]}))}))},Library.prototype.parseResultData=function(t,n){return t?this._store.write(n):this._store.parse(n)},Library.prototype.playlist=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return n=Object.assign({include:"tracks"},n),[2,this.resource("playlists",t,n,l)]}))}))},Library.prototype.createCatalogPlaylist=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return l=Ma({method:"POST"},l),[2,this.resource("playlists/"+t+"/catalog",void 0,n,l)]}))}))},Library.prototype.playlistRelationship=function(t,n,l,d){return void 0===n&&(n="tracks"),__awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection("playlists/"+t+"/"+n,void 0,l,d)]}))}))},Library.prototype.playlists=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d,p=this;return __generator$4(this,(function(h){switch(h.label){case 0:return t&&t.length>0?[4,Promise.all(t.map((function(t){return p.playlist(t,n,l)})))]:[3,2];case 1:return d=h.sent(),[3,4];case 2:return[4,this.collection("playlists",t,n,Ma(Ma({},l),{shouldCacheResults:!1}))];case 3:d=h.sent(),h.label=4;case 4:return[2,this._serverLedger.reconcile("playlists",d,t,n,l)]}}))}))},Library.prototype.recentlyAdded=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){var l,d;return __generator$4(this,(function(p){switch(p.label){case 0:return l=t&&t.limit,[4,this.collection("recently-added",void 0,transformParameters(t,l||10),Ma(Ma({},n),{shouldCacheResults:!1}))];case 1:return d=p.sent(),[2,this._serverLedger.reconcile("all",d,void 0,t,n)]}}))}))},Library.prototype.search=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return n=this._denormalizeLibraryTypes(n),d=Object.assign({term:t,types:"library-albums"},n),[2,this.collection("search",void 0,d,Ma(Ma({},l),{shouldCacheResults:!1}))]}))}))},Library.prototype.song=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource("songs",t,n,l)]}))}))},Library.prototype.songRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection("songs/"+t+"/"+n,void 0,l,d)]}))}))},Library.prototype.songs=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection("songs",t,n,l)]}))}))},Library.prototype.collection=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){var p;return __generator$4(this,(function(h){return!n||n.length||l||(l=transformParameters(n,100),n=void 0),p=n?Object.assign({ids:n},l):l,[2,makeRequest(this,Ns+"/"+t,p,d)]}))}))},Library.prototype.resource=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){var p,h,f;return __generator$4(this,(function(y){switch(y.label){case 0:return!(null==d?void 0:d.reload)&&(p=this._store.read(t,n,l))?[2,p]:(h=Ns+"/"+t,n&&(h=h+"/"+n),[4,makeRequest(this,h,l,d)]);case 1:return f=__read$4.apply(void 0,[y.sent(),1]),[2,f[0]]}}))}))},Library.prototype.purgePlaylistFromCaches=function(t){this._store.delete("library-playlists",t),this.clearCacheItems([this.constructURL(Ns+"/playlists/"+t,{})],!1)},Library.prototype.putPlaylistTracklisting=function(t,n,l){return void 0===l&&(l="PUT"),__awaiter$4(this,void 0,void 0,(function(){var d,p,h;return __generator$4(this,(function(f){switch(f.label){case 0:d=transformTrackParameters(n),p=JSON.stringify({data:d}),f.label=1;case 1:return f.trys.push([1,3,,4]),[4,this.request(Ns+"/playlists/"+t+"/tracks",void 0,{body:p,method:l})];case 2:return f.sent(),[3,4];case 3:return h=f.sent(),[2,Promise.reject(ke.responseError(h))];case 4:return[2]}}))}))},Library.prototype._denormalizeLibraryTypes=function(t,n){void 0===t&&(t={}),void 0===n&&(n="types");var l=t[n];return l?("string"==typeof l&&(l=l.split(",")),t[n]=l.map((function(t){return t.replace(/^(albums|music-videos|playlists|songs)$/,"library-$1")})),t):t},__decorate$2([ChunkedIdApi(1),__metadata$2("design:type",Function),__metadata$2("design:paramtypes",[String,Array,Object,Object]),__metadata$2("design:returntype",Promise)],Library.prototype,"collection",null),Library}(Rs),Us=function(t){function Books(n,l,d,p,h,f){void 0===h&&(h={});var y=t.call(this,"https://api.books.apple.com/v1",n,Ma(Ma({},f),{userToken:l,storage:p}))||this;return y.storefrontId=Gt.ID,d&&(y.storefrontId=d),y._store=new Cs(h),y.defaultIncludePaginationMetadata=h.features&&h.features.hasOwnProperty("api-pagination-metadata"),y}return __extends$4(Books,t),Books.prototype.audioBook=function(t,n,l){return this.resource("audio-books",t,n,l)},Books.prototype.audioBooks=function(t,n,l){return this.collection("audio-books",t,n,l)},Books.prototype.collection=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){var p;return __generator$4(this,(function(h){return p="catalog/"+this.storefrontId+"/"+t,n&&((l=l||{}).ids=n),[2,makeRequest(this,p,l,d)]}))}))},Books.prototype.parseResultData=function(t,n){return t?this._store.write(n):this._store.parse(n)},Books.prototype.resource=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){var p,h;return __generator$4(this,(function(f){switch(f.label){case 0:return!(null==d?void 0:d.reload)&&(p=this._store.read(t,n,l))?[2,p]:[4,this.collection(t,n,l,d)];case 1:return h=__read$4.apply(void 0,[f.sent(),1]),[2,h[0]]}}))}))},__decorate$2([ChunkedIdApi(1),__metadata$2("design:type",Function),__metadata$2("design:paramtypes",[String,Object,Object,Object]),__metadata$2("design:returntype",Promise)],Books.prototype,"collection",null),Books}(Rs),formatTimezoneOffset=function(t){void 0===t&&(t=new Date);var n=t.getTimezoneOffset(),l=Math.floor(Math.abs(n)/60),d=Math.round(Math.abs(n)%60),p="+";return 0!==n&&(p=n>0?"-":"+"),""+p+leadingZeros(l,2)+":"+leadingZeros(d,2)},leadingZeros=function(t,n){void 0===n&&(n=2);for(var l=""+t;l.length<n;)l="0"+l;return l},Bs=function(t){function Podcasts(n,l,d,p,h,f){void 0===d&&(d=Gt.ID),void 0===h&&(h={});var y=t.call(this,"https://amp-api.podcasts.apple.com/v1",n,Ma(Ma({},f),{userToken:l,storage:p}))||this;return y.storefrontId=d,y._store=new Cs(h),y.defaultIncludePaginationMetadata=h.features&&h.features.hasOwnProperty("api-pagination-metadata"),y}return __extends$4(Podcasts,t),Podcasts.prototype.artist=function(t,n,l){return this.resource("artists",t,n,l)},Podcasts.prototype.artists=function(t,n,l){return this.collection("artists",t,n,l)},Podcasts.prototype.artistRelationship=function(t,n,l,d){return this.collection("artists/"+t+"/"+n,void 0,l,d)},Podcasts.prototype.charts=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection("charts",t,n,l)]}))}))},Podcasts.prototype.podcast=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return d=Object.assign({include:"episodes"},n),[2,this.resource("podcasts",t,d,l)]}))}))},Podcasts.prototype.podcasts=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return d=Object.assign({include:"episodes"},n),[2,this.collection("podcasts",t,d,l)]}))}))},Podcasts.prototype.podcastRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection("podcasts/"+t+"/"+n,void 0,l,d)]}))}))},Podcasts.prototype.search=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return d=Object.assign({term:t,types:"podcasts"},n),[2,this.collection("search",void 0,d,l)]}))}))},Podcasts.prototype.episode=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource("podcast-episodes",t,n,l)]}))}))},Podcasts.prototype.episodes=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection("podcast-episodes",t,n,l)]}))}))},Podcasts.prototype.collection=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){var p,h;return __generator$4(this,(function(f){return n?((h={})["charts"===t?"types":"ids"]=n,p=Object.assign(h,l)):p=l,[2,makeRequest(this,"catalog/"+this.storefrontId+"/"+t,p,d)]}))}))},Podcasts.prototype.parseResultData=function(t,n){return t?this._store.write(n):this._store.parse(n)},Podcasts.prototype.resource=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){var p,h;return __generator$4(this,(function(f){switch(f.label){case 0:return!(null==d?void 0:d.reload)&&(p=this._store.read(t,n,l))?[2,p]:[4,this.collection(t,n,l,d)];case 1:return h=__read$4.apply(void 0,[f.sent(),1]),[2,h[0]]}}))}))},__decorate$2([ChunkedIdApi(1),__metadata$2("design:type",Function),__metadata$2("design:paramtypes",[String,Object,Object,Object]),__metadata$2("design:returntype",Promise)],Podcasts.prototype,"collection",null),Podcasts}(Rs),js=function(t){function TVLibrary(n,l,d,p,h){void 0===p&&(p={});var f=t.call(this,"https://amp-api.videos.apple.com/v1",n,Ma(Ma({},h),{userToken:l,storage:d}))||this;return f._store=new Cs(p),f.defaultIncludePaginationMetadata=p.features&&p.features.hasOwnProperty("api-pagination-metadata"),f}return __extends$4(TVLibrary,t),TVLibrary.prototype.genres=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection("genres",Ma({types:"tv-episodes,movies"},t),n)]}))}))},TVLibrary.prototype.movies=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection("movies",t,n)]}))}))},TVLibrary.prototype.purchases=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection("",Ma({types:"tv-episodes,movies"},t),n)]}))}))},TVLibrary.prototype.tvEpisodes=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection("tv-episodes",t,n)]}))}))},TVLibrary.prototype.collection=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){switch(p.label){case 0:return p.trys.push([0,2,,3]),[4,makeRequest(this,"me/purchases/"+t,n,l)];case 1:return[2,p.sent()];case 2:if((d=p.sent()).name===ke.CONTENT_UNAVAILABLE)return[2,(null==l?void 0:l.includePagination)?{data:[],meta:{}}:[]];throw d;case 3:return[2]}}))}))},TVLibrary.prototype.parseResultData=function(t,n){return t?this._store.write(n):this._store.parse(n)},__decorate$2([ChunkedIdApi(1),__metadata$2("design:type",Function),__metadata$2("design:paramtypes",[String,Object,Object]),__metadata$2("design:returntype",Promise)],TVLibrary.prototype,"collection",null),TVLibrary}(Rs),RecommendationUpdate=function(){return function(t,n,l){if(void 0===l||"function"!=typeof l.value)throw new TypeError("Only methods can be decorated with @RecommendationUpdate, but "+n+" is not a method.");return{configurable:!0,get:function(){var t=l.value;function recommendationUpdate(){for(var n=[],l=0;l<arguments.length;l++)n[l]=arguments[l];return __awaiter$4(this,void 0,void 0,(function(){var l,d,p,h,f,y,v,g,_;return __generator$4(this,(function(m){switch(m.label){case 0:return[4,t.apply(this,n)];case 1:return l=m.sent(),d=new Map,p=[],h=new Date,l&&Array.isArray(l)?(l.forEach((function(t,n){var l,f,y=t.id,v=null!==(l=t.nextUpdateDate)&&void 0!==l?l:null===(f=t.attributes)||void 0===f?void 0:f.nextUpdateDate;y&&v&&(new Date(v)<h&&(p.push(y),d.set(y,n)))})),p.length?(f=__read$4(n),f[0],y=f[1],v=f[2],g=f.slice(3),v=Ma(Ma({},v),{reload:!0}),_=__spread$4([p,y,v],g),[4,t.apply(this,_)]):[2,l]):[2,l];case 2:return m.sent().forEach((function(t){var n=d.get(t.id);void 0!==n&&(l[n]=t)})),[2,l]}}))}))}return Object.defineProperty(this,n,{value:recommendationUpdate,configurable:!0,writable:!0}),recommendationUpdate}}}};!function(t){t[t.Global=0]="Global",t.Catalog="catalog",t.Personalized="me",t.Editorial="editorial",t.Engagement="engagement",t.Social="social"}(Ms||(Ms={})),function(t){t.songs="songs",t.albums="albums",t.playlists="playlists",t.stations="stations",t["music-videos"]="music-videos",t["library-music-videos"]="library-music-videos",t["library-playlists"]="library-playlists",t["library-songs"]="library-songs"}(Ds||(Ds={}));var Fs,Ks=function(t){function API(n,l,d,p,h,f,y,v){var g;void 0===y&&(y={});var _=t.call(this,n,l,Ma(Ma({},v),{userToken:p,storage:f}))||this;return _.storefrontId=Gt.ID,_.resourceRelatives={artists:{albums:{include:"tracks"},playlists:{include:"tracks"},songs:null}},_.enableBundledInLibrary=!(null===(g=null==y?void 0:y.features)||void 0===g?void 0:g["disable-bundled-inlibrary"]),_.defaultIncludePaginationMetadata=y.features&&y.features.hasOwnProperty("api-pagination-metadata"),_._store=new Cs(y),_.useStorefrontRecommendations=y.features&&y.features.hasOwnProperty("use-storefront-recommendations"),d&&(_.storefrontId=d.toLowerCase()),p&&h&&(_.userStorefrontId=h.toLowerCase()),_._podcastsAPI=new Bs(l,p,d,f,y,Ma({},v)),_.tvLibrary=new js(l,p,f,y,Ma({},v)),_.library=new xs(n,l,p,y,_,Ma({},v)),_.books=new Us(l,p,d,f,y,Ma({},v)),_}return __extends$4(API,t),Object.defineProperty(API.prototype,"needsEquivalents",{get:function(){return this.userStorefrontId&&this.userStorefrontId!==this.storefrontId},enumerable:!0,configurable:!0}),API.prototype.activity=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"activities",t,n,l)]}))}))},API.prototype.activities=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"activities",t,n,l)]}))}))},API.prototype.album=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"albums",t,n,Ma(Ma({},l),{isPersonalized:this.enableBundledInLibrary}))]}))}))},API.prototype.albumRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection(Ms.Catalog,"albums/"+t+"/"+n,void 0,l,d)]}))}))},API.prototype.albums=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"albums",t,n,Ma(Ma({},l),{isPersonalized:this.enableBundledInLibrary}))]}))}))},API.prototype.appleCurator=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"apple-curators",t,n,l)]}))}))},API.prototype.appleCurators=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"apple-curators",t,n,l)]}))}))},API.prototype.artist=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"artists",t,n,l)]}))}))},API.prototype.artistRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection(Ms.Catalog,"artists/"+t+"/"+n,void 0,l,d)]}))}))},API.prototype.artistView=function(t,n,l,d){return this.collection(Ms.Catalog,"artists/"+t+"/view/"+n,void 0,l,d)},API.prototype.artists=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"artists",t,n,l)]}))}))},API.prototype.audioBook=function(t,n,l){return this.books.audioBook(t,n,l)},API.prototype.audioBooks=function(t,n,l){return this.books.audioBooks(t,n,l)},API.prototype.catalogResources=function(t,n,l){void 0===n&&(n={});var d=transformDescriptorsToIdMap(t);return n=Ma(Ma({},n),{ids:d}),makeRequest(this,Ms.Catalog+"/"+this.storefrontId,n,l)},API.prototype.changeStation=function(t,n,l){return void 0===l&&(l={}),__awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){switch(d.label){case 0:return[4,makeRequest(this,"me/stations/change-station/"+t,n,Ma(Ma({},l),{reload:!0,method:"POST",shouldCacheResults:!1}))];case 1:return[2,d.sent()]}}))}))},API.prototype.charts=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"charts",t,n,Ma(Ma({},l),{returnRawJSONApiRecords:!0}))]}))}))},API.prototype.contents=function(t,n,l){return this.collection(Ms.Catalog,"contents",t,n,l)},API.prototype.curator=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"contents",t,n,l)]}))}))},API.prototype.curators=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"contents",t,n,l)]}))}))},API.prototype.episode=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this._podcastsAPI.episode(t,n,l)]}))}))},API.prototype.episodes=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this._podcastsAPI.episodes(t,n,l)]}))}))},API.prototype.genre=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"genres",t,n,l)]}))}))},API.prototype.genres=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"genres",t,n,l)]}))}))},API.prototype.grouping=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return!n&&isObject(t)&&(n=t,t=void 0),d=Ma(Ma({},{platform:"desktop"}),n),[2,this.resource(Ms.Editorial,"groupings",t,d,Ma(Ma({},l),{shouldCacheResults:!1}))]}))}))},API.prototype.groupings=function(t,n,l){return void 0===n&&(n={}),__awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return d=Ma(Ma({},{platform:"desktop"}),n),[2,this.collection(Ms.Editorial,"groupings",t,d,Ma(Ma({},l),{shouldCacheResults:!1}))]}))}))},API.prototype.lyric=function(t,n,l){return this.resource(Ms.Catalog,"songs/"+t+"/lyrics","",n,Ma({reload:!0},l))},API.prototype.historyHeavyRotation=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection(Ms.Personalized,"history/heavy-rotation",void 0,transformParameters(t,10),n)]}))}))},API.prototype.multiplex=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return(d=this._store.read("multiplex",t,n))?[2,d]:(l=Object.assign({returnRawJSONApiRecords:!0},l),[2,makeRequest(this,Ms.Editorial+"/"+this.storefrontId+"/multiplex/"+t,n,l)])}))}))},API.prototype.multiroom=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d,p;return __generator$4(this,(function(h){switch(h.label){case 0:return(d=this._store.read("multirooms",t,n))?[2,d]:[4,this.collection(Ms.Editorial,"multirooms/"+t,void 0,n,l)];case 1:return p=__read$4.apply(void 0,[h.sent(),1]),[2,p[0]]}}))}))},API.prototype.musicMovie=function(t,n,l){return this.resource(Ms.Catalog,"music-movies",t,n,l)},API.prototype.musicMovies=function(t,n,l){return this.collection(Ms.Catalog,"music-movies",t,n,l)},API.prototype.musicVideo=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"music-videos",t,n,l)]}))}))},API.prototype.musicVideos=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"music-videos",t,n,l)]}))}))},API.prototype.nextStationTracks=function(t,n,l){return void 0===l&&(l={}),__awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){switch(p.label){case 0:return d={},(null==n?void 0:n.clean)&&(d.clean=n.clean,delete n.clean),(null==n?void 0:n.limit)&&(d.limit=n.limit,delete n.limit),[4,makeRequest(this,"me/stations/next-tracks/"+t,n,Ma(Ma({},l),{reload:!0,method:"POST",queryParameters:d,shouldCacheResults:!1}))];case 1:return[2,p.sent()]}}))}))},API.prototype.playlist=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"playlists",t,n,Ma(Ma({},l),{isPersonalized:this.enableBundledInLibrary}))]}))}))},API.prototype.playlistRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection(Ms.Catalog,"playlists/"+t+"/"+n,void 0,l,d)]}))}))},API.prototype.playlists=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Catalog,"playlists",t,n,Ma(Ma({},l),{isPersonalized:this.enableBundledInLibrary}))]}))}))},API.prototype.podcast=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this._podcastsAPI.podcast(t,n,l)]}))}))},API.prototype.podcastRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this._podcastsAPI.podcastRelationship(t,n,l,d)]}))}))},API.prototype.podcasts=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this._podcastsAPI.podcasts(t,n,l)]}))}))},API.prototype.recentPlayed=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection(Ms.Personalized,"recent/played",void 0,transformParameters(t,10),n)]}))}))},API.prototype.recentRadioStations=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection(Ms.Personalized,"recent/radio-stations",void 0,transformParameters(t,10),n)]}))}))},API.prototype.personalRecommendation=function(t,n,l,d){return void 0===d&&(d=!0),__awaiter$4(this,void 0,void 0,(function(){var p,h;return __generator$4(this,(function(f){switch(f.label){case 0:return[4,this.personalRecommendations(t,n,l,d)];case 1:return p=f.sent(),h=__read$4(p,1),[2,h[0]]}}))}))},API.prototype.refreshPersonalRecommendation=function(t,n,l){var d=formatTimezoneOffset();return n=Ma({timezone:d},n),l=Ma(Ma({},l),{method:"POST",queryParameters:n}),this.resource(Ms.Personalized,"recommendations",t,void 0,l)},API.prototype.personalRecommendations=function(t,n,l,d){return void 0===l&&(l={}),void 0===d&&(d=!0),__awaiter$4(this,void 0,void 0,(function(){var p,h,f=this;return __generator$4(this,(function(y){switch(y.label){case 0:return p=formatTimezoneOffset(),[4,this.collection(Ms.Personalized,"recommendations",t,Ma({timezone:p},n),Ma(Ma({},l),{shouldCacheResults:d,returnRawJSONApiRecords:!0}))];case 1:h=y.sent(),this._reindexRelationships(h,"recommendations");try{return[2,mapRequestResult(h,(function(t){return f.parseResultData(!1,t)}))]}catch(ba){return[2,Promise.reject(ke.parseError(ba))]}return[2]}}))}))},API.prototype.personalRecommendationView=function(t,n,l,d){return void 0===d&&(d={}),__awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection(Ms.Personalized,"recommendations/"+t+"/view/"+n,void 0,l,d)]}))}))},API.prototype.recommendations=function(t,n,l,d){return void 0===l&&(l={}),void 0===d&&(d=!0),__awaiter$4(this,void 0,void 0,(function(){var p,h,f=this;return __generator$4(this,(function(y){switch(y.label){case 0:return p=formatTimezoneOffset(),this.useStorefrontRecommendations?[4,this.collection(Ms.Global,"recommendations/"+this.storefrontId,t,Ma({timezone:p},n),Ma(Ma({},l),{shouldCacheResults:!1,returnRawJSONApiRecords:!0}))]:[2,this.personalRecommendations(t,n,l,d)];case 1:h=y.sent(),this._reindexRelationships(h,"recommendations");try{return[2,mapRequestResult(h,(function(t){return f.parseResultData(!1,t)}))]}catch(ba){return[2,Promise.reject(ke.parseError(ba))]}return[2]}}))}))},API.prototype.recommendedFriends=function(t,n,l){return void 0===l&&(l={}),l=Ma(Ma({},l),{method:"POST",body:JSON.stringify(Ma({ids:{socialProfiles:t}},l.body))}),this.collection(Ms.Global,"social/recommended-friends",void 0,n,Ma(Ma({},l),{shouldCacheResults:!1,returnRawJSONApiRecords:!0}))},API.prototype.room=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d,p,h;return __generator$4(this,(function(f){switch(f.label){case 0:return(d=this._store.read("rooms",t,n))&&d.hasAttributes("title")?[2,d]:[4,this.collection(Ms.Editorial,"rooms/"+t,void 0,n,l)];case 1:return p=f.sent(),h=__read$4(p,1),[2,h[0]]}}))}))},API.prototype.roomContents=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Editorial,"rooms/"+t+"/contents",void 0,n,l)]}))}))},API.prototype.search=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){return d=Object.assign({term:t},transformParameters(n)),l=Ma(Ma({},l),{useRawResponse:!0}),[2,this.collection(Ms.Catalog,"search",void 0,d,Ma(Ma({},l),{shouldCacheResults:!1}))]}))}))},API.prototype.searchHints=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d,p;return __generator$4(this,(function(h){switch(h.label){case 0:return d=Object.assign({term:t},transformParameters(n)),[4,this.collection(Ms.Catalog,"search/hints",void 0,d,Ma(Ma({},l),{returnRawJSONApiRecords:!0}))];case 1:return p=h.sent(),"topResults"===(null==d?void 0:d.with)&&"topResults"in p&&(p.topResults=this.parseResultData(!0,p.topResults)),[2,p]}}))}))},API.prototype.searchQuery=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return n=Ma(Ma({},n),{useRawResponse:!0}),[2,this.collection(Ms.Catalog,"search/query",void 0,t,Ma(Ma({},n),{shouldCacheResults:!1}))]}))}))},API.prototype.searchSuggestions=function(t,n,l){var d;return __awaiter$4(this,void 0,void 0,(function(){var p,h=this;return __generator$4(this,(function(f){switch(f.label){case 0:return n=Ma({term:t},n),[4,this.collection(Ms.Catalog,"search/suggestions",void 0,n,Ma(Ma({},l),{returnRawJSONApiRecords:!0}))];case 1:return p=f.sent(),Array.isArray(null===(d=p)||void 0===d?void 0:d.suggestions)&&p.suggestions.forEach((function(t){"topResults"===t.kind&&(t.content=h.parseResultData(!0,[t.content])[0])})),[2,p]}}))}))},API.prototype.socialBadgingMap=function(t,n){return this.collection(Ms.Global,"social/badging-map",void 0,t,Ma(Ma({},n),{returnRawJSONApiRecords:!0}))},API.prototype.socialProfile=function(t,n,l){return this.resource(Ms.Social,"social-profiles",t,n,l)},API.prototype.socialProfiles=function(t,n,l){return this.collection(Ms.Social,"social-profiles",t,n,l)},API.prototype.personalSocialProfile=function(t,n){return this.resource(Ms.Personalized,"social-profile",void 0,t,n)},API.prototype.socialPost=function(t,n,l){return void 0===n&&(n={}),__awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){switch(p.label){case 0:return t.startsWith("sa.")?n.filter={post:t}:n.ids=t,[4,this.collection(Ms.Catalog,"contents","",n,l)];case 1:return d=__read$4.apply(void 0,[p.sent(),1]),[2,d[0]]}}))}))},API.prototype.socialSearch=function(t,n,l){return void 0===n&&(n={}),__awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return n=Ma(Ma({},n),{term:t}),[2,this.collection(Ms.Social,"search",void 0,n,l)]}))}))},API.prototype.song=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"songs",t,n,Ma(Ma({},l),{isPersonalized:this.enableBundledInLibrary}))]}))}))},API.prototype.songRelationship=function(t,n,l,d){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(p){return[2,this.collection(Ms.Catalog,"songs/"+t+"/"+n,void 0,l,d)]}))}))},API.prototype.songs=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return!n&&isObject(t)&&(n=t,t=void 0),[2,this.collection(Ms.Catalog,"songs",t,n,Ma(Ma({},l),{isPersonalized:this.enableBundledInLibrary}))]}))}))},API.prototype.tastePreferences=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection(Ms.Personalized,"taste/taste-preferences",void 0,t,Ma(Ma({},n),{shouldCacheResults:!1}))]}))}))},API.prototype.saveTastePreferences=function(t){return __awaiter$4(this,void 0,void 0,(function(){var n,l;return __generator$4(this,(function(d){switch(d.label){case 0:t=t.map((function(t){return t instanceof ve?t.serialize().data:t})),n={method:"POST",body:JSON.stringify({data:t}),shouldCacheResults:!0},d.label=1;case 1:return d.trys.push([1,3,,4]),[4,makeRequest(this,"me/taste/taste-preferences",void 0,n)];case 2:return[2,d.sent()];case 3:return(l=d.sent()).name===ke.CONTENT_UNAVAILABLE?[2,[]]:[2,Promise.reject(ke.parseError(l))];case 4:return[2]}}))}))},API.prototype.tvEpisode=function(t,n,l){return this.resource(Ms.Catalog,"tv-episodes",t,Ma({include:"seasons"},n),l)},API.prototype.tvEpisodes=function(t,n,l){return this.collection(Ms.Catalog,"tv-episodes",t,Ma({include:"seasons"},n),l)},API.prototype.tvSeason=function(t,n,l){return this.resource(Ms.Catalog,"tv-seasons",t,Ma({include:"episodes"},n),l)},API.prototype.tvSeasons=function(t,n,l){return this.collection(Ms.Catalog,"tv-seasons",t,Ma({include:"episodes"},n),l)},API.prototype.tvShow=function(t,n,l){return this.resource(Ms.Catalog,"tv-shows",t,n,l)},API.prototype.tvShows=function(t,n,l){return this.collection(Ms.Catalog,"tv-shows",t,n,l)},API.prototype.uploadedAudio=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return n=Object.assign({include:"curator,artists"},n),[2,this.resource(Ms.Catalog,"uploaded-audios",t,n,l)]}))}))},API.prototype.uploadedAudios=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return n=Object.assign({include:"curator,artists"},n),[2,this.collection(Ms.Catalog,"uploaded-audios",t,n,l)]}))}))},API.prototype.uploadedVideo=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return n=Object.assign({include:"curator,artists"},n),[2,this.resource(Ms.Catalog,"uploaded-videos",t,n,l)]}))}))},API.prototype.uploadedVideos=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return n=Object.assign({include:"curator,artists"},n),[2,this.collection(Ms.Catalog,"uploaded-videos",t,n,l)]}))}))},API.prototype.upsellMarketingItems=function(t,n){return this.collection(Ms.Engagement,"upsell/marketing-items",void 0,t,n)},API.prototype.station=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Catalog,"stations",t,n,l)]}))}))},API.prototype.stations=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return!n&&isObject(t)&&(n=t,t=void 0),[2,this.collection(Ms.Catalog,"stations",t,n,l)]}))}))},API.prototype.storefront=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Global,"storefronts",t,n,l)]}))}))},API.prototype.storefronts=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.collection(Ms.Global,"storefronts",t,n,l)]}))}))},API.prototype.musicSummary=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(d){return[2,this.resource(Ms.Personalized,"music-summaries",t,n,l)]}))}))},API.prototype.musicSummarySearch=function(t,n){return void 0===t&&(t={}),__awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(l){return[2,this.collection(Ms.Personalized,"music-summaries/search",void 0,t,n)]}))}))},API.prototype.addToLibrary=function(t){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(n){return this.developerToken&&this.userToken&&this.library?[2,this.library.add(t)]:[2,Promise.reject("Invalid tokens")]}))}))},API.prototype.rating=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d;return __generator$4(this,(function(p){switch(p.label){case 0:return[4,this.ratings(t,n,l)];case 1:return d=__read$4.apply(void 0,[p.sent(),1]),[2,d[0]]}}))}))},API.prototype.ratings=function(t,n,l){if(!this.developerToken||!this.userToken)return Promise.reject("Invalid tokens");var d=__read$4(Object.keys(t),1)[0],p=t[d],h=Array.isArray(p);if(h&&0===p.length)return Promise.resolve([]);var f="me/ratings/"+formatRatingsContentType(d,h?p[0]:p);return h?n=Ma(Ma({},n),{ids:p}):f=f+"/"+p,makeRequest(this,f,n,Ma({shouldCacheResults:!1,reload:!0,includePagination:!1},l))},API.prototype.putRating=function(t,n,l){return __awaiter$4(this,void 0,void 0,(function(){var d,p,h,f,y,v,g;return __generator$4(this,(function(_){switch(_.label){case 0:return this.developerToken&&this.userToken?(d=__read$4(Object.keys(t),1),p=d[0],h=t[p],f=formatRatingsContentType(p,h),y={method:"PUT",body:JSON.stringify({type:"rating",attributes:{value:n}}),includePagination:!1},[4,makeRequest(this,"me/ratings/"+f+"/"+h,l,Object.assign({shouldCacheResults:!1},y))]):[2,Promise.reject("Invalid tokens")];case 1:return v=_.sent(),g=__read$4(v,1),[2,g[0]]}}))}))},API.prototype.deleteRating=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){var l,d,p,h,f=this;return __generator$4(this,(function(y){switch(y.label){case 0:return this.developerToken&&this.userToken?(l=__read$4(Object.keys(t),1),d=l[0],p=t[d],h=formatRatingsContentType(d,p),Array.isArray(p)?[2,Promise.all(p.map((function(t){var l;return f.deleteRating(((l={})[d]=t,l),n)}))).then((function(){}))]:[4,makeRequest(this,"me/ratings/"+h+"/"+p,n,{method:"DELETE",shouldCacheResults:!1,returnRawJSONApiRecords:!0})]):[2,Promise.reject("Invalid tokens")];case 1:y.sent();try{this._store.delete(h,p)}catch(ba){return[2,Promise.reject(ke.parseError(ba))]}return[2]}}))}))},API.prototype.equivalent=function(t,n){return __awaiter$4(this,void 0,void 0,(function(){var l,d;return __generator$4(this,(function(p){switch(l="catalog/"+this.userStorefrontId+"/"+t,d={},t){case"albums":case"songs":d={"filter[equivalents]":n};break;case"artists":case"playlists":l=l+"/"+n;break;default:return[2,Promise.reject(new ke(ke.INVALID_ARGUMENTS,"Invalid equivalent type"))]}return[2,this.resource(Ms.Global,l,"",d)]}))}))},API.prototype.collection=function(t,n,l,d,p){return __awaiter$4(this,void 0,void 0,(function(){var h,f,y,v,g;return __generator$4(this,(function(_){switch(y=null==p?void 0:p.shouldCacheResults,h=l?Ma(((g={})["charts"===n?"types":"ids"]=l,g),d):d,t){case Ms.Catalog:case Ms.Editorial:case Ms.Engagement:case Ms.Social:v=this.storefrontId,f=t+"/"+v+"/"+n;break;case Ms.Global:f=n;break;case Ms.Personalized:f=t+"/"+n,y=!1}return[2,makeRequest(this,f,h,Ma(Ma({},p),{shouldCacheResults:y}))]}))}))},API.prototype.parseResultData=function(t,n){return t?this._store.write(n):this._store.parse(n)},API.prototype.resource=function(t,n,l,d,p){return __awaiter$4(this,void 0,void 0,(function(){var h,f;return __generator$4(this,(function(y){switch(y.label){case 0:return!(null==p?void 0:p.reload)&&(h=this._store.read(n,l,d))?[2,h]:[4,this.collection(t,n,l,d,p)];case 1:return f=__read$4.apply(void 0,[y.sent(),1]),[2,f[0]]}}))}))},API.prototype._reindexRelationships=function(t,n){("data"in t?t.data:t).forEach((function(t){t.hasOwnProperty("relationships")&&t.relationships.hasOwnProperty(n)&&t.relationships[n].hasOwnProperty("data")&&Array.isArray(t.relationships[n].data)&&t.relationships[n].data.forEach((function(t,n){t.id=t.id+"-"+n}))}))},__decorate$2([RecommendationUpdate(),__metadata$2("design:type",Function),__metadata$2("design:paramtypes",[Object,Object,Object,Object]),__metadata$2("design:returntype",Promise)],API.prototype,"personalRecommendations",null),__decorate$2([RecommendationUpdate(),__metadata$2("design:type",Function),__metadata$2("design:paramtypes",[Object,Object,Object,Object]),__metadata$2("design:returntype",Promise)],API.prototype,"recommendations",null),__decorate$2([ChunkedIdApi(2),__metadata$2("design:type",Function),__metadata$2("design:paramtypes",[Object,String,Object,Object,Object]),__metadata$2("design:returntype",Promise)],API.prototype,"collection",null),API}(Rs),configure$2=function(t,n){return void 0===n&&(n=!1),__awaiter(void 0,void 0,void 0,(function(){return __generator(this,(function(l){if(Fs&&!n){if(void 0===t.storefrontId||t.storefrontId===Fs.storefrontId)return[2,Fs];Fs.clear()}return[2,(Fs=new $s(t.dispatcher)).configure(t)]}))}))},Vs={album:{isPlural:!1,apiMethod:"album",relationshipMethod:{method:"albumRelationship",relationship:"tracks"}},albums:{isPlural:!0,apiMethod:"albums"},audioBook:{isPlural:!1,apiMethod:"audioBook"},audioBooks:{isPlural:!0,apiMethod:"audioBooks"},episode:{isPlural:!1,apiMethod:"episode"},episodes:{isPlural:!0,apiMethod:"episodes"},musicVideo:{isPlural:!1,apiMethod:"musicVideo"},musicVideos:{isPlural:!0,apiMethod:"musicVideos"},musicMovie:{isPlural:!1,apiMethod:"musicMovie"},musicMovies:{isPlural:!0,apiMethod:"musicMovies"},podcast:{isPlural:!1,apiMethod:"podcast"},podcasts:{isPlural:!0,apiMethod:"podcasts"},playlist:{isPlural:!1,apiMethod:"playlist",relationshipMethod:{method:"playlistRelationship",relationship:"tracks"}},playlists:{isPlural:!0,apiMethod:"playlists"},song:{isPlural:!1,apiMethod:"song"},songs:{isPlural:!0,apiMethod:"songs"},tvEpisode:{isPlural:!1,apiMethod:"tvEpisode"},tvEpisodes:{isPlural:!0,apiMethod:"tvEpisodes"},uploadedAudio:{isPlural:!1,apiMethod:"uploadedAudio"},uploadedAudios:{isPlural:!0,apiMethod:"uploadedAudios"},uploadedVideo:{isPlural:!1,apiMethod:"uploadedVideo"},uploadedVideos:{isPlural:!0,apiMethod:"uploadedVideos"}},$s=function(){function MediaAPIService(t){var n=this;this._dispatcher=t,this.url=ur.urls.mediaApi,this.namedQueueOptions=Vs,this._dispatcher.subscribe(er.apiStorefrontChanged,(function(t,l){var d=l.storefrontId;return __awaiter(n,void 0,void 0,(function(){return __generator(this,(function(t){switch(t.label){case 0:return[4,this._updateStorefrontId(d)];case 1:return t.sent(),[2]}}))}))}))}return Object.defineProperty(MediaAPIService.prototype,"api",{get:function(){if(void 0===this._api)throw new ke(ke.CONFIGURATION_ERROR,"The API cannot be accessed before it is configured.");return this._api},enumerable:!0,configurable:!0}),Object.defineProperty(MediaAPIService.prototype,"storefrontId",{get:function(){return this.store&&this.store.storefrontId},enumerable:!0,configurable:!0}),MediaAPIService.prototype.configure=function(t){return __awaiter(this,void 0,void 0,(function(){var n=this;return __generator(this,(function(l){return void 0===t.store?[2]:(this.store=t.store,[nr.userTokenDidChange,nr.storefrontIdentifierDidChange].forEach((function(t){n.store.storekit.addEventListener(t,(function(){return n.resetAPI()}))})),this._initializeAPI(t),[2,this])}))}))},MediaAPIService.prototype.clear=function(){this.api&&this.api.clearCacheItems()},MediaAPIService.prototype.getAPIForItem=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return ae(t)?[4,this.store.authorize()]:[3,2];case 1:return n.sent(),[2,this.api.library];case 2:return[2,this.api]}}))}))},MediaAPIService.prototype.resetAPI=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(t){return this.clear(),this._initializeAPI(),[2]}))}))},MediaAPIService.prototype._initializeAPI=function(t){if(void 0===(null==t?void 0:t.api)){var n=t&&t.store||this.store;if(void 0!==n){var l=ur.features["api-session-storage"]?sessionStorage:void 0,d=t&&t.storefrontId||n.storefrontId;this._api=new Ks(this.url,n.developerToken,d,n.storekit.userToken,n.storekit.storefrontCountryCode,l,ur,t&&t.apiOptions&&t.apiOptions.sessionOptions)}}else this._api=t.api},MediaAPIService.prototype._updateStorefrontId=function(t){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){switch(n.label){case 0:return this.api&&t===this.api.storefrontId?[2]:[4,this.configure({dispatcher:this._dispatcher,store:this.store,storefrontId:t})];case 1:return n.sent(),[2]}}))}))},MediaAPIService}(),Hs={results:{links:[{feature:"album-song",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/albums?/(?:[^/]+/)?(?<album>\\d+)$",requiredQueryParams:{i:"(?<identifier>\\d+)"},mediaAPI:{resources:["songs"]}},{feature:"albums",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/albums?/(?:[^/]+/)?(?<identifier>\\d+)$",mediaAPI:{resources:["albums"]}},{feature:"algo-stations",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/stations?/(?:[^/]+/)?(?<identifier>(?:ra|st).\\d+)",mediaAPI:{resources:["stations"]}},{feature:"artist-default-playable-content",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/artists?/(?:[^/]+/)?(?<identifier>\\d+)$",mediaAPI:{resources:["artists","default-playable-content"]}},{feature:"genre-stations",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/genre-stations?",mediaAPI:{resources:["stations"],parameterMapping:{genres:"filter[genres]",eras:"filter[eras]",tags:"filter[tags]",moods:"filter[moods]"}}},{feature:"personal-general-radio",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/stations?/me$",mediaAPI:{resources:["stations"],parameters:{"filter[identity]":"personal"}}},{feature:"personal-mixes",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/(?:personal-)?mix/(?:[^/]+/)?(?<identifier>mx.(?:\\d{1,2}|rp-\\d{4}))$",mediaAPI:{resources:["playlists"]}},{feature:"playlists",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/(?<storefront>\\w{2})/playlists?/(?:[^/]+/)?(?<identifier>(?:pl).[a-zA-Z0-9-]+)$",mediaAPI:{resources:["playlists"]}},{feature:"steering-request",regex:"http(?:s)?://(?<realm>itunes|music).apple.com/me/stations?/change-station/?$",mediaAPI:{resources:["stations"]}}]}};function loadLinksData(){return __awaiter$4(this,void 0,void 0,(function(){var t;return __generator$4(this,(function(n){return t=Hs.results.links.map((function(t){return t.regex=new RegExp(t.regex),t.requiredQueryParams&&(t.requiredQueryParams=Object.keys(t.requiredQueryParams).reduce((function(n,l){return n[l]=new RegExp(t.requiredQueryParams[l]),n}),{})),t})),[2,Promise.resolve(t)]}))}))}function filterLinks(t){return __awaiter$4(this,void 0,void 0,(function(){var n,l;return __generator$4(this,(function(d){switch(d.label){case 0:return[4,loadLinksData()];case 1:return n=d.sent(),l=parseQueryParams(t),[2,n.reduce((function(n,d){if(function(t,n,l){void 0===l&&(l={});var d=__read$4(t.split(/\?|\#|\&/),1)[0],p=n.regex.test(d);return p&&n.requiredQueryParams?Object.keys(n.requiredQueryParams).every((function(t){var d=l[t];return n.requiredQueryParams[t].test(d)})):p}(t,d,l)){if(n.length>0)if(d.requiredQueryParams)n=n.filter((function(t){return t.requiredQueryParams}));else if(n.some((function(t){return t.requiredQueryParams})))return n;d.requiredQueryParams?d.mediaAPI.parameters=Object.keys(d.requiredQueryParams).reduce((function(t,n){return t[n]=l[n],t}),{}):d.mediaAPI.parameterMapping&&(d.mediaAPI.parameters=transform(d.mediaAPI.parameterMapping,l,!0)),n.push(d)}return n}),[])]}}))}))}var zs=/^http(?:s)?\:\/\/(?:itunes|(embed\.)?(music|podcasts))\.apple\.com/i,Ws=["allow-forms","allow-popups","allow-same-origin","allow-scripts","allow-storage-access-by-user-activation","allow-top-navigation-by-user-activation"];var Ys=ke.errors,qs=function(t){function MusicKitInstance(){return null!==t&&t.apply(this,arguments)||this}return __extends(MusicKitInstance,t),MusicKitInstance.prototype.addToLibrary=function(t,n){return __awaiter(this,void 0,void 0,(function(){var l;return __generator(this,(function(d){switch(d.label){case 0:return[4,this.authorize()];case 1:return d.sent(),n||(n=/[a-z]{2}\.[a-z0-9\-]+/i.test(t)?"playlists":"albums"),(l={})[n]=[t],[2,this.api.addToLibrary(l)]}}))}))},MusicKitInstance.prototype.changeToMediaItem=function(n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){return this._checkNeedsEquivalent(),[2,t.prototype.changeToMediaItem.call(this,n)]}))}))},MusicKitInstance.prototype.play=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(n){return this._checkNeedsEquivalent(),[2,t.prototype.play.call(this)]}))}))},MusicKitInstance.prototype.playMediaItem=function(n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){return this._checkNeedsEquivalent(),[2,t.prototype.playMediaItem.call(this,n)]}))}))},MusicKitInstance.prototype.setQueue=function(n){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(l){return this._checkNeedsEquivalent(),[2,t.prototype.setQueue.call(this,n)]}))}))},MusicKitInstance.prototype._checkNeedsEquivalent=function(){var t;if(!this.previewOnly&&(null===(t=this.api)||void 0===t?void 0:t.needsEquivalents))throw new ke(ke.CONTENT_EQUIVALENT)},MusicKitInstance}(_s);t.Events=nr,t.MKError=ke,t.MediaItem=Aa,t.MusicKitInstance=qs,t.VideoTypes={movie:!0,musicVideo:!0,musicMovie:!0,trailer:!0,tvEpisode:!0,uploadedVideo:!0,"uploaded-videos":!0,"music-videos":!0,"music-movies":!0,"tv-episodes":!0,Episode:!0,Movie:!0,Show:!0,Vod:!0,EditorialVideoClip:!0},t.configure=function(t){return __awaiter(this,void 0,void 0,(function(){var n,l,d;return __generator(this,(function(p){switch(p.label){case 0:return n=new kr,t.playActivityAPI=n,[4,configure$1(t,qs)];case 1:return l=p.sent(),(d={apiType:ss.MEDIA,configureFn:configure$2,options:{}}).options.apiOptions=t.apiOptions,[4,l.configure([d])];case 2:return p.sent(),t.declarativeMarkup&&function(t){var n=t.services.dispatcher,l={defaultText:"Sign In to Apple Music",click:t.authorize.bind(t),display:function(){return t.canAuthorize()}},d={content:function(){return formatMediaTime(t.currentPlaybackDuration)},display:function(){return t.nowPlayingItem}},p={content:function(){return Math.round(100*t.currentPlaybackProgress)+"%"},display:function(){return t.nowPlayingItem}},h={content:function(){return formatMediaTime(t.currentPlaybackTime)},display:function(){return t.nowPlayingItem}},f={click:function(t){var n=t.target;n.togglePlaybackTime=!n.togglePlaybackTime},content:function(n){return formatMediaTime(n.togglePlaybackTime?t.currentPlaybackDuration:t.currentPlaybackTimeRemaining)},display:function(){return t.nowPlayingItem}},y={defaultText:"Sign Out of Apple Music",click:t.unauthorize.bind(t),display:function(){return t.canUnauthorize()}},v=new ws({"apple-music-authorize":l,"apple-music-current-playback-duration":d,"apple-music-current-playback-progress":p,"apple-music-current-playback-time":h,"apple-music-current-playback-time-remaining":f,"apple-music-unauthorize":y,"data-apple-music-authorize":l,"data-apple-music-add-to-library":{click:function(n){var l=n.target.dataset,d=l.appleMusicAddToLibrary,p=l.appleMusicType;t.addToLibrary(d,p)}},"data-apple-music-current-playback-duration":d,"data-apple-music-current-playback-progress":p,"data-apple-music-current-playback-time":h,"data-apple-music-current-playback-time-remaining":f,"data-apple-music-now-playing":{content:function(n){var l=n.dataset.appleMusicNowPlaying||"info",d=get(t.nowPlayingItem,l);if(!(/artworkurl$/i.test(l)&&n.height&&n.width))return d;n.src=formatArtworkURL({url:d},n.height,n.width)},display:function(){return t.nowPlayingItem}},"data-apple-music-skip-to-next-item":{defaultText:"Next",click:t.skipToNextItem.bind(t),enabled:function(){return!t.queueIsEmpty}},"data-apple-music-seek-forward":{defaultText:"Seek Forward",click:t.seekForward.bind(t),enabled:function(){return!t.queueIsEmpty}},"data-apple-music-seek-backward":{defaultText:"Seek Backward",click:t.seekBackward.bind(t),enabled:function(){return!t.queueIsEmpty}},"data-apple-music-pause":{defaultText:"Pause",click:t.pause.bind(t),display:function(){return t.isPlaying}},"data-apple-music-play":{defaultText:"Play",click:t.play.bind(t),display:function(){return!t.isPlaying},enabled:function(){return!t.queueIsEmpty}},"data-apple-music-set-queue":{click:function(n){var l=n.target.dataset,d=l.appleMusicAutoplay,p=l.appleMusicSetQueue,h=l.appleMusicType;if(isPlayingContainerOrItem(p,t.nowPlayingItem))return t.isPlaying?t.pause():t.play();h||(h=lr.test(p)?"url":/^pl\./i.test(p)?"playlist":"album");var f={};f[h]=p,t.setQueue(f).then((function(){if("false"!==d)return t.play()}))},display:function(n){t.nowPlayingItem&&(isPlayingContainerOrItem(n.dataset.appleMusicSetQueue,t.nowPlayingItem)?n.classList.add(Is):n.classList.remove(Is));return!0}},"data-apple-music-skip-to-previous-item":{defaultText:"Previous",click:t.skipToPreviousItem.bind(t),enabled:function(){return!t.queueIsEmpty}},"data-apple-music-unauthorize":y});n.subscribe(nr.authorizationStatusDidChange,(function(){v.update(["apple-music-authorize","apple-music-unauthorize","data-apple-music-authorize","data-apple-music-unauthorize"])})),n.subscribe(nr.playbackStateDidChange,(function(){v.update(["data-apple-music-pause","data-apple-music-play","data-apple-music-skip-to-next-item","data-apple-music-skip-to-previous-item","data-apple-music-seek-forward","data-apple-music-seek-backward"])})),n.subscribe(nr.nowPlayingItemDidChange,(function(){v.update(["data-apple-music-now-playing","data-apple-music-set-queue"])})),n.subscribe(nr.playbackDurationDidChange,(function(){v.update(["apple-music-current-playback-duration","data-apple-music-current-playback-duration"])})),n.subscribe(nr.playbackProgressDidChange,(function(){v.update(["apple-music-current-playback-progress","data-apple-music-current-playback-progress"])})),n.subscribe(nr.playbackTimeDidChange,(function(){v.update(["apple-music-current-playback-time","apple-music-current-playback-time-remaining","data-apple-music-current-playback-time","data-apple-music-current-playback-time-remaining"])})),n.subscribe(nr.queueItemsDidChange,(function(){v.update(["data-apple-music-pause","data-apple-music-play","data-apple-music-skip-to-next-item","data-apple-music-skip-to-previous-item","data-apple-music-seek-forward","data-apple-music-seek-backward"])}))}(l),[2,l]}}))}))},t.enableMultipleInstances=function(){bs=!0},t.errors=Ys,t.formatArtworkURL=formatArtworkURL,t.formatMediaTime=formatMediaTime,t.formattedMediaURL=formattedMediaURL,t.formattedMilliseconds=function(t){return formattedSeconds(t/1e3)},t.formattedSeconds=formattedSeconds,t.generateEmbedCode=function(t,n){if(void 0===n&&(n={height:"450",width:"660"}),!zs.test(t))throw new Error("Invalid content url");var l=formattedMediaURL(t),d=l.kind,p=l.isUTS;"song"===d?n.height="150":"episode"===d&&(n.height="175"),n.height=(""+n.height).replace(/(\d+)px/i,"$1"),n.width=(""+n.width).replace(/^(\d+)(?!px)%?$/i,"$1px");var h="width:100%;max-width:"+n.width+";overflow:hidden;background:transparent;",f="https://embed.music.apple.com";["podcast","episode"].includes(d)&&!p&&(f="https://embed.podcasts.apple.com");var y=window.localStorage.getItem("mk-generate-swizzle")||f;return'<iframe allow="autoplay *; encrypted-media *;" frameborder="0" height="'+n.height+'" style="'+h+'" sandbox="'+Ws.join(" ")+'" src="'+t.replace(zs,y)+'"></iframe>'},t.getHlsJsCdnConfig=getHlsJsCdnConfig,t.getInstance=function(t){if(0===Ps.length)throw new ke(ke.CONFIGURATION_ERROR,"No configured instance");if(void 0===t)return Ps[Ps.length-1];var n=Ps.find((function(n){return n.id===t}));if(!n)throw new ke("No instance with id "+t+" found");return n},t.getInstances=function(){return Ps},t.getPlayerType=getPlayerType,t.prepareMediaAPIItem=prepareMediaAPIItem,t.resolveCanonical=function(t){return __awaiter$4(this,void 0,void 0,(function(){return __generator$4(this,(function(n){switch(n.label){case 0:return[4,filterLinks(t)];case 1:return[2,{results:{links:n.sent()},meta:{originalUrl:t,originalQueryParams:parseQueryParams(t)}}]}}))}))},t.supportedMediaTypes=yt,t.version="2.2044.10",Object.defineProperty(t,"__esModule",{value:!0})}));
