/** * ios-music-js * Copyright © 2014-2023 Apple Inc. All rights reserved. * Acknowledgements: http://apps.itunes.com/files/ios-music-js/acknowledgements.txt **/ var isArray=Array.isArray;var freeGlobal=typeof global=="object"&&global&&global.Object===Object&&global;var freeSelf=typeof self=="object"&&self&&self.Object===Object&&self;var root=freeGlobal||freeSelf||Function("return this")();var Symbol$1=root.Symbol;var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var nativeObjectToString=objectProto.toString;var symToStringTag=Symbol$1?Symbol$1.toStringTag:undefined;function getRawTag(e){var t=hasOwnProperty.call(e,symToStringTag),r=e[symToStringTag];try{e[symToStringTag]=undefined;var i=true}catch(e){}var n=nativeObjectToString.call(e);if(i){if(t){e[symToStringTag]=r}else{delete e[symToStringTag]}}return n}var objectProto$1=Object.prototype;var nativeObjectToString$1=objectProto$1.toString;function objectToString(e){return nativeObjectToString$1.call(e)}var nullTag="[object Null]",undefinedTag="[object Undefined]";var symToStringTag$1=Symbol$1?Symbol$1.toStringTag:undefined;function baseGetTag(e){if(e==null){return e===undefined?undefinedTag:nullTag}return symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag(e):objectToString(e)}function isObjectLike(e){return e!=null&&typeof e=="object"}var symbolTag="[object Symbol]";function isSymbol(e){return typeof e=="symbol"||isObjectLike(e)&&baseGetTag(e)==symbolTag}var reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/;function isKey(e,t){if(isArray(e)){return false}var r=typeof e;if(r=="number"||r=="symbol"||r=="boolean"||e==null||isSymbol(e)){return true}return reIsPlainProp.test(e)||!reIsDeepProp.test(e)||t!=null&&e in Object(t)}function isObject(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction(e){if(!isObject(e)){return false}var t=baseGetTag(e);return t==funcTag||t==genTag||t==asyncTag||t==proxyTag}var coreJsData=root["__core-js_shared__"];var maskSrcKey=function(){var e=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function isMasked(e){return!!maskSrcKey&&maskSrcKey in e}var funcProto=Function.prototype;var funcToString=funcProto.toString;function toSource(e){if(e!=null){try{return funcToString.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var reRegExpChar=/[\\^$.*+?()[\]{}|]/g;var reIsHostCtor=/^\[object .+?Constructor\]$/;var funcProto$1=Function.prototype,objectProto$2=Object.prototype;var funcToString$1=funcProto$1.toString;var hasOwnProperty$1=objectProto$2.hasOwnProperty;var reIsNative=RegExp("^"+funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function baseIsNative(e){if(!isObject(e)||isMasked(e)){return false}var t=isFunction(e)?reIsNative:reIsHostCtor;return t.test(toSource(e))}function getValue(e,t){return e==null?undefined:e[t]}function getNative(e,t){var r=getValue(e,t);return baseIsNative(r)?r:undefined}var nativeCreate=getNative(Object,"create");function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{};this.size=0}function hashDelete(e){var t=this.has(e)&&delete this.__data__[e];this.size-=t?1:0;return t}var HASH_UNDEFINED="__lodash_hash_undefined__";var objectProto$3=Object.prototype;var hasOwnProperty$2=objectProto$3.hasOwnProperty;function hashGet(e){var t=this.__data__;if(nativeCreate){var r=t[e];return r===HASH_UNDEFINED?undefined:r}return hasOwnProperty$2.call(t,e)?t[e]:undefined}var objectProto$4=Object.prototype;var hasOwnProperty$3=objectProto$4.hasOwnProperty;function hashHas(e){var t=this.__data__;return nativeCreate?t[e]!==undefined:hasOwnProperty$3.call(t,e)}var HASH_UNDEFINED$1="__lodash_hash_undefined__";function hashSet(e,t){var r=this.__data__;this.size+=this.has(e)?0:1;r[e]=nativeCreate&&t===undefined?HASH_UNDEFINED$1:t;return this}function Hash(e){var t=-1,r=e==null?0:e.length;this.clear();while(++t-1}function listCacheSet(e,t){var r=this.__data__,i=assocIndexOf(r,e);if(i<0){++this.size;r.push([e,t])}else{r[i][1]=t}return this}function ListCache(e){var t=-1,r=e==null?0:e.length;this.clear();while(++te(...r))}})}addHandler(e,t,r)}}function removeGlobalCallback(e,t,r){if(e){if(e[t]){removeHandler(e,t,r)}}}var Promise$1=Promise;const timerHandlerMap=new Map;const BAG_TIMEOUT=3e4;function onBagChange(){timerHandlerMap.forEach((e,t)=>{e();t.cancel()});timerHandlerMap.clear();console.log("Bag changed, number of keys in new bag:",Object.keys(Store.bag||{}).length)}class BagError extends Error{static get name(){return"BagError"}}function getFromBag(e,t,r){const i=get(Store.bag,e);if(i!==undefined){t(i)}else{r(new BagError(`${e} not found in bag`))}return i}function getBagValueSync(e,t){return get(Store.bag||{},e,t)}function getBagValue(e){return new Promise$1((t,r)=>{if(Store.bag){getFromBag(e,t,r)}else{const i=new Timer;i.delay=BAG_TIMEOUT;i.onTimeout=()=>{timerHandlerMap.delete(i);r(new BagError("Waiting for bag timed out."))};timerHandlerMap.set(i,()=>{getFromBag(e,t,r)});i.schedule()}})}function registerOnBagChange(e){registerGlobalCallback(Store,"onBagChange",e)}function initializeBag(){registerOnBagChange(onBagChange)}function stackClear(){this.__data__=new ListCache;this.size=0}function stackDelete(e){var t=this.__data__,r=t["delete"](e);this.size=t.size;return r}function stackGet(e){return this.__data__.get(e)}function stackHas(e){return this.__data__.has(e)}var LARGE_ARRAY_SIZE=200;function stackSet(e,t){var r=this.__data__;if(r instanceof ListCache){var i=r.__data__;if(!Map$1||i.length-1&&e%1==0&&e-1&&e%1==0&&e<=MAX_SAFE_INTEGER$1}var argsTag$1="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag$1="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]";var arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]";var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag$1]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag$1]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;function baseIsTypedArray(e){return isObjectLike(e)&&isLength(e.length)&&!!typedArrayTags[baseGetTag(e)]}function baseUnary(e){return function(t){return e(t)}}var freeExports$1=typeof exports=="object"&&exports&&!exports.nodeType&&exports;var freeModule$1=freeExports$1&&typeof module=="object"&&module&&!module.nodeType&&module;var moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1;var freeProcess=moduleExports$1&&freeGlobal.process;var nodeUtil=function(){try{var e=freeModule$1&&freeModule$1.require&&freeModule$1.require("util").types;if(e){return e}return freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}();var nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;var objectProto$7=Object.prototype;var hasOwnProperty$6=objectProto$7.hasOwnProperty;function arrayLikeKeys(e,t){var r=isArray(e),i=!r&&isArguments(e),n=!r&&!i&&isBuffer(e),o=!r&&!i&&!n&&isTypedArray(e),s=r||i||n||o,a=s?baseTimes(e.length,String):[],l=a.length;for(var c in e){if((t||hasOwnProperty$6.call(e,c))&&!(s&&(c=="length"||n&&(c=="offset"||c=="parent")||o&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||isIndex(c,l)))){a.push(c)}}return a}var objectProto$8=Object.prototype;function isPrototype(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||objectProto$8;return e===r}function overArg(e,t){return function(r){return e(t(r))}}var nativeKeys=overArg(Object.keys,Object);var objectProto$9=Object.prototype;var hasOwnProperty$7=objectProto$9.hasOwnProperty;function baseKeys(e){if(!isPrototype(e)){return nativeKeys(e)}var t=[];for(var r in Object(e)){if(hasOwnProperty$7.call(e,r)&&r!="constructor"){t.push(r)}}return t}function isArrayLike(e){return e!=null&&isLength(e.length)&&!isFunction(e)}function keys(e){return isArrayLike(e)?arrayLikeKeys(e):baseKeys(e)}function baseAssign(e,t){return e&©Object(t,keys(t),e)}function nativeKeysIn(e){var t=[];if(e!=null){for(var r in Object(e)){t.push(r)}}return t}var objectProto$a=Object.prototype;var hasOwnProperty$8=objectProto$a.hasOwnProperty;function baseKeysIn(e){if(!isObject(e)){return nativeKeysIn(e)}var t=isPrototype(e),r=[];for(var i in e){if(!(i=="constructor"&&(t||!hasOwnProperty$8.call(e,i)))){r.push(i)}}return r}function keysIn$1(e){return isArrayLike(e)?arrayLikeKeys(e,true):baseKeysIn(e)}function baseAssignIn(e,t){return e&©Object(t,keysIn$1(t),e)}var freeExports$2=typeof exports=="object"&&exports&&!exports.nodeType&&exports;var freeModule$2=freeExports$2&&typeof module=="object"&&module&&!module.nodeType&&module;var moduleExports$2=freeModule$2&&freeModule$2.exports===freeExports$2;var Buffer$1=moduleExports$2?root.Buffer:undefined,allocUnsafe=Buffer$1?Buffer$1.allocUnsafe:undefined;function cloneBuffer(e,t){if(t){return e.slice()}var r=e.length,i=allocUnsafe?allocUnsafe(r):new e.constructor(r);e.copy(i);return i}function copyArray(e,t){var r=-1,i=e.length;t||(t=Array(i));while(++r=200}jsonMergingInXhrMetricsAndExpirationDate(){const e=cloneDeep(this.body);const t=Object.assign({xhrMetrics:this.performanceMetrics,expirationDate:this.expirationDate},e);return Promise$1.resolve(t)}}class ActionError extends Error{constructor(e,t){super(...arguments);this.options=t}static get name(){return"ActionError"}get url(){return get(this,"options.url")}}ActionError.TYPES={GOTO:"Goto",ITEM_NOT_AVAILABLE:"item_not_available",RESET:"Reset"};class RequestError extends Error{constructor(e="",t,r){super(e||RequestError.constructMessage(t,r));this.requestOptions=Object.freeze(cloneDeep(t));this.response=r}static get name(){return"RequestError"}get statusCode(){return get(this,"response.status")}get url(){return get(this,"requestOptions.url")}get method(){return get(this,"requestOptions.method")}static constructMessage(e={},t={}){const{status:r}=t;const{url:i,method:n}=e;let o="";switch(r){case HTTP.STATUS_CODES.CLIENT_TIMEOUT:o=`Request timeout to ${i}.`;break;case HTTP.STATUS_CODES.CLIENT_PARSING_ERROR:o=`Client unable to parse reponse from ${i}.`;break;case 0:o="Network failure";break;default:o=`Received status ${r} from ${n} request to ${i}.`;break}return o}}function fetch(e,t={}){if(!e){return Promise$1.reject(new RequestError("No URL provided for outbound request"))}if(typeof e!=="string"){return Promise$1.reject(new RequestError(`Expected url to be of string type. Got instead: ${typeof e}`))}const{method:r=HTTP.METHOD.GET,headers:i={},body:n,timeout:o=DEFAULT_TIMEOUT,queryItems:s,shouldSuppressResponseDialogs:a,retryCount:l=DEFAULT_RETRY_COUNT,isMusicAPIRequest:c=false,shouldIgnoreCache:u=false,shouldImportResponse:d=true,shouldPrioritizeRequest:g=false}=t;return new Promise$1((t,h)=>{const f={url:e,method:r,headers:i,body:n,timeout:o,queryItems:s,shouldSuppressResponseDialogs:a,retryCount:l,shouldIgnoreCache:u,shouldImportResponse:d,shouldPrioritizeRequest:g};const p=c?MediaKitHTTPRequest:StoreHTTPRequest;const m=Object.assign(new p,f);m.onResponse=e=>{const r=new Response(e);const i=r.body?.dialog;if(r.receivedAnAcceptableStatusCode&&!i){t(r)}else{h(new RequestError("",f,r))}};m.send()})}function fetchJSON(e,t){return fetch(e,t).then(e=>e.jsonMergingInXhrMetricsAndExpirationDate())}class StoreContentRequestError extends Error{constructor(e="",t){super(e||StoreContentRequestError.constructMessage(t));this.requestOptions=Object.freeze(cloneDeep(t))}static get name(){return"StoreContentRequestError"}static constructMessage(e={}){const{identifiers:t=[]}=e;return`Fetching store content for ${t.join(",")} failed.`}}function fetchStoreContent(e){const{ids:t=[],profile:r="lockup",isPersonalized:i=false,caller:n="P6",forceRefresh:o=false}=e;return new Promise((e,s)=>{if(t.length===0){e({})}else{const a={identifiers:t,profile:r,caller:n,timeoutInterval:DEFAULT_TIMEOUT,shouldIgnoreCache:o};if(i&&StoreContentLookupRequest.PERSONALIZATION_STYLE){a.personalizationStyle=StoreContentLookupRequest.PERSONALIZATION_STYLE.ALWAYS}const l=Object.assign(new StoreContentLookupRequest,a);l.onResponse=t=>{if(t&&t.results){e(t.results)}else{s(new StoreContentRequestError("",a))}};l.send()}})}const handlersMap=new Map;function wrapDelay(e){return(...t)=>{const r=new Timer;r.delay=1;r.onTimeout=()=>{e(...t)};r.schedule()}}function registerDelay(e){const t=handlersMap.get(e)||[];let r=t[0];const i=t[1]||0;if(!r){r=wrapDelay(e)}handlersMap.set(e,[r,i+1]);return r}function unregisterDelay(e){const[t,r=0]=handlersMap.get(e)||[];if(r===1){handlersMap.delete(e)}else if(r>1){handlersMap.set(e,[t,r-1])}return t}const timerHandlerMap$1=new Map;const USER_PROFILE_TIMEOUT=3e4;function onUserProfileChange(){timerHandlerMap$1.forEach((e,t)=>{e();t.cancel()});timerHandlerMap$1.clear()}function userDSID(){return get(Store,"account.uniqueIdentifier","")}function isUserSignedIn(){return userDSID()!==""}class UserProfileError extends Error{static get name(){return"UserProfileError"}}function getUserProfile(){function resolveIfUserProfilePresent(e){const t=get(Store,"account.userProfile");if(t){e(t);return true}return false}return new Promise$1((e,t)=>{if(!isUserSignedIn()){e();return}if(resolveIfUserProfilePresent(e)){return}const r=new Timer;r.delay=USER_PROFILE_TIMEOUT;r.onTimeout=()=>{timerHandlerMap$1.delete(r);t(new UserProfileError("Waiting for userProfile timed out."))};timerHandlerMap$1.set(r,()=>{if(!resolveIfUserProfilePresent(e)){const e="No userProfile present after onUserProfileChange called.";t(new UserProfileError(e))}});r.schedule()})}function fetchUsingSameAccountForCloudAndStore(){return new Promise$1(e=>{if(!Store||!Store.account){return e(false)}Store.account.fetchUsingSameAccountForCloudAndStore(e)})}function getFriendsDiscoverySocialProfileIDs(){return getUserProfile().then(()=>get(Store,"account.friendsDiscoverySocialProfileIDs",[]))}function registerOnAccountChange(e){const t=registerDelay(e);registerGlobalCallback(Store,"onAccountChange",t)}function unregisterOnAccountChange(e){const t=unregisterDelay(e);removeGlobalCallback(Store,"onAccountChange",t)}function registerOnUserProfileChange(e){registerGlobalCallback(Store.account,"onUserProfileChange",e)}function unregisterOnUserProfileChange(e){removeGlobalCallback(Store.account,"onUserProfileChange",e)}function initializeUserProfile(){unregisterOnAccountChange(initializeUserProfile);if(Store.account){registerOnUserProfileChange(onUserProfileChange)}else{registerOnAccountChange(initializeUserProfile)}}function getSubscriptionStatus(e,t){return fetchSubscriptionStatus(e,t)}function hasSubscription(e,t=false){return getSubscriptionStatus(e,t).then(e=>e.isSubscribed||e.eligibilityStatus===SubscriptionStatusResponse.ELIGIBILITY_STATUS.ELIGIBLE)}function hasOptedOutOfSubscription(){return CapabilitiesController.hasUserRequestedSubscriptionHidden}function canShowSubscriptionContent(){return CapabilitiesController.canShowSubscriptionContent}function registerOnSubscriptionChange(e){registerGlobalCallback(SubscriptionStatusCoordinator,"onSubscriptionStatusChange",e)}function unregisterOnSubscriptionChange(e){removeGlobalCallback(SubscriptionStatusCoordinator,"onSubscriptionStatusChange",e)}function registerOnHasUserRequestedSubscriptionHiddenChange(e){const t=registerDelay(e);registerGlobalCallback(CapabilitiesController,"onHasUserRequestedSubscriptionHiddenChange",t)}function unregisterOnHasUserRequestedSubscriptionHiddenChange(e){const t=unregisterDelay(e);removeGlobalCallback(CapabilitiesController,"onHasUserRequestedSubscriptionHiddenChange",t)}function registerOnCanShowSubscriptionContentChange(e){const t=registerDelay(e);registerGlobalCallback(CapabilitiesController,"onCanShowSubscriptionContentChange",t)}function hasVoiceAccount(e={}){return e?.accountStatus==="glide"}function hasSubscriptionTier(e={}){let t=e.isSubscribed;if(hasVoiceAccount(e)){t=true}return t}var DEFAULTS={exponential:{maxWait:1500,initialDelay:100,factor:2}};var ExponentialStrategy=function(e,t,r){this.delay=e||DEFAULTS.exponential.initialDelay;this.maxWait=typeof t==="number"?t:DEFAULTS.exponential.maxWait;this.factor=r||DEFAULTS.exponential.factor;this.timeWaited=0};ExponentialStrategy.prototype.nextDelay=function nextDelay(){var e=null;var t=this.maxWait-this.timeWaited;if(t>0){this.delay=Math.min(this.delay,t);this.timeWaited+=this.delay}if(this.maxWait===0||t>0){e=this.delay;this.delay=this.delay*this.factor}return e};var backoff={_backoff:function _backoff(e,t,r,i){var n=function onBackoff(){var n=e.nextDelay();if(n){setTimeout(backoff._backoff.bind(backoff,e,t,r,i),n)}else{i.apply(i,arguments)}};t.call(t,r,n)},exponentialBackoff:function exponentialBackoff(e,t,r,i,n,o){var s=new ExponentialStrategy(i,n,o);backoff._backoff(s,e,t,r)}};var backoff_1=backoff;var config={disabled:function disabled(e){return this.value("disabled",e)?true:false},blacklistedEvents:function blacklistedEvents(e){var t=this.value("blacklistedEvents",e);return t||[]},blacklistedFields:function blacklistedFields(e){var t=this.value("blacklistedFields",e);return t||[]},removeBlacklistedFields:function removeBlacklistedFields(e,t){if(e){var r=config.blacklistedFields.call(this,t);for(var i=0;i-1:false);return r}};var config_1=config;var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function createCommonjsModule(e,t){return t={exports:{}},e(t,t.exports),t.exports}var string={startsWith:function startsWith(e,t,r){var i=false;if(e&&t){e=e.substr(0,t.length);if(r){e=e.toLowerCase();t=t.toLowerCase()}i=e.indexOf(t)===0}return i},endsWith:function endsWith(e,t,r){var i=false;if(e&&t){if(r){e=e.toLowerCase();t=t.toLowerCase()}var n=e.length-t.length;i=n>=0&&e.lastIndexOf(t)===n}return i},trim:function trim(e,t,r){var i=null;var n="\t\n\v\f\r              \u2028\u2029​";var o=new RegExp("^["+n+"]+");var s=new RegExp("["+n+"]+$");if(e){if(!r&&(!t||t==n)&&e.trim){i=e.trim()}else{var a=null;var l=null;var c=null;if(t&&typeof t!=="undefined"){t=t.replace(/([.?*+^$[\]\\(){}-])/g,"\\$1");a="["+t+"]";l=new RegExp("^"+a+"+");c=new RegExp(a+"+$")}else{a=n;l=o;c=s}var u=e.replace(l,"");i=u.replace(c,"")}}return i},snakeCaseToCamelCase:function snakeCaseToCamelCase(e,t){var r="";if(e){var i=e.toLowerCase().split("_");var n;for(var o=0;o=0;n--){var o=i[n];var s=o.indexOf("=");if(s>0){if(s+1==o.length){t=""}else{var a=string_1.trim(o.substring(0,s));if(a==e){t=string_1.trim(o.substring(s+1))}}}}}return t},remove:function remove(e,t){return this.setUnescaped(e,".",this.EXPIRE_NOW,null,t)},_getRaw:function(){var e=this.cookie();if(!reflect_1.isString(e)){e=this.cookieOwnerObject().cookie}var t=e||"";return t}};var cookies_1=cookies;var keyValue={_valueForKeyPath:function(e,t,r){var i=t;if(e&&t){var n=e.split(".");for(var o=0;i&&o1){var r=this.sourcesArray(Array.prototype.slice.call(arguments,1));for(var i=r.length-1;i>=0;i--){var n=r[i];t=this._valueForKeyPath(e,n);if(t){break}}}return t},createObjectAtKeyPath:function(e,t){return this._valueForKeyPath(e,t,true)},sourcesArray:function(e){var t=[];var r=[];r=r.concat(e);if(arguments&&arguments.length>1){r=r.concat(Array.prototype.slice.call(arguments,1))}for(var i=0;i0){_sessions[e]=setTimeout(_clearSession.bind(null,e),r)}i=n}return i},isSampledIn:function isSampledIn(e,t,r,i,n){return t||sampling.sessionSampled(e,r,i)||sampling.lottery(n)}};var sampling_1=sampling;var _storageObject=function _storageObject(e){var t=null;var r=false;return function(){if(!e){if(!r){console.error("storageObject: storage object not found. Override this function if there is a platform-specific implementation");r=true}if(!t){t={storage:{},getItem:function(e){return this.storage[e]},setItem:function(e,t){this.storage[e]=t},removeItem:function(e){delete this.storage[e]}}}}else{t=e}return t}};var storage={localStorageObject:_storageObject(typeof localStorage!="undefined"?localStorage:null),sessionStorageObject:_storageObject(typeof sessionStorage!="undefined"?sessionStorage:null),saveObjectToStorage:function saveObjectToStorage(e,t,r){var i=null;if(r){try{e.setItem(t,JSON.stringify(r));i=r}catch(e){}}else{i=e.removeItem(t)}return i},objectFromStorage:function objectFromStorage(e,t){var r=null;var i=e.getItem(t);if(i){try{r=JSON.parse(i)}catch(e){r=undefined}}return r}};var storage_1=storage;var utils={};utils.backoff=backoff_1;utils.config=config_1;utils.cookies=cookies_1;utils.delegatesInfo=delegates_info;utils.eventFields=event_fields;utils.keyValue=key_value;utils.network=network_1;utils.reflect=reflect_1;utils.sampling=sampling_1;utils.storage=storage_1;utils.string=string_1;utils.optionValueFromStoreFrontHeader=function optionValueFromStoreFrontHeader(e,t){var r=null;var i=typeof e==="string"?e.split(" "):[];var n=utils.string.endsWith(t,":")?t:t+":";for(var o=0;!r&&o=this.MIN_LEVEL&&r<=this.MAX_LEVEL){t=r}return t};Logger.prototype.setLevel=function setLevel(e){var t=this.levelParameterAsInt(e);if(t!==null){this._level=t}};Logger.prototype.setThrowLevel=function setThrowLevel(e){var t=this.levelParameterAsInt(e);if(t!==null){this._throwLevel=t}};Logger.prototype.level=function level(){var level=this._level;return mtMetricskitUtilsPrivate.reflect.isNumber(level)?level:Logger.level()};Logger.prototype.levelString=function levelString(){return this.levelIntToStringMap[this.level()]};Logger.prototype.throwLevel=function throwLevel(){var throwLevel=this._throwLevel;return mtMetricskitUtilsPrivate.reflect.isNumber(throwLevel)?throwLevel:Logger.throwLevel()};Logger.prototype.debug=function debug(){utils_1.execute(this,"debug",arguments)};Logger.prototype.info=function info(){utils_1.execute(this,"info",arguments)};Logger.prototype.warn=function warn(){utils_1.execute(this,"warn",arguments)};Logger.prototype.error=function error(){utils_1.execute(this,"error",arguments)};Logger.prototype.lastLog=function lastLog(e){return this[e]?this[e]._lastLog:null};var logger=Logger;logger.utils=utils_1;var src$1=logger;var mtClientLoggerCore=src$1;var logger$1=mtClientLoggerCore.loggerNamed("mt-client-config");var logger_1=logger$1;var NO_TOPIC_KEY="noTopicConfig";var DEFAULTS$1={blacklistedFields:["capacitySystem","capacitySystemAvailable","capacityDisk","capacityData","capacityDataAvailable"],compoundSeparator:"_",configBaseUrl:"https://xp.apple.com/config/1/report",fieldsMap:{cookies:["itcCt","itscc","xp_ab","xp_abc"],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:"|"};var _configs={};var Config=function Config(e){this._topic=e;this._debugSource=null;this._cachedSource=null;this._serviceSource=null;this._initialized=false;this._showedDebugWarning=false;this._showedNoProvidedSourceWarning=false;this._keyPathsThatSuppressWarning={configBaseUrl:true};this.DEBUG_SOURCE_KEY="mtClientConfig_debugSource"+DEFAULTS$1.compoundSeparator+this._topic;this.CACHED_SOURCE_KEY="mtClientConfig_cachedSource"+DEFAULTS$1.compoundSeparator+this._topic};Config.createConfig=function createConfig(e,t,r,i){e=e||NO_TOPIC_KEY;var n=_configs[e];if(!n){n=new Config(e);_configs[e]=n;if(e!==NO_TOPIC_KEY){n.initialize(t,r,i)}}return n};Config.defaultConfig=function defaultConfig(){return Config.createConfig()};Config.value=function value(e,t){var r=t&&_configs[t]||Config.defaultConfig();return r.value.call(r,e)};Config.environment=environment_1;Config.logger=logger_1;Config.prototype._defaults=function _defaults(){return DEFAULTS$1};Config.prototype._setInitialized=function _setInitialized(e){this._initialized=e};Config.prototype._setShowedDebugWarning=function _setShowedDebugWarning(e){this._showedDebugWarning=e};Config.prototype._setShowedNoProvidedSourceWarning=function _setShowedNoProvidedSourceWarning(e){this._showedNoProvidedSourceWarning=e};Config.prototype.setDelegate=function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)};Config.prototype.topic=function topic(){return this._topic};Config.prototype.configUrl=function configUrl(){var e=this.value("configBaseUrl");if(this._topic!==NO_TOPIC_KEY){e+="/"+this.topic()}else{Config.logger.error("config.configUrl(): Topic must be provided")}return e};Config.prototype.sources=function sources(){};Config.prototype.value=function value(e){var t=this.cachedSource();var r=this.serviceSource();var i=this.sources();var n=this.debugSource();var o=t||r||i||n;var s;if(!i&&!r&&!(e in this._keyPathsThatSuppressWarning)){if(!this._showedNoProvidedSourceWarning){this._showedNoProvidedSourceWarning=true;Config.logger.warn("Metrics config: No config provided via delegate or fetched via init(), using default/cached config values.")}}if(n){if(!this._showedDebugWarning){this._showedDebugWarning=true;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')}}if(!mtMetricskitUtilsPrivate.reflect.isArray(i)){i=[i]}if(e.indexOf("blacklisted")===0){if(o){s=[t,r,i,n]}else{s=[DEFAULTS$1]}}else{s=[DEFAULTS$1,t,r,i,n]}return mtMetricskitUtilsPrivate.keyValue.valueForKeyPath.apply(mtMetricskitUtilsPrivate.keyValue,[e].concat(s))};Config.prototype.setDebugSource=function setDebugSource(e){this._debugSource=e||null;return mtMetricskitUtilsPrivate.storage.saveObjectToStorage(Config.environment.localStorageObject(),this.DEBUG_SOURCE_KEY,this._debugSource)};Config.prototype.debugSource=function debugSource(){if(this._debugSource);else{this._debugSource=mtMetricskitUtilsPrivate.storage.objectFromStorage(Config.environment.localStorageObject(),this.DEBUG_SOURCE_KEY)}return this._debugSource};Config.prototype.setCachedSource=function setCachedSource(e){this._cachedSource=e||null;return mtMetricskitUtilsPrivate.storage.saveObjectToStorage(Config.environment.localStorageObject(),this.CACHED_SOURCE_KEY,this._cachedSource)};Config.prototype.cachedSource=function cachedSource(){if(this._cachedSource);else{this._cachedSource=mtMetricskitUtilsPrivate.storage.objectFromStorage(Config.environment.localStorageObject(),this.CACHED_SOURCE_KEY)}return this._cachedSource};Config.prototype.setServiceSource=function setServiceSource(e){this._serviceSource=e;return this._serviceSource};Config.prototype.serviceSource=function serviceSource(){return this._serviceSource};Config.prototype.fetchConfig=function fetchConfig(e,t,r){r=r||function(){};var i=function onSuccessWrapper(e){var i;try{e=JSON.parse(e);i=true}catch(e){r.call(r,e)}if(i&&t){t.call(t,e)}};mtMetricskitUtilsPrivate.backoff.exponentialBackoff(mtMetricskitUtilsPrivate.network.makeAjaxGetRequest.bind(mtMetricskitUtilsPrivate.network,e),i,r)};Config.prototype.initialize=function initialize(e,t,r){t=t||function(){};var i=function onComplete(){this._initialized=true;t.call(t)}.bind(this);if(e){this.setDelegate({sources:e});i()}else{this.setCachedSource(this.cachedSource());var n=this.configUrl();var o=function onConfigFetched(e){this.setCachedSource(e);this.setServiceSource(e);i()}.bind(this);this.fetchConfig(n,o,r)}};Config.prototype.initialized=function initialized(){return this._initialized};var config$1=Config;var src$2=config$1;var mtClientConfig=src$2;var logger$2=mtClientLoggerCore.loggerNamed("mt-event-queue");var logger_1$1=logger$2;var _isIOS=function _isIOS(){var e=navigator.userAgent;return/iPad|iPhone|iPod/.test(e)&&e.indexOf("IEMobile")==-1};var _eventQueue={DEFAULT_REQUEST_TIMEOUT:1e4,EVENTS_KEY:"events",EVENT_DELIVERY_VERSION:"1.0",EVENT_SEND_METHOD:{AJAX:"ajax",AJAX_SYNCHRONOUS:"ajaxSynchronous",IMAGE:"image"},MAX_PERSISTENT_QUEUE_SIZE:100,RETRY_EXPONENT_BASE:2,URL_DELIVERY_VERSION:2,eventQueues:{},enqueueEvent:function enqueueEvent(e,t){var r=null;if(e&&t){_eventQueue.eventQueues=_eventQueue.eventQueues||{};_eventQueue.eventQueues[e]=_eventQueue.eventQueues[e]||{};_eventQueue.eventQueues[e][_eventQueue.EVENTS_KEY]=_eventQueue.eventQueues[e][_eventQueue.EVENTS_KEY]||[];_eventQueue.eventQueues[e][_eventQueue.EVENTS_KEY].push(t);r=t;var i=mtClientConfig.value("maxPersistentQueueSize",e)||_eventQueue.MAX_PERSISTENT_QUEUE_SIZE;_eventQueue.trimEventQueues(_eventQueue.eventQueues,i)}return r},trimEventQueues:function trimEventQueues(e,t){var r=Object.keys(e);if(r.length){r.forEach((function(r){var i=e[r][_eventQueue.EVENTS_KEY];if(i&&i.length&&i.length>t){logger_1$1.warn("eventQueue overflow, deleting LRU events: size is: "+i.length+" which is over max size: "+t);e[r][_eventQueue.EVENTS_KEY]=i.slice(-t)}}))}},resetTopicQueue:function resetTopicQueue(e){if(_eventQueue.eventQueues[e]){_eventQueue.eventQueues[e][_eventQueue.EVENTS_KEY]=null}},resetTopicRetryAttempts:function resetTopicRetryAttempts(e){if(_eventQueue.eventQueues[e]){_eventQueue.eventQueues[e].retryAttempts=0}},scheduleNextTopicRetryAttempt:function scheduleNextTopicRetryAttempt(e){if(_eventQueue.eventQueues[e]){_eventQueue.eventQueues[e].retryAttempts=_eventQueue.eventQueues[e].retryAttempts||0;_eventQueue.eventQueues[e].retryAttempts++;var t=Math.pow(_eventQueue.RETRY_EXPONENT_BASE,_eventQueue.eventQueues[e].retryAttempts)*mtClientConfig.value("postFrequency",e);_eventQueue.resetTopicPostInterval(e);_eventQueue.setTopicPostInterval(e,t)}},sendEvents:function sendEvents(e,t){for(var r in _eventQueue.eventQueues){_eventQueue.sendEventsForTopic(r,e,t)}},sendEventsForTopic:function sendEventsForTopic(e,t,r){var i=_eventQueue.eventQueues[e];var n=mtClientConfig.value("testExponentialBackoff",e);var o=mtClientConfig.value("metricsUrl",e);var s=mtMetricskitUtilsPrivate.config.disabled.call(mtClientConfig);if(i&&o&&!s&&!n){if(!(i.retryAttempts&&r)){_eventQueue.resetTopicPostInterval(e);_eventQueue.setTopicPostInterval(e,mtClientConfig.value("postFrequency",e));switch(t){case _eventQueue.EVENT_SEND_METHOD.IMAGE:_eventQueue.sendEventsViaImage(e);break;case _eventQueue.EVENT_SEND_METHOD.AJAX_SYNCHRONOUS:_eventQueue.sendEventsViaAjax(e,false);break;case _eventQueue.EVENT_SEND_METHOD.AJAX:default:_eventQueue.sendEventsViaAjax(e,true);break}}}if(n){_eventQueue.scheduleNextTopicRetryAttempt(e)}},sendEventsViaImage:function sendEventsViaImage(e){if(_eventQueue.eventQueues[e]){var t=_eventQueue.metricsUrlForTopic(e);var r=t.indexOf("?")==-1?"?":"&";var i=t+r+"responseType=image";var n=_eventQueue.eventQueues[e][_eventQueue.EVENTS_KEY];if(n&&n.length){n.forEach((function(e){var t=_eventQueue.createQueryParams(e);if(t){var r=i+"&"+t;var n=new Image;n.src=r}}))}_eventQueue.resetTopicQueue(e)}},createQueryParams:function createQueryParams(e){var t;var r;var i="";Object.keys(e).forEach((function(n,o,s){t=e[n];r=mtMetricskitUtilsPrivate.reflect.isString(t)?t:JSON.stringify(t);i+=n+"="+encodeURIComponent(r);if(o=200&&n.status<300||n.status>=400&&n.status<500){r()}else{i()}};n.open("POST",e,t);n.withCredentials=true;n.setRequestHeader("Content-type","application/json");return n},enrichAndSerializeEvents:function enrichAndSerializeEvents(e){var t=null;if(e&&e.length){var r={};r["deliveryVersion"]=_eventQueue.EVENT_DELIVERY_VERSION;r["postTime"]=Date.now();r[_eventQueue.EVENTS_KEY]=e;try{t=JSON.stringify(r)}catch(e){logger_1$1.error("Error stringifying events as JSON: "+e)}}return t},metricsUrlForTopic:function metricsUrlForTopic(e){var t=mtClientConfig.value("metricsUrl",e)+"/"+_eventQueue.URL_DELIVERY_VERSION+"/";return t+e},setTopicPostInterval:function setPostInterval(e,t){if(_eventQueue.eventQueues[e]&&t){_eventQueue.eventQueues[e].postIntervalToken=setInterval((function onPostIntervalTrigger(){logger_1$1.debug("MetricsKit: triggering postIntervalTimer for "+e+" at "+(new Date).toString());_eventQueue.sendEventsForTopic.call(_eventQueue,e)}),t)}},resetTopicPostInterval:function resetPostInterval(e){if(_eventQueue.eventQueues[e]){clearInterval(_eventQueue.eventQueues[e].postIntervalToken);_eventQueue.eventQueues[e].postIntervalToken=null}}};var eventQueue={_utQueue:function _queue(){return _eventQueue},recordEvent:function recordEvent(e,t,r){if(!mtMetricskitUtilsPrivate.config.disabled.call(mtClientConfig)){if(mtClientConfig.value("postFrequency",e)===0){r=true}_eventQueue.enqueueEvent(e,t);if(r){_eventQueue.sendEvents(_eventQueue.EVENT_SEND_METHOD.AJAX,true)}else if(!_eventQueue.eventQueues[e].postIntervalToken){_eventQueue.setTopicPostInterval(e,mtClientConfig.value("postFrequency",e))}}},flushUnreportedEvents:function flushUnreportedEvents(e){if(e){if(_isIOS()){_eventQueue.sendEvents(_eventQueue.EVENT_SEND_METHOD.AJAX_SYNCHRONOUS,true)}else{_eventQueue.sendEvents(_eventQueue.EVENT_SEND_METHOD.IMAGE,true)}}else{_eventQueue.sendEvents(_eventQueue.EVENT_SEND_METHOD.AJAX,true)}}};var event_queue=eventQueue;var eventRecorder={_utResetQueue:function _utResetQueue(){for(var e in event_queue._utQueue().eventQueues){event_queue._utQueue().resetTopicPostInterval(e)}event_queue._utQueue().eventQueues={}},setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},recordEvent:function recordEvent(e,t,r){var i=null;if(t&&!mtMetricskitUtilsPrivate.config.metricsDisabledOrBlacklistedEvent.call(mtClientConfig,t.eventType,e)){mtMetricskitUtilsPrivate.config.removeBlacklistedFields.call(mtClientConfig,t,e);event_queue.recordEvent(e,t,r);i=t}return i},flushUnreportedEvents:function flushUnreportedEvents(e){event_queue.flushUnreportedEvents(e)},sendMethod:function sendMethod(){return"javascript"}};var event_recorder=eventRecorder;var eventQueue$1={eventRecorder:event_recorder,logger:logger_1$1};var src$3=eventQueue$1;var mtEventQueue=src$3;var LOGGER_PROPERTIES$1={mirrorToServerLevel:mtClientLoggerCore.prototype.NONE,topic:""};mtClientLoggerCore.setTopic=function setTopic(e){LOGGER_PROPERTIES$1.topic=e};mtClientLoggerCore.topic=function topic(){return LOGGER_PROPERTIES$1.topic};mtClientLoggerCore.mirrorToServerLevel=function mirrorToServerLevel(){return LOGGER_PROPERTIES$1.mirrorToServerLevel};mtClientLoggerCore.prototype.setTopic=function setTopic(e){this._topic=e};mtClientLoggerCore.prototype.topic=function topic(){var topic=this._topic||mtClientLoggerCore.topic();if(!topic){console.error("LoggerKit: topic must be set in order to mirror log events to the server. Example: loggerKit.setTopic('my_figaro_topic');")}return topic};mtClientLoggerCore.prototype.setMirrorToServerLevel=function setMirrorToServerLevel(e){var t=this.levelParameterAsInt(e);if(t!==null){this._mirrorToServerLevel=t}};mtClientLoggerCore.prototype.mirrorToServerLevel=function mirrorToServerLevel(){var mirrorToServerLevel=this._mirrorToServerLevel;return mtMetricskitUtilsPrivate.reflect.isNumber(mirrorToServerLevel)?mirrorToServerLevel:mtClientLoggerCore.mirrorToServerLevel()};var logger$3=mtClientLoggerCore;mtClientLoggerCore.eventRecorder=mtEventQueue.eventRecorder;var BASE_EVENT_DATA={eventType:"log",eventVersion:"4"};var _createLogEvent=function createLogEvent(e,t,r,i){var n=null;var o=r&&r.length;if(t&&(o||i)){n={};mtMetricskitUtilsPrivate.reflect.extend(n,BASE_EVENT_DATA);n.eventTime=Date.now();n.level=t;n.loggerName=e.loggerName();if(i){n.callstack=i}if(o){try{n.arguments=JSON.stringify(r)}catch(t){e.error("Error stringifying arguments as JSON: "+t)}if(typeof r[0]==="string"){n.message=r[0]}else if(typeof r[0]==="object"&&r.length===1){var s=r[0];n=mtMetricskitUtilsPrivate.reflect.extend({},s,n)}}}else{console.error("LoggerKit: at least one argument or the INCLUDE_CALL_STACK flag is required in order to mirror to server")}return n};var utils$2={sendToServer:function sendToServer(e,t,r,i){var n=e.topic();var o=_createLogEvent(e,t,r,i);var s=null;if(n&&o){s=mtClientLoggerCore.eventRecorder.recordEvent(n,o)}return s}};var utils_1$1=utils$2;logger$3.utils.setDelegate(utils_1$1);var src$4=logger$3;var mtLoggerkit=src$4;const levels={silent:0,error:1,warn:2,info:3,debug:4};const varMap=new WeakMap;function setInternalValues(e,t){if(!varMap.has(e)){varMap.set(e,{})}const r=varMap.get(e);Object.assign(r,t)}function getInternalValue(e,t){const r=varMap.get(e)||{};return r[t]}function setGatedMethod(e,t,r){const i={[t](...i){if(e.level>=levels[t]){r(...i)}}};setInternalValues(e,i)}function createDefaults(){const e={level:0};if(console){["log","dir","debug","info","warn","error"].forEach(t=>{const r=console[t];if(typeof r==="function"){e[t]=console[t].bind(console)}})}return e}class Logger$1{constructor(e){Object.assign(this,createDefaults(),e)}get error(){return getInternalValue(this,"error")}set error(e){setGatedMethod(this,"error",e)}get warn(){return getInternalValue(this,"warn")}set warn(e){setGatedMethod(this,"warn",e)}get info(){return getInternalValue(this,"info")}set info(e){setGatedMethod(this,"info",e)}get debug(){return getInternalValue(this,"debug")}set debug(e){setGatedMethod(this,"debug",e)}get log(){return getInternalValue(this,"log")}set log(e){setInternalValues(this,{log:e})}get dir(){return getInternalValue(this,"dir")}set dir(e){setInternalValues(this,{dir:e})}}Logger$1.prototype.LEVELS=Object.freeze(levels);var compareVersion=function(e,t){var r;var i;if(typeof e+typeof t!=="stringstring"){return false}e=e.split(".");t=t.split(".");r=0;i=Math.max(e.length,t.length);for(;r0||parseInt(e[r])>parseInt(t[r])){return 1}else if(t[r]&&!e[r]&&parseInt(t[r])>0||parseInt(e[r])0&&r(a)){if(t>1){baseFlatten(a,t-1,r,i,n)}else{arrayPush(n,a)}}else if(!i){n[n.length]=a}}return n}function flatten(e){var t=e==null?0:e.length;return t?baseFlatten(e,1):[]}function baseSlice(e,t,r){var i=-1,n=e.length;if(t<0){t=-t>n?0:n+t}r=r>n?n:r;if(r<0){r+=n}n=t>r?0:r-t>>>0;t>>>=0;var o=Array(n);while(++i=i?e:baseSlice(e,t,r)}var rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsVarRange="\\ufe0e\\ufe0f";var rsZWJ="\\u200d";var reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]");function hasUnicode(e){return reHasUnicode.test(e)}function asciiToArray(e){return e.split("")}var rsAstralRange$1="\\ud800-\\udfff",rsComboMarksRange$1="\\u0300-\\u036f",reComboHalfMarksRange$1="\\ufe20-\\ufe2f",rsComboSymbolsRange$1="\\u20d0-\\u20ff",rsComboRange$1=rsComboMarksRange$1+reComboHalfMarksRange$1+rsComboSymbolsRange$1,rsVarRange$1="\\ufe0e\\ufe0f";var rsAstral="["+rsAstralRange$1+"]",rsCombo="["+rsComboRange$1+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange$1+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsZWJ$1="\\u200d";var reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange$1+"]?",rsOptJoin="(?:"+rsZWJ$1+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")";var reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g");function unicodeToArray(e){return e.match(reUnicode)||[]}function stringToArray(e){return hasUnicode(e)?unicodeToArray(e):asciiToArray(e)}function createCaseFirst(e){return function(t){t=toString(t);var r=hasUnicode(t)?stringToArray(t):undefined;var i=r?r[0]:t.charAt(0);var n=r?castSlice(r,1).join(""):t.slice(1);return i[e]()+n}}var upperFirst=createCaseFirst("toUpperCase");function baseSet(e,t,r,i){if(!isObject(e)){return e}t=castPath(t,e);var n=-1,o=t.length,s=o-1,a=e;while(a!=null&&++n{const e=get(Device.systemVersion.split("."),"[0]");if(!e&&!hasLoggedMajorVersionWarning){logger$5.warn(`There was a problem retrieving the major version. Device.systemVersion: '${Device.systemVersion}' This warning is logged once.`);hasLoggedMajorVersionWarning=true;return null}return e};Device;function createCookie(e,t,r={}){const i=new Cookie;i.name=e;if(t){i.value=t}Object.assign(i,{domain:"apple.com",path:"/"},r);return i}function setCookie(e,t,r={}){return new Promise$1(i=>{const n=createCookie(e,t,r);Persistence.cookieStorage.setCookie(n,()=>{i(n)})})}function deleteCookie(e,t={}){return new Promise$1(r=>{const i=createCookie(e,undefined,t);Persistence.cookieStorage.deleteCookie(i,r)})}function getCookieString(){const e=Persistence.cookieStorage.activeCookiesForDefaultURL||{};return Object.keys(e).reduce((t,r)=>{const i=encodeURIComponent(e[r].value);t.push(`${r}=${i}`);return t},[]).join("; ")}const config$2={version:"2336.1.0-v7",localizationResourceForLocale:{ar:"localization/ar.json","ar-sa":"localization/ar-sa.json",ca:"localization/ca.json","ca-es":"localization/ca-es.json",cs:"localization/cs.json","cs-cz":"localization/cs-cz.json",da:"localization/da.json","da-dk":"localization/da-dk.json",de:"localization/de.json","de-ch":"localization/de-ch.json","de-de":"localization/de-de.json",el:"localization/el.json","el-gr":"localization/el-gr.json",en:"localization/en.json","en-au":"localization/en-au.json","en-ca":"localization/en-ca.json","en-gb":"localization/en-gb.json","en-us":"localization/en-us.json",es:"localization/es.json","es-419":"localization/es-419.json","es-es":"localization/es-es.json","es-mx":"localization/es-mx.json","es-xl":"localization/es-xl.json","et-ee":"localization/et-ee.json",fi:"localization/fi.json","fi-fi":"localization/fi-fi.json",fr:"localization/fr.json","fr-ca":"localization/fr-ca.json","fr-fr":"localization/fr-fr.json",he:"localization/he.json",hi:"localization/hi.json","hi-in":"localization/hi-in.json",hr:"localization/hr.json","hr-hr":"localization/hr-hr.json",hu:"localization/hu.json","hu-hu":"localization/hu-hu.json",id:"localization/id.json","id-id":"localization/id-id.json",is:"localization/is.json","is-is":"localization/is-is.json",it:"localization/it.json","it-it":"localization/it-it.json",ja:"localization/ja.json","ja-jp":"localization/ja-jp.json",ko:"localization/ko.json","ko-kr":"localization/ko-kr.json",lt:"localization/lt.json","lt-lt":"localization/lt-lt.json",lv:"localization/lv.json","lv-lv":"localization/lv-lv.json",ms:"localization/ms.json","ms-my":"localization/ms-my.json",nb:"localization/nb.json","nb-no":"localization/nb-no.json",nl:"localization/nl.json","nl-nl":"localization/nl-nl.json",no:"localization/no.json","no-nb":"localization/no-nb.json","no-no":"localization/no-no.json",pl:"localization/pl.json","pl-pl":"localization/pl-pl.json",pt:"localization/pt.json","pt-br":"localization/pt-br.json","pt-pt":"localization/pt-pt.json",ro:"localization/ro.json","ro-ro":"localization/ro-ro.json",ru:"localization/ru.json","ru-ru":"localization/ru-ru.json",sk:"localization/sk.json","sk-sk":"localization/sk-sk.json",sv:"localization/sv.json","sv-se":"localization/sv-se.json",th:"localization/th.json","th-th":"localization/th-th.json",tr:"localization/tr.json","tr-tr":"localization/tr-tr.json",uk:"localization/uk.json","uk-ua":"localization/uk-ua.json",vi:"localization/vi.json","vi-vi":"localization/vi-vi.json","vi-vn":"localization/vi-vn.json",zh:"localization/zh.json","zh-hans-cn":"localization/zh-hans-cn.json","zh-hant-hk":"localization/zh-hant-hk.json","zh-hant-tw":"localization/zh-hant-tw.json"},resourceManifest:{resources:{"localization/ar-sa.json":"resources/localization/568152e91e4e9ee2532f531035e99a9f/ar-sa.json","localization/ar.json":"resources/localization/568152e91e4e9ee2532f531035e99a9f/ar.json","localization/ca-es.json":"resources/localization/5a35ebef4f4e22a30d68967eb6f21a16/ca-es.json","localization/ca.json":"resources/localization/5a35ebef4f4e22a30d68967eb6f21a16/ca.json","localization/cs-cz.json":"resources/localization/0ae561d5c767e7f75a682e20985bf101/cs-cz.json","localization/cs.json":"resources/localization/0ae561d5c767e7f75a682e20985bf101/cs.json","localization/da-dk.json":"resources/localization/670b78c7931c2806ffde165ea667dd98/da-dk.json","localization/da.json":"resources/localization/670b78c7931c2806ffde165ea667dd98/da.json","localization/de-ch.json":"resources/localization/bb1228d22ddab9b401c8326985e9ae17/de-ch.json","localization/de-de.json":"resources/localization/4de91016f8246710019a8f12300f4512/de-de.json","localization/de.json":"resources/localization/4de91016f8246710019a8f12300f4512/de.json","localization/dev.json":"resources/localization/b380994a6d518bc36d7b653dcb4fcf2e/dev.json","localization/el-gr.json":"resources/localization/f8ef1e23889ff97e0b797e73b08efe01/el-gr.json","localization/el.json":"resources/localization/f8ef1e23889ff97e0b797e73b08efe01/el.json","localization/en-au.json":"resources/localization/4e53ca572917df297973d014dcb8f96e/en-au.json","localization/en-ca.json":"resources/localization/cc48961f131526f6784a4557457f4e6a/en-ca.json","localization/en-gb.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/en-gb.json","localization/en-us.json":"resources/localization/322d68c286f8ba7b6e1637ee3bf1de79/en-us.json","localization/es-419.json":"resources/localization/3d28a95544d3f196fbdca3b1246b1ccf/es-419.json","localization/en.json":"resources/localization/322d68c286f8ba7b6e1637ee3bf1de79/en.json","localization/es-es.json":"resources/localization/3d28a95544d3f196fbdca3b1246b1ccf/es-es.json","localization/es-mx.json":"resources/localization/1d766a2ed90eaf1af7ec9374c5251182/es-mx.json","localization/es-xl.json":"resources/localization/1d766a2ed90eaf1af7ec9374c5251182/es-xl.json","localization/es.json":"resources/localization/3d28a95544d3f196fbdca3b1246b1ccf/es.json","localization/et-ee.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/et-ee.json","localization/fi-fi.json":"resources/localization/19b2030de85cb7bc21bf4d0552693107/fi-fi.json","localization/fi.json":"resources/localization/19b2030de85cb7bc21bf4d0552693107/fi.json","localization/fr-fr.json":"resources/localization/acb2cf1e0ea2bd63c9e5efde008b74ee/fr-fr.json","localization/fr-ca.json":"resources/localization/155451b1ae2e2d1c96b3914920867247/fr-ca.json","localization/fr.json":"resources/localization/acb2cf1e0ea2bd63c9e5efde008b74ee/fr.json","localization/he.json":"resources/localization/1438fd2aa67f599a83f936dd229b8d12/he.json","localization/hi-in.json":"resources/localization/64ffde877250b09890fb078f3d6affb8/hi-in.json","localization/hi.json":"resources/localization/64ffde877250b09890fb078f3d6affb8/hi.json","localization/hr-hr.json":"resources/localization/051cb0c7ad4e399996bee4893ee8ed5b/hr-hr.json","localization/hr.json":"resources/localization/051cb0c7ad4e399996bee4893ee8ed5b/hr.json","localization/hu-hu.json":"resources/localization/3b5d6bda2b0bc2d20d3ea0e76775c9bf/hu-hu.json","localization/hu.json":"resources/localization/3b5d6bda2b0bc2d20d3ea0e76775c9bf/hu.json","localization/id-id.json":"resources/localization/606385bfa94de2e6f2c230a55e598ee6/id-id.json","localization/id.json":"resources/localization/606385bfa94de2e6f2c230a55e598ee6/id.json","localization/is-is.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/is-is.json","localization/is.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/is.json","localization/it-it.json":"resources/localization/9bfd62e3f321ea82e8df92d0ff444d0e/it-it.json","localization/it.json":"resources/localization/9bfd62e3f321ea82e8df92d0ff444d0e/it.json","localization/ja-jp.json":"resources/localization/68588d3006bec8598fea2c4f1e9d0b35/ja-jp.json","localization/ja.json":"resources/localization/68588d3006bec8598fea2c4f1e9d0b35/ja.json","localization/ko-kr.json":"resources/localization/6a22890ba0f7f9388949f35599c5b4a0/ko-kr.json","localization/ko.json":"resources/localization/6a22890ba0f7f9388949f35599c5b4a0/ko.json","localization/lt-lt.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/lt-lt.json","localization/lt.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/lt.json","localization/lv-lv.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/lv-lv.json","localization/lv.json":"resources/localization/a441827b38e7d39fb91626d83e13814b/lv.json","localization/ms-my.json":"resources/localization/41ecd4bb998f6076380f1cf203088ddb/ms-my.json","localization/ms.json":"resources/localization/41ecd4bb998f6076380f1cf203088ddb/ms.json","localization/nb-no.json":"resources/localization/f63c6daf953addce1a0a3c39f2291bf3/nb-no.json","localization/nb.json":"resources/localization/f63c6daf953addce1a0a3c39f2291bf3/nb.json","localization/nl-nl.json":"resources/localization/5b664f27833a82180cc2ac197bd09619/nl-nl.json","localization/nl.json":"resources/localization/5b664f27833a82180cc2ac197bd09619/nl.json","localization/no-nb.json":"resources/localization/f63c6daf953addce1a0a3c39f2291bf3/no-nb.json","localization/no-no.json":"resources/localization/f63c6daf953addce1a0a3c39f2291bf3/no-no.json","localization/no.json":"resources/localization/f63c6daf953addce1a0a3c39f2291bf3/no.json","localization/pl-pl.json":"resources/localization/46fd03a50b583cabb55cbc75008aaebe/pl-pl.json","localization/pl.json":"resources/localization/46fd03a50b583cabb55cbc75008aaebe/pl.json","localization/pt-br.json":"resources/localization/4a9436d764c39590a40d5bf31a6dda3c/pt-br.json","localization/pt-pt.json":"resources/localization/52f02324d7f8ac4607ec1cd0d13d4a69/pt-pt.json","localization/pt.json":"resources/localization/52f02324d7f8ac4607ec1cd0d13d4a69/pt.json","localization/ro-ro.json":"resources/localization/cc3d254ce99ad7190d2c94e91dd30f48/ro-ro.json","localization/ro.json":"resources/localization/cc3d254ce99ad7190d2c94e91dd30f48/ro.json","localization/ru-ru.json":"resources/localization/d7fa3494a5c53d9ef2e38eaf88672b18/ru-ru.json","localization/ru.json":"resources/localization/d7fa3494a5c53d9ef2e38eaf88672b18/ru.json","localization/sk-sk.json":"resources/localization/10bdfc8523b04764ad92404945fa5879/sk-sk.json","localization/sk.json":"resources/localization/10bdfc8523b04764ad92404945fa5879/sk.json","localization/sv-se.json":"resources/localization/2bafc0c548d4e2c6688bada3f6853470/sv-se.json","localization/sv.json":"resources/localization/2bafc0c548d4e2c6688bada3f6853470/sv.json","localization/th-th.json":"resources/localization/1174cbb88b60996adb1ec3d17c05f4c7/th-th.json","localization/th.json":"resources/localization/1174cbb88b60996adb1ec3d17c05f4c7/th.json","localization/tr-tr.json":"resources/localization/935350ea6076793d755528bc282125a6/tr-tr.json","localization/tr.json":"resources/localization/935350ea6076793d755528bc282125a6/tr.json","localization/uk-ua.json":"resources/localization/587a2c91cd797c5115a8a51fea2ce329/uk-ua.json","localization/uk.json":"resources/localization/587a2c91cd797c5115a8a51fea2ce329/uk.json","localization/vi-vi.json":"resources/localization/bd26cb5612a719f91897d2ada71e4d4a/vi-vi.json","localization/vi-vn.json":"resources/localization/bd26cb5612a719f91897d2ada71e4d4a/vi-vn.json","localization/vi.json":"resources/localization/bd26cb5612a719f91897d2ada71e4d4a/vi.json","localization/zh-hans-cn.json":"resources/localization/f5b4a91c51662707512bf8b5b2eb66d9/zh-hans-cn.json","localization/zh-hant-hk.json":"resources/localization/62a26c7af03e5fd114e6e8376be15290/zh-hant-hk.json","localization/zh-hant-tw.json":"resources/localization/91390cd067ace36d4ea1b3727ab03f98/zh-hant-tw.json","localization/zh.json":"resources/localization/f5b4a91c51662707512bf8b5b2eb66d9/zh.json"},version:"2336.1.0-v7"},localizableStringsStorefrontOverrides:{"FUSE.Upsell.Onboard.Description":{USA:"FUSE.Upsell.Onboard.Description.Alternate"},"FUSE.Upsell.Onboard.Header":{USA:"FUSE.Upsell.Onboard.Header.Alternate"},"FUSE.UpsellBanner.Subscribe.Long.PXMY":{BRA:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",CHE:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",CHL:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",COL:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",CZE:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",DNK:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",GRC:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",HKG:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",HUN:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",IDN:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",ISR:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",KAZ:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",MYS:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",PER:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",POL:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",ROU:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",TUR:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",TWN:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",UKR:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",VNM:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration",ZAF:"FUSE.UpsellBanner.Subscribe.Long.PXMY.WithoutDuration"},"FUSE.UpsellBanner.Subscribe.Short.PXMY":{BRA:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",CHE:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",CHL:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",COL:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",CZE:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",DNK:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",GRC:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",HKG:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",HUN:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",IDN:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",ISR:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",KAZ:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",MYS:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",PER:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",POL:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",ROU:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",TUR:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",TWN:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",UKR:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",VNM:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration",ZAF:"FUSE.UpsellBanner.Subscribe.Short.PXMY.WithoutDuration"}}};var config$3=Object.freeze(config$2);function noop(){}function deResNumber(e){let t;if(typeof e==="number"){t=Math.floor(Math.floor(e/1024/1024)/100)*100}return t}function app(){return Application.identifier}function appVersion(){return Application.version}function capacityData(){return deResNumber(get(Device,"diskUsage.totalDataCapacity"))}function capacityDataAvailable(){return deResNumber(get(Device,"diskUsage.totalDataAvailable"))}function capacitySystem(){return deResNumber(get(Device,"diskUsage.totalSystemCapacity"))}function capacitySystemAvailable(){return deResNumber(get(Device,"diskUsage.totalSystemAvailable"))}function capacityDisk(){return deResNumber(get(Device,"diskUsage.totalDiskCapacity"))}function connectionType(){return Network.connectionTypeHeader}function dsId(){return userDSID()||undefined}function osVersion(){return Device.systemVersion}function pixelRatio(){return get(Device,"mainScreen.scale")}function resourceRevNum(){return config$3.version}function screenHeight(){return get(Device,"mainScreen.size.height")}function screenWidth(){return get(Device,"mainScreen.size.width")}function storeFrontHeader(){return Store.storeFrontIdentifier}function localStorageObject(){return Persistence.localStorage}function userAgent(){return Device.userAgent}function windowInnerHeight(){return get(Device,"mainScreen.mainWindow.size.height")}function windowInnerWidth(){return get(Device,"mainScreen.mainWindow.size.width")}var environment$1={app:app,appVersion:appVersion,capacityData:capacityData,capacityDataAvailable:capacityDataAvailable,capacitySystem:capacitySystem,capacitySystemAvailable:capacitySystemAvailable,capacityDisk:capacityDisk,connectionType:connectionType,cookie:getCookieString,dsId:dsId,hostApp:noop,osVersion:osVersion,pixelRatio:pixelRatio,pageUrl:noop,resourceRevNum:resourceRevNum,screenHeight:screenHeight,screenWidth:screenWidth,storeFrontHeader:storeFrontHeader,localStorageObject:localStorageObject,userAgent:userAgent,windowInnerHeight:windowInnerHeight,windowInnerWidth:windowInnerWidth,windowOuterHeight:windowInnerHeight,windowOuterWidth:windowInnerWidth};var info={version:"6.3.0",name:"mt-metricskit"};var delegateInfo={mtName:function(){return info.name},mtVersion:function(){return info.version}};var delegateExtension={attachDelegateInfo:function(e){mtMetricskitUtilsPrivate.reflect.extend(e,delegateInfo)}};var delegate_extension=delegateExtension;var logger$4=mtLoggerkit.loggerNamed("mt-metricskit");var logger_1$2=logger$4;var exceptionStringTemplate=["The function metrics.system.environment.","placeholder","() must be overridden with a platform-specific delegate function. If you have no data for this field, have your delegate return null or undefined (no 'return')"];var environment$2={setDelegate:function setDelegate(e){mtMetricskitUtilsPrivate.cookies.setDelegate(e);return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},app:function app(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},appVersion:function appVersion(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},capacityData:function capacityData(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},capacityDataAvailable:function capacityDataAvailable(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},capacityDisk:function capacityDisk(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},capacitySystem:function capacitySystem(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},capacitySystemAvailable:function capacitySystemAvailable(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},connectionType:function connectionType(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},cookieOwnerObject:function cookieOwnerObject(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},dsId:function dsId(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},environmentBuild:function environmentBuild(){},environmentDataCenter:function environmentDataCenter(){},environmentInstance:function environmentInstance(){},hostApp:function hostApp(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},hostAppVersion:function hostAppVersion(){},osLanguages:function osLanguages(){},osVersion:function osVersion(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},pageUrl:function pageUrl(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},pixelRatio:function pixelRatio(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},resourceRevNum:function resourceRevNum(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},screenHeight:function screenHeight(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},screenWidth:function screenWidth(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},storeFrontHeader:function storeFrontHeader(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},userAgent:function userAgent(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},userType:function userType(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},windowInnerHeight:function windowInnerHeight(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},windowInnerWidth:function windowInnerWidth(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},windowOuterHeight:function windowOuterHeight(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},windowOuterWidth:function windowOuterWidth(){exceptionStringTemplate[1]=mtMetricskitUtilsPrivate.reflect.functionName();throw exceptionStringTemplate.join("")},localStorageObject:mtMetricskitUtilsPrivate.storage.localStorageObject,sessionStorageObject:mtMetricskitUtilsPrivate.storage.sessionStorageObject};var environment_1$1=environment$2;mtClientConfig.environment.setDelegate(environment_1$1);mtClientConfig.logger.setDelegate(logger_1$2);mtMetricskitUtilsPrivate.reflect.attachMethods(mtClientConfig,mtMetricskitUtilsPrivate.config,mtClientConfig);var _topic;var config$4={topic:function topic(){return _topic},setTopic:function setTopic(e){_topic=e}};var config_1$1=config$4;var dedupeSiblingImpressions=function(e){var t={};var r=[];var i;if(e&&e[0]&&e[0].index!==undefined){for(var n=0;n0){o=this.flattenImpressions(i.children,a);r=r.concat(o);a+=o.length}}}}else{logger_1$2.warn("Fuse-Metrics: No impressions provided to to flattenImpressions")}return r},buildLocationStructure:function(e){var t=e;var r;var i=[];var n;var o;var s;var a;var l;while(t){n={};l=0;r=t.parentNode;if(t.hasAttribute&&t.hasAttribute("data-metrics-location")){n=JSON.parse(t.getAttribute("data-metrics-location"));if(n.locationType){if(r){o=r.childNodes;for(var c=0;c=5){pageHistoryCache.shift()}pageHistoryCache.push(r)}}return t}};var page_1=page;var buyConfirmed={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r){return base_1.processMetricsData.apply(this,arguments)},knownFields:function knownFields(){var knownFields=["eventType","eventVersion"];return knownFields},eventType:function(e){return"buyConfirmed"},eventVersion:function(e){return 1},createClientBuyId:function(){var e=null;var t=environment_1$1.sessionStorageObject().getItem("mtMetricsKit_previousClientBuyId");e=++t;if(!t){logger_1$2.warn("Metrics: buyConfirmed.createClientBuyId: clientBuyId did not exist or was of incorrect type, reset to 1.");e=1}environment_1$1.sessionStorageObject().setItem("mtMetricsKit_previousClientBuyId",e);return e},clientBuyIdQueryParamString:function(e){return"&clientBuyId="+e},metricsBuyParamsString:function(e,t,r,i){var n=page_1.pageHistory();var o=base_1.clientId();var s;if(Array.isArray(n)){if(n.length>=2){s=n[n.length-2]}}else{logger_1$2.warn("MetricsKit: metricsBuyParamsString: pageHistory is not an Array")}return mtMetricskitUtilsPrivate.string.paramString({mtApp:base_1.app(),mtEventTime:Date.now(),mtHostApp:base_1.hostApp(),mtHostAppVersion:base_1.hostAppVersion(),mtPageId:e,mtPageType:t,mtPageContext:r,mtTopic:i||"xp_its_main",mtPrevPage:s,mtRequestId:mtMetricskitUtilsPrivate.string.requestId(o),mtClientId:o})},cacheMetricsBuyData:function(e,t){if(arguments.length!=2){logger_1$2.error("buyConfirmed.cacheMetricsBuyData(): function invoked with incorrect number of parameters. Perhaps you meant to retrieve cached data instead of setting it, which would be a call to uncacheMetricsBuyData(clientBuyId)?")}else{var r=JSON.stringify(t);environment_1$1.sessionStorageObject().setItem("mtMetricsKit_metricsBuyData_for_clientBuyId_"+e,r)}},uncacheMetricsBuyData:function(e){var t=null;if(arguments.length!=1){logger_1$2.error("buyConfirmed.uncacheMetricsBuyData(): function invoked with incorrect number of parameters. Perhaps you meant to set cached data instead of retrieving it, which would be a call to cacheMetricsBuyData(clientBuyId, metricsBuyData)?")}else{var r=environment_1$1.sessionStorageObject().getItem("mtMetricsKit_metricsBuyData_for_clientBuyId_"+e);if(r){t=JSON.parse(r);environment_1$1.sessionStorageObject().removeItem("mtMetricsKit_metricsBuyData_for_clientBuyId_"+e)}}return t},buyFailureOccurred:function(e){var t=this.uncacheMetricsBuyData(e);if(t){t.detoured=true;this.cacheMetricsBuyData(e,t)}}};var buy_confirmed=buyConfirmed;var click={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r,i){var n=[e,t,r];if(i){n.push({location:utils_1$2.eventFields.buildLocationStructure(i)});n.push(click.dataForElement(i)||{})}n=n.concat(Array.prototype.slice.call(arguments,4));return base_1.processMetricsData.apply(this,n)},knownFields:function knownFields(){var knownFields=["actionContext","actionDetails","actionType","actionUrl","eventType","eventVersion","impressions","location","targetId","targetType","positionX","positionY","xpViewablePercentage"];return knownFields},dataForElement:function dataForElement(e){var t=null;if(e&&mtMetricskitUtilsPrivate.reflect.isFunction(e.hasAttribute)&&mtMetricskitUtilsPrivate.reflect.isFunction(e.getAttribute)){var r=click.dataAttribute();if(e.hasAttribute(r)){try{t=JSON.parse(e.getAttribute(r))}catch(e){logger_1$2.error("MetricsKit: error parsing click data - "+e)}}}return t},dataAttribute:function dataAttribute(){return"data-metrics-click"},eventType:function(e){return"click"},eventVersion:function(e){return 4},impressions:function impressions(e){return e?e.impressions:undefined},xpViewablePercentage:function xpViewablePercentage(e){return base_1.xpViewablePercentage(e)}};var click_1=click;var dialog={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r){return base_1.processMetricsData.apply(this,arguments)},knownFields:function knownFields(){var knownFields=["buttons","code","details","message","type","eventType","eventVersion","type"];return knownFields},eventType:function(e){return"dialog"},eventVersion:function(e){return 2}};var dialog_1=dialog;var environment$4=system_1.environment;var enter={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r){return base_1.processMetricsData.apply(this,arguments)},knownFields:function knownFields(){var knownFields=["eventType","eventVersion","extRefUrl","osLanguages","refApp","type"];return knownFields},eventType:function(e){return"enter"},eventVersion:function(e){return 1},osLanguages:function osLanguages(e){return e&&e.osLanguages||environment$4.osLanguages()}};var enter_1=enter;var exit={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r){return base_1.processMetricsData.apply(this,arguments)},knownFields:function knownFields(){var knownFields=["destinationUrl","eventType","eventVersion","type"];return knownFields},eventType:function(e){return"exit"},eventVersion:function(e){return 1}};var exit_1=exit;var flexible={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e){var t=[undefined,undefined,undefined];t.push({eventType:e});var r=Array.prototype.slice.call(arguments,1);t=t.concat(r);return base_1.processMetricsData.apply(this,t)},knownFields:function knownFields(){var knownFields=["eventTime","eventType"];return knownFields},mtIncludeBaseFields:function mtIncludeBaseFields(){return false},eventTime:function eventTime(e){return e&&e.eventTime||Date.now()},eventType:function(e){return e&&e.eventType||undefined}};var flexible_1=flexible;var impressions={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r){return base_1.processMetricsData.apply(this,arguments)},knownFields:function knownFields(){var knownFields=["eventType","eventVersion","impressions","xpViewablePercentage","xpViewableThreshold"];return knownFields},eventType:function(e){return"impressions"},eventVersion:function(e){return 3},impressions:function impressions(e){return e?e.impressions:undefined},xpViewablePercentage:function xpViewablePercentage(e){return base_1.xpViewablePercentage(e)},xpViewableThreshold:function xpViewableThreshold(e){return e&&e.xpViewableThreshold||mtClientConfig.value("viewableThreshold",config_1$1.topic())}};var impressions_1=impressions;var media={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r){return base_1.processMetricsData.apply(this,arguments)},knownFields:function knownFields(){var knownFields=["eventType","id","idType","type","typeDetails","actionType","actionDetails","url","duration","position"];return knownFields},eventType:function(e){return"media"},eventVersion:function(e){return 1}};var media_1=media;var search={setDelegate:function setDelegate(e){return mtMetricskitUtilsPrivate.reflect.attachDelegate(this,e)},metricsData:function(e,t,r){return base_1.processMetricsData.apply(this,arguments)},knownFields:function knownFields(){var knownFields=["actionDetails","actionType","actionUrl","eventType","eventVersion","filters","location","targetId","targetType","term"];return knownFields},eventType:function(e){return"search"},eventVersion:function(e){return 2}};var search_1=search;var eventHandlers={};eventHandlers.account=account_1;eventHandlers.base=base_1;eventHandlers.buyConfirmed=buy_confirmed;eventHandlers.click=click_1;eventHandlers.dialog=dialog_1;eventHandlers.enter=enter_1;eventHandlers.exit=exit_1;eventHandlers.flexible=flexible_1;eventHandlers.impressions=impressions_1;eventHandlers.media=media_1;eventHandlers.page=page_1;eventHandlers.search=search_1;for(var key$1 in eventHandlers){delegate_extension.attachDelegateInfo(eventHandlers[key$1])}var event_handlers=eventHandlers;var _initCalled;var _initializeConfig=function _initializeConfig(){mtMetricskitUtilsPrivate.reflect.attachMethods(metrics.config,mtMetricskitUtilsPrivate.config,metrics.config);delegate_extension.attachDelegateInfo(metrics.config)};var metrics={_utSetInitCalled:function _setInitCalled(e){_initCalled=e},system:system_1,config:mtClientConfig.defaultConfig(),eventHandlers:event_handlers,utils:utils_1$2,init:function init(e,t,r,i,n){if(!_initCalled){_initCalled=true;if(r){mtMetricskitUtilsPrivate.reflect.setDelegates(event_handlers,r);mtMetricskitUtilsPrivate.reflect.setDelegates(system_1,r)}config_1$1.setTopic(e);metrics.config=mtClientConfig.createConfig(e,t,i,n);_initializeConfig();metrics.system.configSources=metrics.config}}};_initializeConfig();var metrics_1=metrics;var mtMetricskit=metrics_1;function sanitizeEventForPrivacyCompliance(e){const t=["dsId","clientId","userAgent","analyticsClientId"];const r=cloneDeep(e);t.forEach(e=>{delete r[e]});const i=r?.eventTime;if(i){const e=new Date(new Date(i).toDateString());r.eventTime=e.getTime()}return r}function urlContainsVacToken(e){if(typeof e==="string"){const t=new RegExp("meta=vacToken","i");return t.test(e)}}function sanitizeImpressionsForPrivacyCompliance(e,t={}){if(t.pageContext==="ListenNow"&&urlContainsVacToken(t.pageUrl)&&Array.isArray(e)){e.forEach(e=>{const t=e?.fields;if(t.impressionType==="GridItem"){t.id="RequestItem";delete t.description;delete t.name}})}return e}function shouldDeferSendingEvent(e){const t=e?.pageId;if(!t){return false}const r=["CarPlayLibraryUpsell"];return r.indexOf(t)>-1}function shouldSuppressUserInfoForMetricsData(e){const t=e?.pageId;if(!t){return false}const r=["CarPlayNonsubscriber","CarPlayLibraryUpsell","MusicRecognitionInControlCenterFullSheet"];return r.indexOf(t)>-1}function removeBundleIdentifiersFromOptionsForPrivacyCompliance(e={}){const t=["com.noodlecake.soundfall","com.n3twork.tetrisbeat","com.gameloft.SongPopParty","com.rogue.mindsymphony","com.apple.mobileslideshow"];const r=cloneDeep(e);const i=r.sourceApplicationBundleIdentifier;if(t.indexOf(i)!==-1){delete r.sourceApplicationBundleIdentifier}return r}function createArtwork(e){return Object.assign(new Artwork,e)}const MUSIC_VIDEO_KINDS=["musicVideo","uploadedVideo","movie"];function isMusicVideoKind(e){return MUSIC_VIDEO_KINDS.indexOf(e)!==-1}function getVerticalVideoArtworkProperties(e){const t=e?.kind;const r={};if(isMusicVideoKind(t)){const i=e?.artwork;const n=i?.height;const o=i?.width;const s=i?.url;const a=n>o;if(a){if(s){if(t==="musicVideo"){e.artwork.url=s.replace("{w}x{h}mv",`${o}x${n}bf`)}const i={url:e.artwork.url,height:1080,width:1080};r.backgroundArtwork=createArtwork({dictionary:i,cropStyle:"bf"})}}}return r}function getStoreMetricsFields(e){const t=get(e,"xhrMetrics");const r=get(e,"pageData.metrics");const i=Object.assign({pageId:get(e,"pageData.id")},get(e,"pageData.metricsBase"));return[i,t,r]}function combineWithSeparator(...e){let t="";if(e){t=e.filter(e=>e&&typeof e==="string").join(mtMetricskit.config.value("compoundSeparator"))}return t}function currentPageContext(){let e;switch(Application.selectedTabIdentifier){case Application.TAB_IDENTIFIER.LISTEN_NOW:e="ListenNow";break;case Application.TAB_IDENTIFIER.BROWSE:e="Browse";break;case Application.TAB_IDENTIFIER.RADIO:e="Radio";break;case Application.TAB_IDENTIFIER.SEARCH:e="Search";break;case Application.TAB_IDENTIFIER.LIBRARY:e="Library";break}return e}function extractMappedFields(e,t){return mtMetricskit.utils.eventFields.applyFieldsMap(e,t)}function combineActionDetails(e={},t={}){return Object.assign({},e,t)}function assignClickMetricsFields(...e){const t=e.shift();if(!t){logger$5.warn("assignClickMetricsFields requires at least one metrics field object");return}e.forEach(e=>{if(typeof e!=="object"||e===null){return}Object.entries(e).forEach(([r,i])=>{if(r==="actionDetails"){if(typeof i==="object"&&i!==null){if(Object.keys(i).length>0){t.actionDetails=combineActionDetails(t.actionDetails,i)}}else if(i!==undefined){logger$5.warn("assignClickMetricsFields: actionDetails should be an object",e)}}else{t[r]=i}})});return t}function assignPageMetricsFields(...e){const t=e.shift();if(!t){logger$5.warn("assignPageMetricsFields requires at least one metrics field object");return}e.forEach(e=>{if(typeof e!=="object"||e===null){return}Object.entries(e).forEach(([r,i])=>{if(r==="pageDetails"){if(typeof i==="object"&&i!==null){if(Object.keys(i).length>0){t.pageDetails=combineActionDetails(t.pageDetails,i)}}else if(i!==undefined){logger$5.warn("assignPageMetricsFields: pageDetails should be an object",e)}}else{t[r]=i}})});return t}function getTypeOfItem(e){return Object.getPrototypeOf(e).constructor.name}const metricsHandlersKey=Symbol("metricsHandlers");function createMetricsDescriptorForKey(e){return t=>{let r;if(t.object){const{object:i}=t;r=t.fields;const n=get(i,"kind");if(n){Object.assign(r,{kind:n})}const o=get(i,"reco_id");if(o){Object.assign(r,{"data.reco.dataSetId":o})}const s=get(i,"displayStyle");if(s){Object.assign(r,{displayStyle:s})}const a=get(i,["metrics",e]);if(a){Object.assign(r,a)}const{storePlatformDictionary:l}=i;if(l){const t=extractMappedFields(l,e);if(get(t,"kind")==="socialProfile"){delete t.id;delete t.name}Object.assign(r,t)}const c=i[metricsHandlersKey];if(c){const e=[];c.forEach(t=>{const r=t(i);const n=get(r,"actionDetails");if(n){Object.keys(n).forEach(e=>n[e]===undefined&&delete n[e]);if(Object.keys(n).length>0){e.push({actionDetails:n})}}});assignClickMetricsFields(r,...e)}if(!r.name&&i.name){if(r.id!=="RequestItem"){r.name=i.name}}}else if(t.fields){r=t.fields}else if(t){r=t}if(!r.id){r.id=get(t,"object.id")||get(t,"object.resourceIdentifier.id")}return r}}const addImpressionsFields=createMetricsDescriptorForKey("impressions");function createLocationItemFromImpression(e){const t=addImpressionsFields(e);const r={};r.locationType=t.impressionType;r.locationPosition=t.impressionIndex;r.id=t.id;r.containerType=get(e,"object.containerType");r.kind=t.kind;r.name=t.name;r["data.reco.dataSetId"]=t["data.reco.dataSetId"];r.displayStyle=t.displayStyle;r.actionDetails=t.actionDetails;r.actionType=t.actionType;if(e.object&&e.object.identifierSet){const t=e.object;const i=t.identifierSet;r.kind=i.contentKind;r.heading=t.sectionTitle;r.description=t.description}return r}function createLocationField(e,t=[]){let r=t.find(t=>t?.object===e);if(!r){r=t.find(t=>t.fields.id===e.recommendationId)}if(!r){return}const i=new Map(t.map(e=>[e.fields.impressionId,e]));const n=[createLocationItemFromImpression(r)];while(r&&r.fields.impressionParentId){r=i.get(r.fields.impressionParentId);if(r){n.push(createLocationItemFromImpression(r))}}return n}function clickMetricsFieldsForItem(e){const t=e[metricsHandlersKey];if(!t){return{}}const r=[];t.forEach(t=>{const i=t(e);if(i){r.push(i)}});return assignClickMetricsFields({},...r)}function getActionTypeForKind(e,t){if(t){return"play"}const r=["song","track","radioStation","uploadedAudio"].concat(MUSIC_VIDEO_KINDS);return r.indexOf(e)===-1?"navigate":"play"}function clickFieldsForStorePlatformDictionary(e){const t=e.kind;if(t==="socialProfile"){return null}const r={};const i=e.id;if(i){assignClickMetricsFields(r,{targetId:i})}const n=e.url;if(n){assignClickMetricsFields(r,{actionUrl:n})}return r}function clickFieldsForIdentifierSet(e={}){const t={};const r=e.storeAdamID||"userContent";const i=e.contentKind;if(i){assignClickMetricsFields(t,{targetId:r,actionDetails:{kind:i}})}return t}function clickMetricsForImpressions(e,t,r,i){const n={};const{identifierSet:o,storePlatformDictionary:s,resourceIdentifier:a}=e;const l=t?.impressions;let c;if(s){assignClickMetricsFields(n,clickFieldsForStorePlatformDictionary(s));c=s.kind}else if(o){assignClickMetricsFields(n,clickFieldsForIdentifierSet(o));c=o.contentKind}else{const t=a?.id;if(t){assignClickMetricsFields(n,{targetId:t})}const r=e.url;if(r){assignClickMetricsFields(n,{actionUrl:r})}const i=e?.metrics?.eligibilityType;if(i){assignClickMetricsFields(n,{eligibilityType:i})}const o=e?.metrics?.placement;if(o){assignClickMetricsFields(n,{placement:o})}const s=e?.metrics?.placementType;if(s){assignClickMetricsFields(n,{placementType:s})}const l=e?.metrics?.channelPartner;if(l){assignClickMetricsFields(n,{channelPartner:l})}const c=e?.metrics?.upsellScenario;if(c){assignClickMetricsFields(n,{upsellScenario:c})}const u=e?.metrics?.upsellType;if(u){assignClickMetricsFields(n,{upsellType:u})}}const u=e?.isDirectPlayEnabled;n.actionType=getActionTypeForKind(c,u);n.targetType=getTypeOfItem(e);if(l){const r=t?.pageDetailsProvider?.pageMetricsController?.pageFields;let i;if(r){i={pageContext:r?.pageType,pageUrl:r?.pageUrl}}const o=sanitizeImpressionsForPrivacyCompliance(t?.impressions,i);n.impressions=o.map(e=>addImpressionsFields(e));n.location=t?.location||createLocationField(e,t?.impressions);if(e.metrics?.impressions?.marketing){n.marketing=e.metrics.impressions.marketing}}else{logger$5.warn(`Missing impressions for click on view model item with id "${n.targetId}" and kind "${c}"`)}if(i){n?.location?.push(...i)}const d=clickMetricsFieldsForItem(e);assignClickMetricsFields(n,d,r);const g={pageContext:currentPageContext()};const h=get(t,"pageDetailsProvider.pageMetricsController");if(h){const{pageMetrics:e,combinedPageFields:t,xhrMetrics:r}=h;Object.assign(g,t,r,e)}else{logger$5.warn(`Missing pageMetricsController for click on view model item with id "${n.targetId}" and kind "${c}"`)}return[n,g]}function addClickMetricsHandlerToItem(e,t){let r=e[metricsHandlersKey];if(!r){r=new Set;e[metricsHandlersKey]=r}r.add(t)}function addAdditionalMarketingItemMetrics(e={},t={}){const r=["eligibilityType","placement","placementType","channelPartner","upsellScenario","upsellType"];r.forEach(r=>{if(t[r]&&t[r].length>0){e[r]=t[r];if(e.impressions){e.impressions[r]=t[r]}}});return e}const CAR_PLAY_TOPIC="xp_amp_music_carplay";const UNIDENTIFIED_TOPIC="xp_amp_music_cs_unidentified";const DEFAULT_TOPIC="xp_its_music_main";const PERF_TOPIC="xp_amp_clientperf";let storedLaunchData;function storeLaunchData(e){storedLaunchData=e}function clearLaunchData(){storedLaunchData=undefined}function gatedRecordEvent(e=noop,t=DEFAULT_TOPIC){return getBagValue("metrics").then(e).then(e=>{const r=shouldSuppressUserInfoForMetricsData(e);let i=e;let n=t;if(r){i=sanitizeEventForPrivacyCompliance(i);n=UNIDENTIFIED_TOPIC}mtMetricskit.system.eventRecorder.recordEvent(n,i,r,true)}).catch(e=>logger$5.error("sending metrics error",e))}function ungatedRecordEvent(e,t=DEFAULT_TOPIC){return mtMetricskit.system.eventRecorder.recordEvent(t,e,shouldSuppressUserInfoForMetricsData(e),false)}let hasFiredEnter=false;function recordEnter(){const e=storedLaunchData;clearLaunchData();const t=hasFiredEnter?"taskSwitch":"launch";hasFiredEnter=true;gatedRecordEvent(()=>mtMetricskit.eventHandlers.enter.metricsData(undefined,undefined,undefined,{type:t},e))}function recordExitAndFlush(){gatedRecordEvent(()=>mtMetricskit.eventHandlers.exit.metricsData(undefined,undefined,undefined)).then(()=>{MetricsController.flushUnreportedEvents()})}function updateLaunchData(e={}){const{sourceApplicationBundleIdentifier:t,referrerURL:r,url:i}=e;storeLaunchData({refApp:t,extRefUrl:r});return{refApp:t,extRefUrl:r,originalUrl:i}}function recordPageEvent(e={},t={},r={},i={}){gatedRecordEvent(()=>{const n={pageLoadTime:Date.now()};return mtMetricskit.eventHandlers.page.metricsData(undefined,undefined,undefined,n,e,t,r,i,get(r,"fields"))})}function recordDialogEvent(e={},t={},r={},i={}){gatedRecordEvent(()=>{const n=undefined;return mtMetricskit.eventHandlers.dialog.metricsData(undefined,undefined,undefined,n,e,t,r,i,get(r,"fields"))})}function recordFlexibleEvent(e,...t){gatedRecordEvent(()=>mtMetricskit.eventHandlers.flexible.metricsData(e,...t),PERF_TOPIC)}let isSamplingRendering=false;let renderingSession;function rerollPageRenderSampling(){const e=mtMetricskit.config.value("performance.samplingPercentageUsersPageRender")||0;const t=Math.random(){isSamplingRendering=false};renderingSession.schedule()}else if(!t&&isSamplingRendering){isSamplingRendering=false;if(renderingSession){renderingSession.cancel();renderingSession=null}}return isSamplingRendering}function recordPageRenderEvent(...e){if(isSamplingRendering||rerollPageRenderSampling()){recordFlexibleEvent("pageRender",...e)}}function recordImpressionsEvent(e,t){return gatedRecordEvent(()=>{const r=e.map(e=>addImpressionsFields(e));return mtMetricskit.eventHandlers.impressions.metricsData(undefined,undefined,undefined,t,{impressions:r})})}function recordCarPlayEvent(e){if(!e){logger$5.warn("Unable to record a car play event which doesn't provide the event.");return}return gatedRecordEvent(()=>{const t=mtMetricskit.eventHandlers.media.metricsData(undefined,undefined,undefined,e);t.eventType="playsSummary";Reflect.deleteProperty(t,"screenWidth");Reflect.deleteProperty(t,"screenHeight");Reflect.deleteProperty(t,"windowInnerHeight");Reflect.deleteProperty(t,"windowInnerWidth");Reflect.deleteProperty(t,"windowOuterHeight");Reflect.deleteProperty(t,"windowOuterWidth");Reflect.deleteProperty(t,"pixelRatio");return t},CAR_PLAY_TOPIC)}function recordClickEvent(e,t){if(!e){logger$5.warn("Unable to record a click event which doesn't provide click fields.",t);return}const r=Object.assign({},e);if(typeof r.actionDetails==="object"&&r.actionDetails!==null){if(Object.keys(r.actionDetails).length>0){r.eventVersion=5}else{delete r.actionDetails}}return gatedRecordEvent(()=>mtMetricskit.eventHandlers.click.metricsData(undefined,undefined,undefined,undefined,t,r))}function reportEventForLocalEvaluation(e){MetricsController.reportEventForLocalEvaluation(e)}const LOGGED_OUT_KEY="noauth";function getDsid(){return userDSID()||LOGGED_OUT_KEY}function getItemsByDsid(){return Persistence.localStorage.getItem(getDsid())}const Storage={clear(){Persistence.localStorage.clear()},getItem(e){return get(Storage.getWrappedItem(e),"value")},getRawItem(e){return Persistence.localStorage.getItem(e)},getWrappedItem(e){return get(getItemsByDsid(),e)},migrateNoAuthToDsid(e=userDSID()){const t=Storage.getRawItem(e)||{};const r=Storage.getRawItem(LOGGED_OUT_KEY)||{};const i=Object.assign({},t,r);Storage.setRawItem(e,i);Storage.removeRawItem(LOGGED_OUT_KEY)},removeItem(e){const t=getItemsByDsid()||{};delete t[e];Persistence.localStorage.setItem(getDsid(),t)},removeItemsForDsid(e=getDsid()){Persistence.localStorage.removeItem(e)},removeRawItem(e){return Persistence.localStorage.removeItem(e)},setItem(e,t){const r=getItemsByDsid()||{};r[e]={value:t,date:Date.now(),systemVersion:Device.systemVersion};return Persistence.localStorage.setItem(getDsid(),r)},setRawItem(e,t){return Persistence.localStorage.setItem(e,t)},setWrappedItem(e,t){const r={value:t,date:Date.now(),systemVersion:Device.systemVersion};return Persistence.localStorage.setItem(e,r)}};var StorageKeys={User:{LAST_MAJOR_VERSION_WELCOME_SHEET_PRESENTED:"lastMajorVersionWelcomeSheetPresented",LAST_MAJOR_VERSION_HAS_MANUALLY_DISMISSED_SEARCH_LANDING_UPSELL:"lastMajorVersionHasManuallyDismissedSearchLandingUpsell",LAST_DISMISSED_INLINE_SOCIAL_UPSELL_BANNER_VERSION:"FOR_YOU_DISCOVER_FRIENDS",HAS_SEEN_WINBACK_OFFER:"hasSeenWinbackOffer",DATE_CACHED_SHOW_IN_LIBARY_SETTING_LAST_SYNCED:"dateCachedShowInLibrarySettingLastSynced",NON_SUBSCRIBER_TRIAL_ELIGIBLE_DID_USE_CAR_PLAY:"nonSubscriberTrialEligibleDidUseCarPlay",LAST_NON_SUBSCRIBER_TRIAL_ELIGIBLE_CAR_PLAY_EVENT_DISPATCH_TIME:"lastNonSubscriberTrialEligibleCarPlayEventDispatchTime",NON_SUBSCRIBER_CAR_PLAY_UPSELL_BATCHED_SANITIZED_EVENTS:"nonSubscriberCarPlayUpsellBatchedSanitizedEvents",FAMILY_WELCOME_SHOWN:"familyWelcomeShown",HAS_MANUALLY_DISMISSED_SEARCH_LANDING_UPSELL:"hasManuallyDismissedSearchLandingUpsell",RECOMMENDED_FRIENDS_RESPONSE:"recommendedFriendsResponse",FOR_YOU_MODULE_CLOSED:"FOR_YOU_CLOSED_KEY_",FORCED_SUBSCRIPTION_STATUS_REFRESH_ON_VERSION:"lastForcedSubscriptionStatusRefreshVersion",FORCED_SUBSCRIPTION_STATUS_REFRESH_ON_BUILD_WITH_NATIVE_FIX:"forcedSubscriptionStatusRefreshOnBuildWithNativeFix",HAS_PRESENTED_NOTIFICATIONS_UPSELL:"hasPresentedNotificationsUpsell",SHOULD_PRESENT_NOTIFICATIONS_UPSELL_ONCE:"shouldPresentNotificationsUpsellOnce"},Device:{HAS_SEEN_RETAIL_DEVICE_OFFER:"hasSeenRetailDeviceOffer",CAR_PLAY_BATCH_TIME_PLAYED:"carPlayBatchTimePlayed",CAR_PLAY_BATCH_TRACKS_PLAYED:"carPlayBatchTracksPlayed",CAR_PLAY_FIRST_EVENT_IN_BATCH_TIMESTAMP:"carPlayFirstEventInBatchTimeStamp",LAST_TIME_SOCIAL_ONBOARDING_PRESENTED:"lastTimeSocialOnboardingPresented",LOCALIZED_STRINGS:"localizedStrings",HOME_POD_OFFER_LAST_PRESENTED_V2:"homePodOfferLastPresented.v2",LAST_STUDENT_PROMPT:"lastStudentPrompt",LAST_MAJOR_VERSION_TRIGGERED:"lastMajorVersionTriggered",LAST_WELCOME_PRESENTATION:"lastWelcomePresentation",DID_RETRIGGER_WELCOME_PRESENTATION:"didRetriggerWelcomePresentation",LAST_MAJOR_VERSION_NO_THANKS_REVERTED:"lastMajorVersionNoThanksReverted",DID_SEND_ALLOWS_EXPLICIT_CONTENT_SETTING:"didSendAllowsExplicitContentSetting",NOTIFICATIONS_UPSELL_KEY:"NOTIFICATIONS_UPSELL_KEY",LAST_REFRESHED_SUBSCRIPTION_STATUS_VERSION:"lastStatusVersionChecked"}};const subscribersForTopic=new Map;function publish(e,t){const r=subscribersForTopic.get(e);if(r){r.forEach(e=>{if(typeof e==="function"){e(t)}})}}function subscribe(e,t){let r=subscribersForTopic.get(e);if(!r){r=new Set;subscribersForTopic.set(e,r)}r.add(t)}function unsubscribe(e,t){const r=subscribersForTopic.get(e);if(r){r.delete(t)}}const LIBRARY_OPT_IN_SHEET_SWIPE_DISMISSED="LIBRARY_OPT_IN_SHEET_SWIPE_DISMISSED";function recordNativeLegacyClickEvent(e){const{targetId:t,contentDictionary:r={}}=e;const i="button";let{actionType:n}=e;let o;let s;if(t==="trackSelection"){o=get(r,"trackSelection.track.id");s=get(r,`playlist.children.${o}.url`)||get(r,`album.children.${o}.url`);n="play"}else if(t==="shuffleAll"||t==="playAll"){o=get(r,"playlist.id")||get(r,"album.id");s=get(r,"playlist.url")||get(r,"album.url");n="play"}else if(t==="addToLibrary"||t==="contextualActionButtonSelection"){o=get(r,"playlist.id")||get(r,"album.id")}else if(t==="trackAddToLibrary"){o=get(r,"trackAddToLibrary.track.id")}if(!o){o=get(r,"id")}recordClickEvent({actionType:n,actionDetails:t,actionUrl:s,targetId:o,targetType:i},{pageContext:currentPageContext()})}function considerOptingOutOfPushNotifications(e){const t=get(e,"pageId");const r=get(e,"targetId");const i=t==="LibraryContentBannerOptInNonsubscriber"||t==="LibraryContentBannerOptInSubscriber";if(i&&r==="SwipeDismiss"){publish(LIBRARY_OPT_IN_SHEET_SWIPE_DISMISSED)}}function recordNativeClickEvent(e){const t=Object.assign({},e,{pageContext:currentPageContext()});considerOptingOutOfPushNotifications(e);recordClickEvent(t)}const PrivacyDisclaimerPageEventPageId={WELCOME_GDPR:"Welcome_GDPR",SUBSCRIBE_GDPR:"Subscribe_GDPR"};function recordNativePageEvent(e){const t=Object.assign({},e,{pageContext:currentPageContext()});const r=get(e,"pageId");switch(r){case PrivacyDisclaimerPageEventPageId.WELCOME_GDPR:case PrivacyDisclaimerPageEventPageId.SUBSCRIBE_GDPR:break;default:recordPageEvent(t)}}function recordNativePageRenderEvent(e){recordFlexibleEvent("pageRender",e)}function onRecordNativeEvent(e){const t=get(e,"eventType");switch(t){case"click":recordNativeClickEvent(e);break;case"page":recordNativePageEvent(e);break;case"dialog":recordDialogEvent(e);break;case"impressions":{const t=e.impressions;if(t){delete e.impressions;recordImpressionsEvent(t,e)}break}case"pageRender":recordNativePageRenderEvent(e);break;default:recordNativeLegacyClickEvent(e)}}function initializeNativeMetrics(){registerGlobalCallback(MetricsController,"onRecordNativeEvent",onRecordNativeEvent)}const MetricsFieldsForAction={addToLibrary:()=>({actionType:"add",targetId:"addToLibrary",actionDetails:{addTo:"Library"},targetType:"button"}),addToPlaylist:()=>({actionType:"add",targetId:"addToPlaylist",actionDetails:{addTo:"Playlist"},targetType:"button"}),artistFavorited:()=>({actionType:"favorite",targetType:"button"}),artistUnfavorited:()=>({actionType:"unfavorite",targetType:"button"}),autoPlay:()=>({targetId:"autoPlay",targetType:"button"}),autoPlayOff:()=>({targetId:"autoPlayOff",targetType:"button"}),cancelEdit:()=>({actionType:"cancel",actionDetails:{cancelledActionType:"edit"},targetId:"cancel",targetType:"button"}),cancelNew:()=>({actionType:"cancel",actionDetails:{cancelledActionType:"addNew"},targetId:"cancel",targetType:"button"}),containerDetailLink:()=>({actionType:"navigate",targetId:"seeAll",targetType:"button"}),createStation:()=>({actionType:"play",actionDetails:{playType:"createStation"},targetId:"createStation",targetType:"button"}),dismissAppleClassicalPopover:()=>({actionType:"dismiss",targetId:"close",targetType:"bubbleTip"}),dismissArtistFavoritingPopover:()=>({actionType:"dismiss",targetId:"close",targetType:"bubbleTip"}),dismissSingPopover:()=>({actionType:"dismiss",targetId:"close",targetType:"bubbleTip"}),download:()=>({actionType:"download"}),navigateBack:()=>({actionType:"back",targetType:"button"}),edit:()=>({actionType:"edit",targetId:"edit",targetType:"button"}),fullSchedule:()=>({targetType:"button",targetId:"fullSchedule",actionType:"navigate"}),hate:()=>({actionType:"hate",targetType:"button"}),hideLyrics:()=>({actionType:"navigate",targetId:"hideLyrics",targetType:"button"}),hideUpNextQueue:()=>({actionType:"navigate",targetId:"hideUpNext",targetType:"button"}),love:()=>({actionType:"love",targetId:"love",targetType:"button"}),openInAppleClassical:()=>({actionType:"navigate",targetId:"OpenInAppleClassical",targetType:"link"}),new:()=>({actionType:"addNew",targetId:"new",targetType:"button"}),playAll:()=>({actionType:"play",actionDetails:{playType:"all"}}),playLater:()=>({actionType:"add",actionDetails:{addTo:"EndOfQueue"},targetType:"button"}),playNext:()=>({actionType:"add",actionDetails:{addTo:"StartOfQueue"},targetType:"button"}),playRadioStation:()=>({actionType:"play",targetType:"button"}),play:()=>({actionType:"play"}),recordLabelLink:()=>({actionType:"navigate",targetType:"button"}),removeDownload:()=>({actionType:"delete",actionDetails:{deleteFrom:"Downloads"}}),removeDownloadOrFromLibrary:()=>({actionType:"delete",actionDetails:{deleteFrom:"Downloads/Library"}}),removeFromLibrary:()=>({actionType:"delete",actionDetails:{deleteFrom:"Library"}}),reportConcern:()=>({actionType:"navigate",actionDetails:{navigateTo:"ReportAConcern"},targetType:"button"}),saveEdit:()=>({actionType:"update",targetId:"done",targetType:"button"}),saveNew:()=>({actionType:"create",targetId:"done",targetType:"button"}),searchLandingItemClick:()=>({targetType:"Category",actionContext:"Category",actionType:"navigate"}),searchLandingUpsellSeeAllPlans:()=>({targetId:"SeeAllPlans",targetType:"button",actionType:"navigate"}),searchLandingUpsellSelect:e=>({targetType:"platter",actionType:e?"buy":"navigate",actionDetails:e?{buyParams:e}:undefined}),searchLandingUpsellDismiss:e=>({targetId:"DismissX",actionType:"dismiss",targetType:"platter",actionDetails:{title:e.title}}),listenNowMusicSiriUpsellSelect:e=>({targetType:"banner",actionType:"buy",actionDetails:e?{buyParams:e}:undefined}),seeAll:()=>({actionType:"navigate",targetId:"seeAll",targetType:"button"}),seekLyrics:e=>({actionType:"seek",targetId:e,targetType:"lyricLine"}),share:()=>({actionType:"share",targetType:"button"}),shareLyrics:()=>({actionType:"share",actionContext:"contextualAction",targetType:"button",targetId:"share_lyric"}),shareLyricsAction:()=>({actionType:"share",actionContext:"lyric",targetType:"app"}),sharePlay:()=>({actionType:"sharePlay",actionContext:"contextualAction",targetType:"button"}),story:()=>({actionType:"share",actionContext:"story",targetType:"app"}),showContextualActions:()=>({actionType:"sheet"}),shuffleAll:()=>({actionType:"play",actionDetails:{playType:"shuffleAll"}}),showLyrics:()=>({actionType:"navigate",targetId:"showLyrics",targetType:"button"}),showUpNextQueue:()=>({actionType:"navigate",targetId:"showUpNext",targetType:"button"}),socialFollow:()=>({actionType:"follow",targetType:"button"}),unlove:()=>({actionType:"unlove",targetType:"button"}),viewAlbum:()=>({actionType:"navigate",actionDetails:{navigateTo:"Album"},targetType:"button"}),viewNotes:()=>({actionType:"navigate",actionDetails:{action:"more"},targetType:"button"}),vocalAttenuationChangeLevel:()=>({actionContext:"vocalAttenuation",actionType:"adjust",targetType:"slider"}),vocalAttenuationTurnOff:()=>({actionContext:"vocalAttenuation",actionType:"toggle",targetId:"disableVocalAttenuation",targetType:"button"}),vocalAttenuationTurnOn:()=>({actionContext:"vocalAttenuation",actionType:"toggle",targetId:"enableVocalAttenuation",targetType:"button"})};function metricsFieldsForSource(e,t){const r=get(t,"actionContext");if(e&&!r){return{actionContext:e}}}function metricsFieldsForItemKind(e){if(e){return{actionDetails:{kind:e}}}}function metricsFieldsForTargetId(e){if(e){return{targetId:e}}}function metricsFieldsForItemSectionName(e){if(e){return{actionDetails:{sectionName:e}}}}function metricsFieldsForStationId(e){if(e){return{actionDetails:{station:e}}}}function metricsFieldsForActionURL(e){if(e){return{actionUrl:e}}}function metricsFieldsForBaseItemAction(e,t,r,i,n){const o={};switch(e){case BaseItem.ACTION.ADD_TO_LIBRARY:assignClickMetricsFields(o,MetricsFieldsForAction.addToLibrary());break;case BaseItem.ACTION.ADD_TO_PLAYLIST:assignClickMetricsFields(o,MetricsFieldsForAction.addToPlaylist());break;case BaseItem.ACTION.BEGIN_PLAYBACK:assignClickMetricsFields(o,MetricsFieldsForAction.play());break;case BaseItem.ACTION.CREATE_STATION:assignClickMetricsFields(o,MetricsFieldsForAction.createStation());break;case BaseItem.ACTION.DOWNLOAD:assignClickMetricsFields(o,MetricsFieldsForAction.download());break;case BaseItem.ACTION.HATE:assignClickMetricsFields(o,MetricsFieldsForAction.hate());break;case BaseItem.ACTION.LOVE:assignClickMetricsFields(o,MetricsFieldsForAction.love());break;case BaseItem.ACTION.PLAY_LATER:assignClickMetricsFields(o,MetricsFieldsForAction.playLater());break;case BaseItem.ACTION.PLAY_NEXT:assignClickMetricsFields(o,MetricsFieldsForAction.playNext());break;case BaseItem.ACTION.REMOVE_DOWNLOAD:assignClickMetricsFields(o,MetricsFieldsForAction.removeDownload());break;case BaseItem.ACTION.REMOVE_DOWNLOAD_OR_FROM_LIBRARY:assignClickMetricsFields(o,MetricsFieldsForAction.removeDownloadOrFromLibrary());break;case BaseItem.ACTION.REMOVE_FROM_LIBRARY:assignClickMetricsFields(o,MetricsFieldsForAction.removeFromLibrary());break;case BaseItem.ACTION.REPORT_CONCERN:assignClickMetricsFields(o,MetricsFieldsForAction.reportConcern());break;case BaseItem.ACTION.SHARE:assignClickMetricsFields(o,MetricsFieldsForAction.share());break;case BaseItem.ACTION.SHARE_LYRICS:assignClickMetricsFields(o,MetricsFieldsForAction.shareLyrics());break;case BaseItem.ACTION.SHARE_LYRICS_ACTION:assignClickMetricsFields(o,MetricsFieldsForAction.shareLyricsAction());break;case BaseItem.ACTION.SHARE_PLAY:assignClickMetricsFields(o,MetricsFieldsForAction.sharePlay());break;case BaseItem.ACTION.SOCIAL_FOLLOW:assignClickMetricsFields(o,MetricsFieldsForAction.socialFollow());break;case BaseItem.ACTION.UNLOVE:assignClickMetricsFields(o,MetricsFieldsForAction.unlove());break;case BaseItem.ACTION.VIEW_ALBUM:assignClickMetricsFields(o,MetricsFieldsForAction.viewAlbum());break;case BaseItem.ACTION.STORY:assignClickMetricsFields(o,MetricsFieldsForAction.story());break;default:logger$5.warn("Couldn't derive metrics fields from unknown BaseItem.ACTION",e);return null}assignClickMetricsFields(o,metricsFieldsForSource(t,o));assignClickMetricsFields(o,metricsFieldsForItemKind(r));assignClickMetricsFields(o,metricsFieldsForTargetId(n||i));return o}function baseFieldsForContainerDetailAction(e){const t={};switch(e){case ContainerDetail.ACTION.ADD_TO_LIBRARY:assignClickMetricsFields(t,MetricsFieldsForAction.addToLibrary());break;case ContainerDetail.ACTION.ADD_TO_PLAYLIST:assignClickMetricsFields(t,MetricsFieldsForAction.addToPlaylist());break;case ContainerDetail.ACTION.BEGIN_PLAYBACK:assignClickMetricsFields(t,MetricsFieldsForAction.play());break;case ContainerDetail.ACTION.CREATE_STATION:assignClickMetricsFields(t,MetricsFieldsForAction.createStation());break;case ContainerDetail.ACTION.DISMISS_APPLE_CLASSICAL_POPOVER:assignClickMetricsFields(t,MetricsFieldsForAction.dismissAppleClassicalPopover());break;case ContainerDetail.ACTION.DOWNLOAD:assignClickMetricsFields(t,MetricsFieldsForAction.download());break;case ContainerDetail.ACTION.NAVIGATE_BACK:assignClickMetricsFields(t,MetricsFieldsForAction.navigateBack());break;case ContainerDetail.ACTION.HATE:assignClickMetricsFields(t,MetricsFieldsForAction.hate());break;case ContainerDetail.ACTION.LOVE:assignClickMetricsFields(t,MetricsFieldsForAction.love());break;case ContainerDetail.ACTION.OPEN_IN_APPLE_CLASSICAL:assignClickMetricsFields(t,MetricsFieldsForAction.openInAppleClassical());break;case ContainerDetail.ACTION.PLAY_ALL:assignClickMetricsFields(t,MetricsFieldsForAction.playAll());break;case ContainerDetail.ACTION.PLAY_LATER:assignClickMetricsFields(t,MetricsFieldsForAction.playLater());break;case ContainerDetail.ACTION.PLAY_NEXT:assignClickMetricsFields(t,MetricsFieldsForAction.playNext());break;case ContainerDetail.ACTION.PLAY_TRACK:assignClickMetricsFields(t,MetricsFieldsForAction.play());break;case ContainerDetail.ACTION.RECORD_LABEL_LINK:assignClickMetricsFields(t,MetricsFieldsForAction.recordLabelLink());break;case ContainerDetail.ACTION.REMOVE_DOWNLOAD:assignClickMetricsFields(t,MetricsFieldsForAction.removeDownload());break;case ContainerDetail.ACTION.REMOVE_DOWNLOAD_OR_FROM_LIBRARY:assignClickMetricsFields(t,MetricsFieldsForAction.removeDownloadOrFromLibrary());break;case ContainerDetail.ACTION.REMOVE_FROM_LIBRARY:assignClickMetricsFields(t,MetricsFieldsForAction.removeFromLibrary());break;case ContainerDetail.ACTION.REPORT_CONCERN:assignClickMetricsFields(t,MetricsFieldsForAction.reportConcern());break;case ContainerDetail.ACTION.SHARE:assignClickMetricsFields(t,MetricsFieldsForAction.share());break;case ContainerDetail.ACTION.SHARE_LYRICS:assignClickMetricsFields(t,MetricsFieldsForAction.shareLyrics());break;case ContainerDetail.ACTION.SHARE_LYRICS_ACTION:assignClickMetricsFields(t,MetricsFieldsForAction.shareLyricsAction());break;case ContainerDetail.ACTION.SHARE_PLAY:assignClickMetricsFields(t,MetricsFieldsForAction.sharePlay());break;case ContainerDetail.ACTION.STORY:assignClickMetricsFields(t,MetricsFieldsForAction.story());break;case ContainerDetail.ACTION.SHOW_CONTEXTUAL_ACTIONS:assignClickMetricsFields(t,MetricsFieldsForAction.showContextualActions());break;case ContainerDetail.ACTION.SHUFFLE_ALL:assignClickMetricsFields(t,MetricsFieldsForAction.shuffleAll());break;case ContainerDetail.ACTION.SOCIAL_FOLLOW:assignClickMetricsFields(t,MetricsFieldsForAction.socialFollow());break;case ContainerDetail.ACTION.UNLOVE:assignClickMetricsFields(t,MetricsFieldsForAction.unlove());break;case ContainerDetail.ACTION.VIEW_ALBUM:assignClickMetricsFields(t,MetricsFieldsForAction.viewAlbum());break;case ContainerDetail.ACTION.VIEW_NOTES:assignClickMetricsFields(t,MetricsFieldsForAction.viewNotes());break;default:logger$5.warn("Couldn't derive metrics fields from unknown ContainerDetail.ACTION",e);return null}return t}function metricsFieldsForContainerDetailAction(e,t,r,i,n,o){const s=baseFieldsForContainerDetailAction(e);if(!s){return null}assignClickMetricsFields(s,metricsFieldsForSource(t,s));assignClickMetricsFields(s,metricsFieldsForItemKind(r));if(e===ContainerDetail.ACTION.OPEN_IN_APPLE_CLASSICAL){assignClickMetricsFields(s,metricsFieldsForTargetId(e.targetId))}else{assignClickMetricsFields(s,metricsFieldsForTargetId(n||i))}assignClickMetricsFields(s,metricsFieldsForActionURL(o));return s}function metricsFieldsForPlaylistDetailAction(e,t,r,i,n){const o={};let s={};switch(e){case PlaylistDetail.ACTION.CANCEL_EDIT:s=n?MetricsFieldsForAction.cancelNew():MetricsFieldsForAction.cancelEdit();break;case PlaylistDetail.ACTION.EDIT:s=n?MetricsFieldsForAction.new():MetricsFieldsForAction.edit();break;case PlaylistDetail.ACTION.SAVE_EDIT:s=n?MetricsFieldsForAction.saveNew():MetricsFieldsForAction.saveEdit();break;case PlaylistDetail.ACTION.VIEW_NOTES:s=MetricsFieldsForAction.viewNotes();break;default:s=baseFieldsForContainerDetailAction(e)}if(!s){return null}assignClickMetricsFields(o,s);assignClickMetricsFields(o,metricsFieldsForSource(t,o));assignClickMetricsFields(o,metricsFieldsForItemKind(r));assignClickMetricsFields(o,metricsFieldsForTargetId(i));return o}function metricsFieldsForNowPlayingViewModelAction(e,t,r){const i={};const n=get(r,"target.kind");const o=get(r,"targetId");switch(e){case NowPlayingViewModel.ACTION.ADD_TO_LIBRARY:assignClickMetricsFields(i,MetricsFieldsForAction.addToLibrary());break;case NowPlayingViewModel.ACTION.ADD_TO_PLAYLIST:assignClickMetricsFields(i,MetricsFieldsForAction.addToPlaylist());break;case NowPlayingViewModel.ACTION.AUTO_PLAY:assignClickMetricsFields(i,MetricsFieldsForAction.autoPlay());break;case NowPlayingViewModel.ACTION.AUTO_PLAY_OFF:assignClickMetricsFields(i,MetricsFieldsForAction.autoPlayOff());break;case NowPlayingViewModel.ACTION.BEGIN_PLAYBACK:assignClickMetricsFields(i,MetricsFieldsForAction.play());break;case NowPlayingViewModel.ACTION.CREATE_STATION:assignClickMetricsFields(i,MetricsFieldsForAction.createStation());break;case NowPlayingViewModel.ACTION.DISMISS_SING_POPOVER:assignClickMetricsFields(i,MetricsFieldsForAction.dismissSingPopover());break;case NowPlayingViewModel.ACTION.DOWNLOAD:assignClickMetricsFields(i,MetricsFieldsForAction.download());break;case NowPlayingViewModel.ACTION.HATE:assignClickMetricsFields(i,MetricsFieldsForAction.hate());break;case NowPlayingViewModel.ACTION.HIDE_LYRICS:assignClickMetricsFields(i,MetricsFieldsForAction.hideLyrics());break;case NowPlayingViewModel.ACTION.HIDE_UP_NEXT_QUEUE:assignClickMetricsFields(i,MetricsFieldsForAction.hideUpNextQueue());break;case NowPlayingViewModel.ACTION.LOVE:assignClickMetricsFields(i,MetricsFieldsForAction.love());break;case NowPlayingViewModel.ACTION.PLAY_LATER:assignClickMetricsFields(i,MetricsFieldsForAction.playLater());break;case NowPlayingViewModel.ACTION.PLAY_NEXT:assignClickMetricsFields(i,MetricsFieldsForAction.playNext());break;case NowPlayingViewModel.ACTION.REPORT_CONCERN:assignClickMetricsFields(i,MetricsFieldsForAction.reportConcern());break;case NowPlayingViewModel.ACTION.SCRUB_LYRICS:{const e=get(r,"scrubLyricsLineIndex");assignClickMetricsFields(i,MetricsFieldsForAction.seekLyrics(e));break}case NowPlayingViewModel.ACTION.SHARE:assignClickMetricsFields(i,MetricsFieldsForAction.share());break;case NowPlayingViewModel.ACTION.SHARE_LYRICS:assignClickMetricsFields(i,MetricsFieldsForAction.shareLyrics());break;case NowPlayingViewModel.ACTION.SHARE_LYRICS_ACTION:assignClickMetricsFields(i,MetricsFieldsForAction.shareLyricsAction());break;case NowPlayingViewModel.ACTION.SHARE_PLAY:assignClickMetricsFields(i,MetricsFieldsForAction.sharePlay());break;case NowPlayingViewModel.ACTION.STORY:assignClickMetricsFields(i,MetricsFieldsForAction.story());break;case NowPlayingViewModel.ACTION.SHOW_LYRICS:assignClickMetricsFields(i,MetricsFieldsForAction.showLyrics());break;case NowPlayingViewModel.ACTION.SHOW_UP_NEXT_QUEUE:assignClickMetricsFields(i,MetricsFieldsForAction.showUpNextQueue());break;case NowPlayingViewModel.ACTION.SOCIAL_FOLLOW:assignClickMetricsFields(i,MetricsFieldsForAction.socialFollow());break;case NowPlayingViewModel.ACTION.UNLOVE:assignClickMetricsFields(i,MetricsFieldsForAction.unlove());break;case NowPlayingViewModel.ACTION.VIEW_ALBUM:assignClickMetricsFields(i,MetricsFieldsForAction.viewAlbum());break;case NowPlayingViewModel.ACTION.VOCAL_ATTENUATION_CHANGE_LEVEL:assignClickMetricsFields(i,MetricsFieldsForAction.vocalAttenuationChangeLevel());break;case NowPlayingViewModel.ACTION.VOCAL_ATTENUATION_TURN_OFF:assignClickMetricsFields(i,MetricsFieldsForAction.vocalAttenuationTurnOff());break;case NowPlayingViewModel.ACTION.VOCAL_ATTENUATION_TURN_ON:assignClickMetricsFields(i,MetricsFieldsForAction.vocalAttenuationTurnOn());break;default:logger$5.warn("Couldn't derive metrics fields from unknown NowPlayingViewModel.ACTION",e);return null}assignClickMetricsFields(i,metricsFieldsForSource(t,i));assignClickMetricsFields(i,metricsFieldsForItemKind(n));assignClickMetricsFields(i,metricsFieldsForTargetId(o));return i}function metricsFieldsForHeaderItemAction(e,t,r,i,n,o){const s={};switch(e){case HeaderItem.ACTION.PLAY_RADIO_STATION:assignClickMetricsFields(s,MetricsFieldsForAction.playRadioStation());break;case HeaderItem.ACTION.SHOW_CONTEXTUAL_ACTIONS:assignClickMetricsFields(s,MetricsFieldsForAction.showContextualActions());break;case HeaderItem.ACTION.NAVIGATE_BACK:assignClickMetricsFields(s,MetricsFieldsForAction.navigateBack());break;case HeaderItem.ACTION.OPEN_IN_APPLE_CLASSICAL:assignClickMetricsFields(s,MetricsFieldsForAction.openInAppleClassical());break;case HeaderItem.ACTION.DISMISS_APPLE_CLASSICAL_POPOVER:assignClickMetricsFields(s,MetricsFieldsForAction.dismissAppleClassicalPopover());break;case HeaderItem.ACTION.DISMISS_ARTIST_FAVORITING_POPOVER:assignClickMetricsFields(s,MetricsFieldsForAction.dismissArtistFavoritingPopover());break;case HeaderItem.ACTION.ARTIST_FAVORITED:assignClickMetricsFields(s,MetricsFieldsForAction.artistFavorited());assignClickMetricsFields(s,metricsFieldsForItemKind(o));break;case HeaderItem.ACTION.ARTIST_UNFAVORITED:assignClickMetricsFields(s,MetricsFieldsForAction.artistUnfavorited());assignClickMetricsFields(s,metricsFieldsForItemKind(o));break;default:logger$5.warn("Couldn't derive metrics fields from unknown HeaderItem.ACTION",e);return null}assignClickMetricsFields(s,metricsFieldsForItemSectionName(r));assignClickMetricsFields(s,metricsFieldsForTargetId(i||t));assignClickMetricsFields(s,metricsFieldsForActionURL(n));return s}function metricsFieldsForLiveRadioCase(e,t,r){const i={};assignClickMetricsFields(i,MetricsFieldsForAction.fullSchedule());assignClickMetricsFields(i,metricsFieldsForStationId(r));assignClickMetricsFields(i,metricsFieldsForActionURL(t));return i}function metricsFieldsForSearchLandingItem(e){const t={};assignClickMetricsFields(t,MetricsFieldsForAction.searchLandingItemClick());assignClickMetricsFields(t,metricsFieldsForTargetId(e));return t}function metricsFieldsForShelfAccessoryButtonItem(){const e={};assignClickMetricsFields(e,MetricsFieldsForAction.seeAll());return e}function metricsFieldsForContainerDetailLinkButtonItem(e){const t={};if(e.id&&e.type){assignClickMetricsFields(t,{targetId:e.id});assignClickMetricsFields(t,metricsFieldsForItemKind(e.type));assignClickMetricsFields(t,{targetType:"button"})}else{assignClickMetricsFields(t,MetricsFieldsForAction.containerDetailLink())}return t}function metricsFieldsForSearchLandingUpsell(e,t,r){const i={};const n=e?.primaryOffer?.metrics?.id;const o=e?.metrics?.impressions;if(o){o.id=n}assignClickMetricsFields(i,{targetId:n});switch(r){case SearchLandingUpsell.ACTION.ACCESSORY_BUTTON_SELECT:assignClickMetricsFields(i,MetricsFieldsForAction.searchLandingUpsellSeeAllPlans());break;case SearchLandingUpsell.ACTION.SELECT:{const t=e?.primaryOffer?.buyParams;assignClickMetricsFields(i,MetricsFieldsForAction.searchLandingUpsellSelect(t));break}case SearchLandingUpsell.ACTION.CLOSE_BUTTON_SELECT:assignClickMetricsFields(i,MetricsFieldsForAction.searchLandingUpsellDismiss(e));break;default:logger$5.warn("Couldn't derive metrics fields from unknown SearchLandingUpsell.ACTION",r);return null}return i}function metricsFieldsForListenNowMusicSiriUpsell(e,t){const r={};if(e&&t){assignClickMetricsFields(r,{targetId:e?.metrics?.impressions?.id});const t=e?.primaryOffer?.buyParams;assignClickMetricsFields(r,MetricsFieldsForAction.listenNowMusicSiriUpsellSelect(t))}else{logger$5.warn("Couldn't derive metrics fields without listenNowMusicSiriUpsell && impression");return null}return r}function onBagChange$1(){return getBagValue("metrics").then(e=>{mtMetricskit.system.configSources.setDelegate({sources:()=>[e]})})}let userType;const envDelegate=Object.assign({},environment$1,{userType:()=>userType});function getUserTypeFromAccountStatus(e){switch(e){case SubscriptionStatusResponse.ACCOUNT_STATUS.NEEDS_AUTHENTICATION:return"needsAuthentication";case SubscriptionStatusResponse.ACCOUNT_STATUS.NOT_SUBSCRIBED:return"notSubscribed";case SubscriptionStatusResponse.ACCOUNT_STATUS.SUBSCRIBED:case SubscriptionStatusResponse.ACCOUNT_STATUS.GLIDE:return"subscribed";case SubscriptionStatusResponse.ACCOUNT_STATUS.UNKNOWN:default:return"unknown"}}function onSubscriptionStatusChange(){getSubscriptionStatus().then(e=>{userType=getUserTypeFromAccountStatus(get(e,"accountStatus"))})}const METRICS_SAFE_ON_BECOMING_ACTIVE="METRICS_SAFE_ON_BECOMING_ACTIVE";const METRICS_SAFE_ON_RESIGNING_ACTIVE="METRICS_SAFE_ON_RESIGNING_ACTIVE";function initializeMetrics(){initializeNativeMetrics();initializeCarPlayMetics();onSubscriptionStatusChange();registerOnSubscriptionChange(onSubscriptionStatusChange);registerOnAccountChange((e,t)=>{if(t===Store.ACCOUNT_CHANGE_REASON.UNIQUE_IDENTIFIER_CHANGED){onSubscriptionStatusChange()}});mtMetricskit.system.environment.setDelegate(envDelegate);mtMetricskit.eventHandlers.flexible.setDelegate({mtIncludeBaseFields(){return true}});mtMetricskit.eventHandlers.click.setDelegate({eventVersion(e={}){return e.eventVersion||4}});mtMetricskit.system.eventRecorder.setDelegate(eventRecorder$2);mtMetricskit.system.logger.setDelegate(logger$5);onBagChange$1();registerOnBagChange(onBagChange$1);subscribe(METRICS_SAFE_ON_BECOMING_ACTIVE,()=>{logger$5.log("Recording metrics safe enter event.");if(!userType){getSubscriptionStatus().then(e=>{userType=getUserTypeFromAccountStatus(e?.accountStatus);recordEnter()})}else{recordEnter()}});subscribe(METRICS_SAFE_ON_RESIGNING_ACTIVE,()=>{logger$5.log("Recording metrics safe exit event. Flushing metrics.");recordExitAndFlush()})}const DEFAULT_POST_FREQUENCY=24*60*60*1e3;function isGreaterThanPostFrequency(e,t){return Date.now()-t>e}function createEventFromNative(e,t,r){const i=new Date;i.setHours(0,0,0,0);return{totalDuration:Math.round(e*1e3),playCount:t,eventTime:i.getTime(),actionContext:"CarPlay",rangeStartTime:r,rangeEndTime:Date.now()}}function reportBuyConfirmedEventFromCarplayUpsellIfNecessary(e){const t=e?.storeFlowSegue?.userInfo?.marketingMessageIdentifier;if(!t){logger$5.warn(`Did not enqueue buyConfirmed event because no marketingIdentifier or storeFlowSegue was found. options: '${JSON.stringify(e)}''`);return}logger$5.log(`Enqueueing buyConfirmed event with message id: '${t}'`);const r={pageContext:currentPageContext(),pageId:"CarPlayLibraryUpsell",pageType:"Modal",page:"Modal_CarPlayLibraryUpsell",messageId:t};recordFlexibleEvent("buyConfirmed",r)}function sanitizeAndStoreDeferredEvent(e){const t=sanitizeEventForPrivacyCompliance(e);const r={invocationDate:Date.now(),event:t};const i=Storage.getItem(StorageKeys.User.NON_SUBSCRIBER_CAR_PLAY_UPSELL_BATCHED_SANITIZED_EVENTS)||[];i.push(r);logger$5.log(`Event intercepted, stored, and sanitized. eventType: '${e.eventType}' pageId: '${e.pageId}' Enqueued event count: ${i.length}`);Storage.setItem(StorageKeys.User.NON_SUBSCRIBER_CAR_PLAY_UPSELL_BATCHED_SANITIZED_EVENTS,i)}function dispatchNonSubscriberCarPlayUpsellEventsIfNeeded(e){const t=Storage.getItem(StorageKeys.User.NON_SUBSCRIBER_CAR_PLAY_UPSELL_BATCHED_SANITIZED_EVENTS);if(!Array.isArray(t)){return}let r=0;t.slice().reverse().every(t=>{if(!isGreaterThanPostFrequency(e,t.invocationDate)){return false}r++;ungatedRecordEvent(t.event,UNIDENTIFIED_TOPIC);return true});let i=t;if(r){i=t.splice(r);logger$5.log(`Deferred events dispatched with count: ${r}. Remaining event count: ${i.length}`);Storage.setItem(StorageKeys.User.NON_SUBSCRIBER_CAR_PLAY_UPSELL_BATCHED_SANITIZED_EVENTS,i)}}function dispatchNonSubscriberCarPlayEventIfNeeded(e){const t=Storage.getWrappedItem(StorageKeys.User.NON_SUBSCRIBER_TRIAL_ELIGIBLE_DID_USE_CAR_PLAY);logger$5.log("hasUsedCarPlaySinceLastDispatch",t);if(!t){return}let r=Storage.getItem(StorageKeys.User.LAST_NON_SUBSCRIBER_TRIAL_ELIGIBLE_CAR_PLAY_EVENT_DISPATCH_TIME);if(!r){r=t.date}if(!isGreaterThanPostFrequency(e,r)){logger$5.log("No dispatching car play event becauase not enough time has elapsed since the last dispatch");return}const i={eventType:"hasUsedCarPlayAsTrialEligibleNonSubscriber"};reportEventForLocalEvaluation(i);Storage.setItem(StorageKeys.User.LAST_NON_SUBSCRIBER_TRIAL_ELIGIBLE_CAR_PLAY_EVENT_DISPATCH_TIME,Date.now());Storage.removeItem(StorageKeys.User.NON_SUBSCRIBER_TRIAL_ELIGIBLE_DID_USE_CAR_PLAY)}function flushIfNeeded(e){const t=StorageKeys.Device.CAR_PLAY_FIRST_EVENT_IN_BATCH_TIMESTAMP;const r=Storage.getRawItem(t);if(!r||!isGreaterThanPostFrequency(e,r)){return}const i=StorageKeys.Device.CAR_PLAY_BATCH_TIME_PLAYED;const n=StorageKeys.Device.CAR_PLAY_BATCH_TRACKS_PLAYED;const o=Storage.getRawItem(i);const s=Storage.getRawItem(n);const a=createEventFromNative(o,s,r);recordCarPlayEvent(a);Storage.setRawItem(i,0);Storage.setRawItem(n,0);Storage.removeRawItem(t)}function isEligibleForFreeTrial(e){const t=!get(e,"rawResponseData.music.isNotEligibleForFreeTrial",false);logger$5.log("Is free trial eligible: ",t);return t}function flushCarPlayEventsIfNeeded(){Promise.all([getBagValue('musicCommon["car-play-media-event-post-frequency"]'),getSubscriptionStatus()]).then(([e=DEFAULT_POST_FREQUENCY,t={}])=>{const r=parseInt(e,10);if(t.isSubscribed||hasVoiceAccount(t)){flushIfNeeded(r)}else if(isEligibleForFreeTrial(t)){dispatchNonSubscriberCarPlayEventIfNeeded(r)}dispatchNonSubscriberCarPlayUpsellEventsIfNeeded(r)}).catch(e=>logger$5.warn(e,"Car play bag key not present"))}function storeCarMetricsEvent(e){const{startTime:t=0,endTime:r=0}=e;const i=StorageKeys.Device.CAR_PLAY_BATCH_TIME_PLAYED;const n=StorageKeys.Device.CAR_PLAY_BATCH_TRACKS_PLAYED;const o=StorageKeys.Device.CAR_PLAY_FIRST_EVENT_IN_BATCH_TIMESTAMP;const s=Storage.getRawItem(o);const a=Math.abs(r-t);let l=Storage.getRawItem(i);if(!l){l=0}l+=a;let c=Storage.getRawItem(n);if(!c){c=0}c+=1;Storage.setRawItem(i,l);Storage.setRawItem(n,c);if(!s){Storage.setRawItem(o,Date.now())}}function handleNonSubscriberCarPlayTrialEligibleEvent(){const e=Storage.getItem(StorageKeys.User.NON_SUBSCRIBER_TRIAL_ELIGIBLE_DID_USE_CAR_PLAY);logger$5.log("hasUsedCarPlaySinceLastDispatch",e);if(!e){Storage.setItem(StorageKeys.User.NON_SUBSCRIBER_TRIAL_ELIGIBLE_DID_USE_CAR_PLAY,true);logger$5.log("did set item ",StorageKeys.User.NON_SUBSCRIBER_TRIAL_ELIGIBLE_DID_USE_CAR_PLAY)}}function onRecordCarMetricsNativeEvent(e){logger$5.log("onRecordCarMetricsNativeEvent was called: ",e);getSubscriptionStatus().then((t={})=>{if(t.isSubscribed||hasVoiceAccount(t)){storeCarMetricsEvent(e)}else if(isEligibleForFreeTrial(t)){handleNonSubscriberCarPlayTrialEligibleEvent()}})}function onBecomingActive(){flushCarPlayEventsIfNeeded()}function initializeCarPlayMetics(){registerGlobalCallback(MetricsController,"onRecordCarMetricsNativeEvent",onRecordCarMetricsNativeEvent);subscribe(METRICS_SAFE_ON_BECOMING_ACTIVE,onBecomingActive)}function sendMethod(){return"musicjs"}function removeClientIdsFromEvent(e){const t=["clientId","analyticsClientId"];const r=cloneDeep(e);t.forEach(e=>{delete r[e]});return r}function recordEvent(e,t,r,i){let n;const o=r!==false&&e!==LOGGING_TOPIC;const s=i!==false&&e!==LOGGING_TOPIC;if(t&&!mtMetricskit.config.metricsDisabledOrBlacklistedEvent(t.eventType)){mtMetricskit.config.removeBlacklistedFields(t);if(s&&shouldDeferSendingEvent(t)){sanitizeAndStoreDeferredEvent(t)}else if(e===CAR_PLAY_TOPIC){MetricsController.recordCarMetricsEvent(e,removeClientIdsFromEvent(t),o)}else{MetricsController.recordEvent(e,removeClientIdsFromEvent(t),o)}n=t}return n}var eventRecorder$2={sendMethod:sendMethod,recordEvent:recordEvent};const LOGGING_TOPIC="xp_amp_music_log";const SESSION_ID_SYMBOL=Symbol("session");class SplunkLogger extends Logger$1{constructor(...e){super(...e);mtLoggerkit.eventRecorder.setDelegate(eventRecorder$2);this.logger=mtLoggerkit.loggerNamed("music-js-logging");this.logger.setTopic(LOGGING_TOPIC);this.logger.setDelegate({error:(...e)=>{e.push(this.logger.SUPPRESS_CLIENT_OUTPUT);this.logger.error.origFunction(...e)}});this.hasWonLottery=isInternalInstall()||Math.random()<.01}get error(){return super.error}set error(e){super.error=(...e)=>{this.logErrorMessage(...e)}}get sessionId(){return this[SESSION_ID_SYMBOL]}set sessionId(e){this[SESSION_ID_SYMBOL]=e}get shouldLogErrorsToTheServer(){return this.loggingToServerEnabled&&this.hasWonLottery}logErrorMessage(...e){const t=e.map(e=>String(e)).join(" ");const r={message:t,musicJSVersion:this.musicJSVersion,sessionId:this.sessionId};const i=[r];if(this.shouldLogErrorsToTheServer){i.push(this.logger.MIRROR_TO_SERVER)}console.error(...e);this.logger.error(...i)}}function createUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;const r=e==="x"?t:t&3|8;return r.toString(16)})}const logger$5=new SplunkLogger({level:4,loggingToServerEnabled:Application.isDeployedScript,musicJSVersion:config$3.version,sessionId:createUUID()});class SubscriptionStatusRequestError extends Error{constructor(e=""){super(e||SubscriptionStatusRequestError.constructMessage())}static get name(){return"SubscriptionStatusRequestError"}static constructMessage(){return"Unable to fetch subscription status"}}function waitForSubscriptionStatusChange(){return new Promise(e=>{const subscriptionStatusDidChange=()=>{unregisterOnSubscriptionChange(subscriptionStatusDidChange);e()};registerOnSubscriptionChange(subscriptionStatusDidChange)})}function performSubscriptionStatusRequest(e,t=false){return new Promise((r,i)=>{const n=new SubscriptionStatusRequest;n.reason=e;n.ignoreCache=t;n.wantsPartialResults=false;n.onResponse=e=>{if(e){Application.subscriptionStatusSync=e?.isSubscribed;r(e)}else{i(new SubscriptionStatusRequestError)}};n.send()})}function getSubscriptionStatusSync(){return Application.subscriptionStatusSync}function fetchSubscriptionStatus(e,t=false){return performSubscriptionStatusRequest(e,t).catch(r=>{logger$5.log(`Subscription status error, ${r} - will retry when subscripition status updates`);return waitForSubscriptionStatusChange().then(()=>{logger$5.log("Subscription status changed after error");return performSubscriptionStatusRequest(e,t)})})}function hasOwnProperty$a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var decode=function(e,t,r,i){t=t||"&";r=r||"=";var n={};if(typeof e!=="string"||e.length===0){return n}var o=/\+/g;e=e.split(t);var s=1e3;if(i&&typeof i.maxKeys==="number"){s=i.maxKeys}var a=e.length;if(s>0&&a>s){a=s}for(var l=0;l=0){d=c.substr(0,u);g=c.substr(u+1)}else{d=c;g=""}h=decodeURIComponent(d);f=decodeURIComponent(g);if(!hasOwnProperty$a(n,h)){n[h]=f}else if(isArray$1(n[h])){n[h].push(f)}else{n[h]=[n[h],f]}}return n};var isArray$1=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};var stringifyPrimitive=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};var encode=function(e,t,r,i){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return map(objectKeys(e),(function(i){var n=encodeURIComponent(stringifyPrimitive(i))+r;if(isArray$2(e[i])){return map(e[i],(function(e){return n+encodeURIComponent(stringifyPrimitive(e))})).join(t)}else{return n+encodeURIComponent(stringifyPrimitive(e[i]))}})).join(t)}if(!i)return"";return encodeURIComponent(stringifyPrimitive(i))+r+encodeURIComponent(stringifyPrimitive(e))};var isArray$2=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};function map(e,t){if(e.map)return e.map(t);var r=[];for(var i=0;i0){const r=e.indexOf("?")!==-1;e=`${e}${r?"&":"?"}${querystringEs3.encode(t)}`}return e}function baseURLFromApplicationScriptURL(e){let t=e;const r=t.lastIndexOf("/");const i=r===t.length-1;if(!i){t=t.substring(0,r+1)}const n="js/";const o=t.lastIndexOf(n);const s=o===t.length-n.length;if(s){t=t.substring(0,o)}return t}const localizedStrings={};const durationISORegex=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;function replace(e,t,r){let i=e;if(i){if(typeof i!=="string"){i=String(i)}i=i.split(t).join(r)}return i}function replaceTokens(e,t){let r=e;if(t){Object.keys(t).forEach(e=>{r=replace(r,`@@${e}@@`,t[e])})}return r}let isAppLocalizationInitialized=false;let appLocalizationError=null;let pendingLocalizationPromises=[];function onLocalizationInitialized(e,t){if(e){logger$5.log("Localization resource loaded with",`${Object.keys(e).length} strings`);Object.assign(localizedStrings,e)}isAppLocalizationInitialized=true;if(t){logger$5.error("Localization failed to initialize",t)}pendingLocalizationPromises.forEach(({resolve:e,reject:r})=>{if(t){r(t)}else{e()}});appLocalizationError=t;pendingLocalizationPromises=[]}function waitForLocInitialization(){if(isAppLocalizationInitialized){return appLocalizationError?Promise.reject(appLocalizationError):Promise.resolve()}return new Promise((e,t)=>{pendingLocalizationPromises.push({resolve:e,reject:t})})}function localizationResourcePathForBagLanguageTag(e){let t=e.toLowerCase();let r=config$3.localizationResourceForLocale[t];if(!r){logger$5.error(`No localization file for ${t} from bag language-tag ${e}`);t="en-us";r=config$3.localizationResourceForLocale[t]}const i=config$3.resourceManifest.resources[r];logger$5.log("Selected localization resource",t,i);return i}function persistLocalizedStrings(e,t){Persistence.localStorage.setItem(StorageKeys.Device.LOCALIZED_STRINGS,{[t]:e})}function getPersistedLocalizedStrings(e){const t=Persistence.localStorage.getItem(StorageKeys.Device.LOCALIZED_STRINGS);if(!t){return null}if(e){return t[e]||null}const r=Object.keys(t)[0];if(!r){return null}return t[r]||null}function fetchAndPersistLocalization(e,t){const r=getPersistedLocalizedStrings(e);if(r){logger$5.log("Retrieved localization from local storage.");return Promise.resolve(r)}const i=baseURLFromApplicationScriptURL(t);const n=i+e;return fetch(n).then(t=>{const r=t.performanceMetrics;if(r&&typeof r==="object"){delete t.performanceMetrics;const{requestStartTime:e,responseEndTime:i}=r;if(typeof e==="number"&&typeof i==="number"){const t=(i-e)/1e3;logger$5.log("Fetched localization in",`${t}s`)}}persistLocalizedStrings(t.body,e);return t.body}).catch(e=>{const t=getPersistedLocalizedStrings();if(t){logger$5.error("Failed to load localization resource. Falling back on out-of-date persisted localized strings.",e);return t}throw e})}function initializeLocalization(e){isAppLocalizationInitialized=false;appLocalizationError=null;return getBagValue("language-tag").then(localizationResourcePathForBagLanguageTag).then(t=>fetchAndPersistLocalization(t,e)).then(onLocalizationInitialized).catch(e=>{onLocalizationInitialized(null,e)})}function localize(e,t){let r=e;if(!isAppLocalizationInitialized){logger$5.error("Localization not initialized before call to localize() with key:",r);return replaceTokens(r,t)}const i=getBagValueSync("currentStorefrontCountryCodeISO3A");const n=get(config$3,["localizableStringsStorefrontOverrides",r,i]);if(n){r=n}const o=localizedStrings[r];if(o===undefined){if(appLocalizationError){logger$5.error("Localization failed, unable to localize key:",r)}else{logger$5.error("Localization key missing from localizable-strings.json:",r)}return replaceTokens(r,t)}if(o===`**${r}**`){logger$5.error("Localization missing for key:",r)}return replaceTokens(o,t)}function parseIso(e){const t=e&&parseFloat(e.replace(",","."));return isNaN(t)?0:t}function parseISODuration(e=""){const t=durationISORegex.exec(e);if(!t){return null}const r=parseIso(t[2]);const i=parseIso(t[3]);const n=parseIso(t[4]);const o=parseIso(t[5]);return{years:r,months:i,weeks:n,days:o}}function getDurationNum(e={}){return e.years||e.months||e.weeks||e.days}function durationLocString(e={},t){let r="Finance.Duration";const i=getDurationNum(e);if(e.years){r+=".Years"}else if(e.months){r+=".Months"}else if(e.weeks){r+=".Weeks"}else if(e.days){r+=".Days"}if(t){r+=".Cap"}if(i===1){r+=".One"}return localize(r,{num:i})}function locWithIntroPricing(e="",t={},r){let i;const n=parseFloat(t.price)||0;const o=r||t.priceForDisplay;const s=t.period||t.freeTrialPeriod||t.introOfferPeriod;const a=parseISODuration(s);const l=a?.months===6;if(l){return null}if(a&&o){const t=durationLocString(a,false);const r=durationLocString(a,true);let s=".PX";if(a.years){s+="Y"}else if(a.months){s+="M"}else if(a.weeks){s+="W"}else if(a.days){s+="D"}if(n!==0){s+="Y"}e+=s;const l={introPrice:o,introPricing:o,intropricingduration:t,introPricingDuration:r};i=localize(e,l)}else{i=localize(e)}return i}const onOpenURLCallbacks=new Set;function callOnOpenURLCallbacks(e,t,r){onOpenURLCallbacks.forEach(i=>i(e,t,r))}function registerOnOpenURLCallback(e){if(typeof Application.onOpenURL!=="function"){Application.onOpenURL=callOnOpenURLCallbacks}else if(Application.onOpenURL!==callOnOpenURLCallbacks){console.warn("Application.onOpenURL has already been set outside of registerOnOpenURLCallback, registerOnOpenURLCallback may not behave as expected.")}onOpenURLCallbacks.add(e)}let activationMethod;registerGlobalCallback(Application,"onLaunch",e=>{activationMethod=e.activationMethod});function restrictsExplicitContent(){if(Restrictions.allowsExplicitContent===undefined){return undefined}return!Restrictions.allowsExplicitContent}function restrictsMusicVideos(){if(Restrictions.allowsMusicVideos===undefined){return undefined}return!Restrictions.allowsMusicVideos}function restrictsMusicSubscription(){if(Restrictions.allowsMusicSubscription===undefined){return undefined}return!Restrictions.allowsMusicSubscription}function registerOnExplicitContentChange(e){registerGlobalCallback(Restrictions,"onAllowsExplicitContentChange",e)}function registerOnAllowsMusicVideosChange(e){registerGlobalCallback(Restrictions,"onAllowsMusicVideosChange",e)}const SUBSCRIBER_COOKIE_UPDATED="SUBSCRIBER_COOKIE_UPDATED";function updateExplicitCookie(){const e=restrictsExplicitContent();if(e===undefined){return}if(e){logger$5.log("Restrictions: Explicit content restricted.")}return getBagValue("isExplicitMusicDisallowed").catch(e=>{let t;if(e instanceof BagError){t=false}else{throw e}return t}).then(e=>{const t=e||restrictsExplicitContent();let r;const i={domain:".apple.com",path:"/"};if(t){r=setCookie("itre","1",i)}else{r=deleteCookie("itre",i)}return r}).catch(e=>logger$5.error(e))}function updateAllowsMusicVideosCookie(){const e=restrictsMusicVideos();if(e===undefined){return}if(e){logger$5.log("Restrictions: Music videos restricted.")}let t;const r={domain:".apple.com",path:"/"};if(e){t=setCookie("itrv","1",r)}else{t=deleteCookie("itrv",r)}return t}function updateSubscriberCookie(){return hasSubscription().then(e=>{const t=hasOptedOutOfSubscription();const r={domain:".apple.com",path:"/"};let i;if(t){i=setCookie("itst","1",r)}else if(e){i=setCookie("itst","2",r)}else{i=deleteCookie("itst",r)}return i}).catch(e=>logger$5.error(e))}function registerOnActiveCookiesForDefaultURLChange(e){registerGlobalCallback(Persistence.cookieStorage,"onActiveCookiesChangeForDefaultURL",e)}function onActiveCookiesForDefaultURLChange(e){logger$5.log(`Cookies changed to ${JSON.stringify(e)}`)}function updateCookies(){updateExplicitCookie();updateSubscriberCookie();updateAllowsMusicVideosCookie()}function initializeCookies(){const publishCookieUpdate=()=>{publish(SUBSCRIBER_COOKIE_UPDATED)};registerOnBagChange(updateExplicitCookie);registerOnHasUserRequestedSubscriptionHiddenChange(updateSubscriberCookie);registerOnSubscriptionChange(()=>{updateSubscriberCookie().then(()=>publishCookieUpdate())});registerOnAccountChange((e,t)=>{if(t===Store.ACCOUNT_CHANGE_REASON.UNIQUE_IDENTIFIER_CHANGED){return updateSubscriberCookie().then(()=>publishCookieUpdate())}});registerOnExplicitContentChange(updateExplicitCookie);registerOnAllowsMusicVideosChange(updateAllowsMusicVideosCookie);registerOnActiveCookiesForDefaultURLChange(onActiveCookiesForDefaultURLChange);updateCookies()}const PLAY_ACTIVITY_TOPIC="PLAY_ACTIVITY_TOPIC";const PLAY_DELAY=500;function initializePlayActivity(){PlayActivityController.onEventFlush=e=>{if(e){const e=new Timer;e.delay=PLAY_DELAY;e.onTimeout=()=>{publish(PLAY_ACTIVITY_TOPIC,{})};e.schedule()}}}const PUSH_NOTIFICATION_TOPIC="com.apple.itunesstored";function initializePushNotifications(){PushNotificationObserver.addTopicObserver(PUSH_NOTIFICATION_TOPIC,e=>publish(PLAY_ACTIVITY_TOPIC,e))}const cache={};const SIMPLE_PROFILES=["lockup"];function cacheContent(e,t){if(!cache[e]){cache[e]={}}Object.assign(cache[e],t);if(SIMPLE_PROFILES.indexOf(e)===-1){SIMPLE_PROFILES.forEach(e=>cacheContent(e,t))}}function peekContent(e){const{ids:t=[],profile:r="lockup"}=e;return new Promise$1(e=>{const i=t.reduce((e,t)=>{e[t]=get(cache,[r,t]);return e},{});e(i)})}function fetchAndCache(e){const{profile:t,shouldCacheStorePlatformData:r=true}=e;return fetchStoreContent(e).then(e=>{if(r){cacheContent(t,e)}return e})}function fetchContent(e){const{ids:t=[],profile:r="lockup",isPersonalized:i=false,shouldCacheStorePlatformData:n=true,forceRefresh:o=false}=e;let s;if(o){s=fetchAndCache(e)}else{const e=[];const o=[];t.forEach(t=>{const i=get(cache,[r,t])?e:o;i.push(t)});s=Promise$1.all([peekContent({ids:e,profile:r,isPersonalized:i}),fetchAndCache({ids:o,profile:r,isPersonalized:i,shouldCacheStorePlatformData:n})]).then(([e,t])=>Object.assign({},e,t))}return s}function cacheStorePlatformData(e={}){const t=Object.keys(e);if(t.length>1){t.sort((e,t)=>{let r=0;const i=SIMPLE_PROFILES.indexOf(e)===-1;const n=SIMPLE_PROFILES.indexOf(t)===-1;if(i&&!n){r=-1}else if(n&&!i){r=1}return r})}t.forEach(t=>{cacheContent(t,e[t].results)})}function registerOnFollowStateDidChange(e){registerGlobalCallback(SocialActivityController,"onFollowStateDidChange",e)}function unregisterOnFollowStateDidChange(e){removeGlobalCallback(SocialActivityController,"onFollowStateDidChange",e)}function registerOnFollowApprovalDidChange(e){registerGlobalCallback(SocialActivityController,"onFollowApprovalDidChange",e)}function unregisterOnFollowApprovalDidChange(e){removeGlobalCallback(SocialActivityController,"onFollowApprovalDidChange",e)}function registerOnDidApproveAll(e){registerGlobalCallback(SocialActivityController,"onDidApproveAll",e)}function unregisterOnDidApproveAll(e){removeGlobalCallback(SocialActivityController,"onDidApproveAll",e)}function registerOnRemovedFollower(e){registerGlobalCallback(SocialActivityController,"onRemovedFollower",e)}function unregisterOnRemovedFollower(e){removeGlobalCallback(SocialActivityController,"onRemovedFollower",e)}function createStoreFlowSegue(e){return Object.assign(new StoreFlowSegue,e)}const URLPatterns={LEGACY_FINANCE_APP:{bagKey:"commerce-ui-urls.url-patterns",fallbackPatterns:["(?:account|redeem|redeemLandingPage|freeProductCodeWizard|showDialogForRedeem|webobjects/mzfinance.woa)([/?&]|$)","^https?://finance-app[.]itunes[.]apple[.]com([/?]|$)"],trustedDomains:["finance-app.itunes.apple.com"]},COMMERCE_APP:{bagKey:"commerce-ui-urls.v2-url-patterns",fallbackPatterns:["(?:54a1317a0ad442d3965d64ef6bfaae1c)([/?]|$)","WebObjects/MZFinance.woa/.*/(manageSubscriptions)"],trustedDomains:["apps.mzstatic.com/content/54a1317a0ad442d3965d64ef6bfaae1c"]},AMS_DYNAMIC:{bagKey:"commerce-ui-urls.dynamic-url-patterns",fallbackPatterns:["amsui[.]apple[.]com/dynamic/marketing([/?#]|$)","one[.]apple[.]com([/?]|$)","(?:apps|tv|fitness|music).apple.com(?:/\\w+/carrier)(?:[?]|$)","(?:tv|music|app).apple.com(?:/\\w+/subscription/link)(?:[?]|$)"],trustedDomains:["amsui.apple.com","one.apple.com","music.apple.com"]},CONTENT:{fallbackPatterns:["music[.]apple[.]com/[a-z]{2}/(album|playlist)"],trustedDomains:["music.apple.com"]}};function patternMatchingURLMatchesPatterns(e,t){if(!e||!t){return false}const r=t.find(t=>{const r=new RegExp(t,"i");return r.test(e)});return!!r}const URLPatternMatcher={TYPES:{FINANCE_APP_TYPE:"FINANCE_APP_TYPE",COMMERCE_APP_TYPE:"COMMERCE_APP_TYPE",AMS_DYNAMIC_TYPE:"AMS_DYNAMIC_TYPE",CONTENT_TYPE:"CONTENT_TYPE",UNKNOWN_TYPE:"UNKNOWN_TYPE"},isURLLegacyFinanceURL(e){if(!e){return false}const t=URLPatterns.LEGACY_FINANCE_APP;const r=getBagValueSync(t.bagKey,t.fallbackPatterns);return patternMatchingURLMatchesPatterns(e,r)},isURLCommerceAppURL(e){if(!e){return false}const t=URLPatterns.COMMERCE_APP;const r=getBagValueSync(t.bagKey,t.fallbackPatterns);return patternMatchingURLMatchesPatterns(e,r)},isURLAMSDynamicURL(e){if(!e){return false}const t=URLPatterns.AMS_DYNAMIC;const r=getBagValueSync(t.bagKey,t.fallbackPatterns);return patternMatchingURLMatchesPatterns(e,r)},isURLContentURL(e){if(!e){return false}const t=URLPatterns.CONTENT;return patternMatchingURLMatchesPatterns(e,t.fallbackPatterns)},typeForURL(e){if(this.isURLLegacyFinanceURL(e)){return this.TYPES.FINANCE_APP_TYPE}else if(this.isURLCommerceAppURL(e)){return this.TYPES.COMMERCE_APP_TYPE}else if(this.isURLAMSDynamicURL(e)){return this.TYPES.AMS_DYNAMIC_TYPE}else if(this.isURLContentURL(e)){return this.TYPES.CONTENT_TYPE}return this.TYPES.UNKNOWN_TYPE},trustedDomainForType(e){switch(e){case this.TYPES.FINANCE_APP_TYPE:return URLPatterns.LEGACY_FINANCE_APP.trustedDomains;case this.TYPES.COMMERCE_APP_TYPE:return URLPatterns.COMMERCE_APP.trustedDomains;case this.TYPES.AMS_DYNAMIC_TYPE:return URLPatterns.AMS_DYNAMIC.trustedDomains;case this.TYPES.CONTENT_TYPE:return URLPatterns.CONTENT.trustedDomains;case this.TYPES.UNKNOWN_TYPE:default:return[]}}};let isNotEligibleForFreeTrial=false;function onSubscriptionStatusChange$1(){return getSubscriptionStatus().then(e=>{isNotEligibleForFreeTrial=get(e,"rawResponseData.music.isNotEligibleForFreeTrial",false)})}function createState(){let e;if(isUserSignedIn()){if(isNotEligibleForFreeTrial){e="FormerFreeTrial"}else if(hasOptedOutOfSubscription()){e="NoThanks"}}return e}function constructFinanceFlowURL(e="",t="",r=""){const i=t.indexOf("?")!==-1;const n=i?r.replace("?","&"):r;return e+t+n}function createFinanceSegue(e,t={}){const r={url:e,sourceApplicationBundleIdentifier:t.refApp,referrerURL:t.extRefUrl,userInfo:{originalUrl:t.originalUrl,storePlatformDictionary:t.storePlatformDictionary,reason:t.reason,state:createState(),currentTab:currentPageContext()}};if(URLPatternMatcher.isURLLegacyFinanceURL(e)){logger$5.log("StoreFlowSegue: Disabled camera redemption for legacy URL",e);set(r,"userInfo.musicRedeemCameraAvailable",false)}return createStoreFlowSegue(r)}function createFinanceURLForPathName(e={},t=[],r="/",i="",n=""){const{urlPath:o={}}=e;const s=t.reduce((e,t)=>{const r=o[t]||{};Object.keys(r).forEach(t=>{e[t.toLowerCase()]=r[t]});return e},{});const a=r.indexOf("/")===0?r.slice(1).toLowerCase():r.toLowerCase();let l=s[a];if(!l){Object.keys(s).forEach(e=>{if(a.indexOf(e)!==-1){l=s[e]}})}if(!l){return}let c=constructFinanceFlowURL(e.baseUrl,l,i);if(n){c+=n}return c}createFinanceURLForPathName.DEFAULT_URL_PATH_KEYS=["musicDeeplinks","musicInternal"];function initializeFinanceDeeplinks(){registerOnHasUserRequestedSubscriptionHiddenChange(onSubscriptionStatusChange$1);registerOnSubscriptionChange(onSubscriptionStatusChange$1);onSubscriptionStatusChange$1()}function createOnboardingViewModel(e){return Object.assign(new OnboardingViewModel,e)}function requestMusicAPIResource(e,t={}){return fetchJSON(e,Object.assign({},t,{isMusicAPIRequest:true}))}function requestMusicAPIResponse(e,t={}){return fetch(e,Object.assign({},t,{isMusicAPIRequest:true}))}const parametersSymbol=Symbol("parameters");class QueryString{get parameters(){let e=this[parametersSymbol];if(!e){e={};this[parametersSymbol]=e}return e}set parameters(e){this[parametersSymbol]=e}addParameters(e){Object.assign(this.parameters,e)}object(){return Promise.resolve(Object.assign({},this.parameters))}}var moment=createCommonjsModule((function(e,t){(function(t,r){e.exports=r()})(commonjsGlobal,(function(){var t;function hooks(){return t.apply(null,arguments)}function setHookCallback(e){t=e}function isArray(e){return e instanceof Array||Object.prototype.toString.call(e)==="[object Array]"}function isObject(e){return e!=null&&Object.prototype.toString.call(e)==="[object Object]"}function isObjectEmpty(e){if(Object.getOwnPropertyNames){return Object.getOwnPropertyNames(e).length===0}else{var t;for(t in e){if(e.hasOwnProperty(t)){return false}}return true}}function isUndefined(e){return e===void 0}function isNumber(e){return typeof e==="number"||Object.prototype.toString.call(e)==="[object Number]"}function isDate(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function map(e,t){var r=[],i;for(i=0;i>>0;for(var i=0;i0){for(r=0;r0?"future":"past"];return isFunction(r)?r(t):r.replace(/%s/i,t)}var h={};function addUnitAlias(e,t){var r=e.toLowerCase();h[r]=h[r+"s"]=h[t]=e}function normalizeUnits(e){return typeof e==="string"?h[e]||h[e.toLowerCase()]:undefined}function normalizeObjectUnits(e){var t={},r,i;for(i in e){if(hasOwnProp(e,i)){r=normalizeUnits(i);if(r){t[r]=e[i]}}}return t}var f={};function addUnitPriority(e,t){f[e]=t}function getPrioritizedUnits(e){var t=[];for(var r in e){t.push({unit:r,priority:f[r]})}t.sort((function(e,t){return e.priority-t.priority}));return t}function zeroFill(e,t,r){var i=""+Math.abs(e),n=t-i.length,o=e>=0;return(o?r?"+":"":"-")+Math.pow(10,Math.max(0,n)).toString().substr(1)+i}var p=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;var m=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;var S={};var I={};function addFormatToken(e,t,r,i){var n=i;if(typeof i==="string"){n=function(){return this[i]()}}if(e){I[e]=n}if(t){I[t[0]]=function(){return zeroFill(n.apply(this,arguments),t[1],t[2])}}if(r){I[r]=function(){return this.localeData().ordinal(n.apply(this,arguments),e)}}}function removeFormattingTokens(e){if(e.match(/\[[\s\S]/)){return e.replace(/^\[|\]$/g,"")}return e.replace(/\\/g,"")}function makeFormatFunction(e){var t=e.match(p),r,i;for(r=0,i=t.length;r=0&&m.test(e)){e=e.replace(m,replaceLongDateFormatTokens);m.lastIndex=0;r-=1}return e}var C=/\d/;var y=/\d\d/;var P=/\d{3}/;var E=/\d{4}/;var T=/[+-]?\d{6}/;var b=/\d\d?/;var A=/\d\d\d\d?/;var M=/\d\d\d\d\d\d?/;var R=/\d{1,3}/;var w=/\d{1,4}/;var _=/[+-]?\d{1,6}/;var v=/\d+/;var D=/[+-]?\d+/;var F=/Z|[+-]\d\d:?\d\d/gi;var O=/Z|[+-]\d\d(?::?\d\d)?/gi;var L=/[+-]?\d+(\.\d{1,3})?/;var k=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;var U={};function addRegexToken(e,t,r){U[e]=isFunction(t)?t:function(e,i){return e&&r?r:t}}function getParseRegexForToken(e,t){if(!hasOwnProp(U,e)){return new RegExp(unescapeFormat(e))}return U[e](t._strict,t._locale)}function unescapeFormat(e){return regexEscape(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,(function(e,t,r,i,n){return t||r||i||n})))}function regexEscape(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var N={};function addParseToken(e,t){var r,i=t;if(typeof e==="string"){e=[e]}if(isNumber(t)){i=function(e,r){r[t]=toInt(e)}}for(r=0;r68?1900:2e3)};var W=makeGetSet("FullYear",true);function getIsLeapYear(){return isLeapYear(this.year())}function makeGetSet(e,t){return function(r){if(r!=null){set$1(this,e,r);hooks.updateOffset(this,t);return this}else{return get(this,e)}}}function get(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function set$1(e,t,r){if(e.isValid()&&!isNaN(r)){if(t==="FullYear"&&isLeapYear(e.year())&&e.month()===1&&e.date()===29){e._d["set"+(e._isUTC?"UTC":"")+t](r,e.month(),daysInMonth(r,e.month()))}else{e._d["set"+(e._isUTC?"UTC":"")+t](r)}}}function stringGet(e){e=normalizeUnits(e);if(isFunction(this[e])){return this[e]()}return this}function stringSet(e,t){if(typeof e==="object"){e=normalizeObjectUnits(e);var r=getPrioritizedUnits(e);for(var i=0;i=0){a=new Date(e+400,t,r,i,n,o,s);if(isFinite(a.getFullYear())){a.setFullYear(e)}}else{a=new Date(e,t,r,i,n,o,s)}return a}function createUTCDate(e){var t;if(e<100&&e>=0){var r=Array.prototype.slice.call(arguments);r[0]=e+400;t=new Date(Date.UTC.apply(null,r));if(isFinite(t.getUTCFullYear())){t.setUTCFullYear(e)}}else{t=new Date(Date.UTC.apply(null,arguments))}return t}function firstWeekOffset(e,t,r){var i=7+t-r,n=(7+createUTCDate(e,0,i).getUTCDay()-t)%7;return-n+i-1}function dayOfYearFromWeeks(e,t,r,i,n){var o=(7+r-i)%7,s=firstWeekOffset(e,i,n),a=1+7*(t-1)+o+s,l,c;if(a<=0){l=e-1;c=daysInYear(l)+a}else if(a>daysInYear(e)){l=e+1;c=a-daysInYear(e)}else{l=e;c=a}return{year:l,dayOfYear:c}}function weekOfYear(e,t,r){var i=firstWeekOffset(e.year(),t,r),n=Math.floor((e.dayOfYear()-i-1)/7)+1,o,s;if(n<1){s=e.year()-1;o=n+weeksInYear(s,t,r)}else if(n>weeksInYear(e.year(),t,r)){o=n-weeksInYear(e.year(),t,r);s=e.year()+1}else{s=e.year();o=n}return{week:o,year:s}}function weeksInYear(e,t,r){var i=firstWeekOffset(e,t,r),n=firstWeekOffset(e+1,t,r);return(daysInYear(e)-i+n)/7}addFormatToken("w",["ww",2],"wo","week");addFormatToken("W",["WW",2],"Wo","isoWeek");addUnitAlias("week","w");addUnitAlias("isoWeek","W");addUnitPriority("week",5);addUnitPriority("isoWeek",5);addRegexToken("w",b);addRegexToken("ww",b,y);addRegexToken("W",b);addRegexToken("WW",b,y);addWeekParseToken(["w","ww","W","WW"],(function(e,t,r,i){t[i.substr(0,1)]=toInt(e)}));function localeWeek(e){return weekOfYear(e,this._week.dow,this._week.doy).week}var ee={dow:0,doy:6};function localeFirstDayOfWeek(){return this._week.dow}function localeFirstDayOfYear(){return this._week.doy}function getSetWeek(e){var t=this.localeData().week(this);return e==null?t:this.add((e-t)*7,"d")}function getSetISOWeek(e){var t=weekOfYear(this,1,4).week;return e==null?t:this.add((e-t)*7,"d")}addFormatToken("d",0,"do","day");addFormatToken("dd",0,0,(function(e){return this.localeData().weekdaysMin(this,e)}));addFormatToken("ddd",0,0,(function(e){return this.localeData().weekdaysShort(this,e)}));addFormatToken("dddd",0,0,(function(e){return this.localeData().weekdays(this,e)}));addFormatToken("e",0,0,"weekday");addFormatToken("E",0,0,"isoWeekday");addUnitAlias("day","d");addUnitAlias("weekday","e");addUnitAlias("isoWeekday","E");addUnitPriority("day",11);addUnitPriority("weekday",11);addUnitPriority("isoWeekday",11);addRegexToken("d",b);addRegexToken("e",b);addRegexToken("E",b);addRegexToken("dd",(function(e,t){return t.weekdaysMinRegex(e)}));addRegexToken("ddd",(function(e,t){return t.weekdaysShortRegex(e)}));addRegexToken("dddd",(function(e,t){return t.weekdaysRegex(e)}));addWeekParseToken(["dd","ddd","dddd"],(function(e,t,r,i){var n=r._locale.weekdaysParse(e,i,r._strict);if(n!=null){t.d=n}else{getParsingFlags(r).invalidWeekday=e}}));addWeekParseToken(["d","e","E"],(function(e,t,r,i){t[i]=toInt(e)}));function parseWeekday(e,t){if(typeof e!=="string"){return e}if(!isNaN(e)){return parseInt(e,10)}e=t.weekdaysParse(e);if(typeof e==="number"){return e}return null}function parseIsoWeekday(e,t){if(typeof e==="string"){return t.weekdaysParse(e)%7||7}return isNaN(e)?null:e}function shiftWeekdays(e,t){return e.slice(t,7).concat(e.slice(0,t))}var te="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_");function localeWeekdays(e,t){var r=isArray(this._weekdays)?this._weekdays:this._weekdays[e&&e!==true&&this._weekdays.isFormat.test(t)?"format":"standalone"];return e===true?shiftWeekdays(r,this._week.dow):e?r[e.day()]:r}var re="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");function localeWeekdaysShort(e){return e===true?shiftWeekdays(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort}var ie="Su_Mo_Tu_We_Th_Fr_Sa".split("_");function localeWeekdaysMin(e){return e===true?shiftWeekdays(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin}function handleStrictParse$1(e,t,r){var i,n,o,s=e.toLocaleLowerCase();if(!this._weekdaysParse){this._weekdaysParse=[];this._shortWeekdaysParse=[];this._minWeekdaysParse=[];for(i=0;i<7;++i){o=createUTC([2e3,1]).day(i);this._minWeekdaysParse[i]=this.weekdaysMin(o,"").toLocaleLowerCase();this._shortWeekdaysParse[i]=this.weekdaysShort(o,"").toLocaleLowerCase();this._weekdaysParse[i]=this.weekdays(o,"").toLocaleLowerCase()}}if(r){if(t==="dddd"){n=K.call(this._weekdaysParse,s);return n!==-1?n:null}else if(t==="ddd"){n=K.call(this._shortWeekdaysParse,s);return n!==-1?n:null}else{n=K.call(this._minWeekdaysParse,s);return n!==-1?n:null}}else{if(t==="dddd"){n=K.call(this._weekdaysParse,s);if(n!==-1){return n}n=K.call(this._shortWeekdaysParse,s);if(n!==-1){return n}n=K.call(this._minWeekdaysParse,s);return n!==-1?n:null}else if(t==="ddd"){n=K.call(this._shortWeekdaysParse,s);if(n!==-1){return n}n=K.call(this._weekdaysParse,s);if(n!==-1){return n}n=K.call(this._minWeekdaysParse,s);return n!==-1?n:null}else{n=K.call(this._minWeekdaysParse,s);if(n!==-1){return n}n=K.call(this._weekdaysParse,s);if(n!==-1){return n}n=K.call(this._shortWeekdaysParse,s);return n!==-1?n:null}}}function localeWeekdaysParse(e,t,r){var i,n,o;if(this._weekdaysParseExact){return handleStrictParse$1.call(this,e,t,r)}if(!this._weekdaysParse){this._weekdaysParse=[];this._minWeekdaysParse=[];this._shortWeekdaysParse=[];this._fullWeekdaysParse=[]}for(i=0;i<7;i++){n=createUTC([2e3,1]).day(i);if(r&&!this._fullWeekdaysParse[i]){this._fullWeekdaysParse[i]=new RegExp("^"+this.weekdays(n,"").replace(".","\\.?")+"$","i");this._shortWeekdaysParse[i]=new RegExp("^"+this.weekdaysShort(n,"").replace(".","\\.?")+"$","i");this._minWeekdaysParse[i]=new RegExp("^"+this.weekdaysMin(n,"").replace(".","\\.?")+"$","i")}if(!this._weekdaysParse[i]){o="^"+this.weekdays(n,"")+"|^"+this.weekdaysShort(n,"")+"|^"+this.weekdaysMin(n,"");this._weekdaysParse[i]=new RegExp(o.replace(".",""),"i")}if(r&&t==="dddd"&&this._fullWeekdaysParse[i].test(e)){return i}else if(r&&t==="ddd"&&this._shortWeekdaysParse[i].test(e)){return i}else if(r&&t==="dd"&&this._minWeekdaysParse[i].test(e)){return i}else if(!r&&this._weekdaysParse[i].test(e)){return i}}}function getSetDayOfWeek(e){if(!this.isValid()){return e!=null?this:NaN}var t=this._isUTC?this._d.getUTCDay():this._d.getDay();if(e!=null){e=parseWeekday(e,this.localeData());return this.add(e-t,"d")}else{return t}}function getSetLocaleDayOfWeek(e){if(!this.isValid()){return e!=null?this:NaN}var t=(this.day()+7-this.localeData()._week.dow)%7;return e==null?t:this.add(e-t,"d")}function getSetISODayOfWeek(e){if(!this.isValid()){return e!=null?this:NaN}if(e!=null){var t=parseIsoWeekday(e,this.localeData());return this.day(this.day()%7?t:t-7)}else{return this.day()||7}}var ne=k;function weekdaysRegex(e){if(this._weekdaysParseExact){if(!hasOwnProp(this,"_weekdaysRegex")){computeWeekdaysParse.call(this)}if(e){return this._weekdaysStrictRegex}else{return this._weekdaysRegex}}else{if(!hasOwnProp(this,"_weekdaysRegex")){this._weekdaysRegex=ne}return this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex}}var oe=k;function weekdaysShortRegex(e){if(this._weekdaysParseExact){if(!hasOwnProp(this,"_weekdaysRegex")){computeWeekdaysParse.call(this)}if(e){return this._weekdaysShortStrictRegex}else{return this._weekdaysShortRegex}}else{if(!hasOwnProp(this,"_weekdaysShortRegex")){this._weekdaysShortRegex=oe}return this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex}}var se=k;function weekdaysMinRegex(e){if(this._weekdaysParseExact){if(!hasOwnProp(this,"_weekdaysRegex")){computeWeekdaysParse.call(this)}if(e){return this._weekdaysMinStrictRegex}else{return this._weekdaysMinRegex}}else{if(!hasOwnProp(this,"_weekdaysMinRegex")){this._weekdaysMinRegex=se}return this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex}}function computeWeekdaysParse(){function cmpLenRev(e,t){return t.length-e.length}var e=[],t=[],r=[],i=[],n,o,s,a,l;for(n=0;n<7;n++){o=createUTC([2e3,1]).day(n);s=this.weekdaysMin(o,"");a=this.weekdaysShort(o,"");l=this.weekdays(o,"");e.push(s);t.push(a);r.push(l);i.push(s);i.push(a);i.push(l)}e.sort(cmpLenRev);t.sort(cmpLenRev);r.sort(cmpLenRev);i.sort(cmpLenRev);for(n=0;n<7;n++){t[n]=regexEscape(t[n]);r[n]=regexEscape(r[n]);i[n]=regexEscape(i[n])}this._weekdaysRegex=new RegExp("^("+i.join("|")+")","i");this._weekdaysShortRegex=this._weekdaysRegex;this._weekdaysMinRegex=this._weekdaysRegex;this._weekdaysStrictRegex=new RegExp("^("+r.join("|")+")","i");this._weekdaysShortStrictRegex=new RegExp("^("+t.join("|")+")","i");this._weekdaysMinStrictRegex=new RegExp("^("+e.join("|")+")","i")}function hFormat(){return this.hours()%12||12}function kFormat(){return this.hours()||24}addFormatToken("H",["HH",2],0,"hour");addFormatToken("h",["hh",2],0,hFormat);addFormatToken("k",["kk",2],0,kFormat);addFormatToken("hmm",0,0,(function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)}));addFormatToken("hmmss",0,0,(function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)}));addFormatToken("Hmm",0,0,(function(){return""+this.hours()+zeroFill(this.minutes(),2)}));addFormatToken("Hmmss",0,0,(function(){return""+this.hours()+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)}));function meridiem(e,t){addFormatToken(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}meridiem("a",true);meridiem("A",false);addUnitAlias("hour","h");addUnitPriority("hour",13);function matchMeridiem(e,t){return t._meridiemParse}addRegexToken("a",matchMeridiem);addRegexToken("A",matchMeridiem);addRegexToken("H",b);addRegexToken("h",b);addRegexToken("k",b);addRegexToken("HH",b,y);addRegexToken("hh",b,y);addRegexToken("kk",b,y);addRegexToken("hmm",A);addRegexToken("hmmss",M);addRegexToken("Hmm",A);addRegexToken("Hmmss",M);addParseToken(["H","HH"],$);addParseToken(["k","kk"],(function(e,t,r){var i=toInt(e);t[$]=i===24?0:i}));addParseToken(["a","A"],(function(e,t,r){r._isPm=r._locale.isPM(e);r._meridiem=e}));addParseToken(["h","hh"],(function(e,t,r){t[$]=toInt(e);getParsingFlags(r).bigHour=true}));addParseToken("hmm",(function(e,t,r){var i=e.length-2;t[$]=toInt(e.substr(0,i));t[H]=toInt(e.substr(i));getParsingFlags(r).bigHour=true}));addParseToken("hmmss",(function(e,t,r){var i=e.length-4;var n=e.length-2;t[$]=toInt(e.substr(0,i));t[H]=toInt(e.substr(i,2));t[j]=toInt(e.substr(n));getParsingFlags(r).bigHour=true}));addParseToken("Hmm",(function(e,t,r){var i=e.length-2;t[$]=toInt(e.substr(0,i));t[H]=toInt(e.substr(i))}));addParseToken("Hmmss",(function(e,t,r){var i=e.length-4;var n=e.length-2;t[$]=toInt(e.substr(0,i));t[H]=toInt(e.substr(i,2));t[j]=toInt(e.substr(n))}));function localeIsPM(e){return(e+"").toLowerCase().charAt(0)==="p"}var ae=/[ap]\.?m?\.?/i;function localeMeridiem(e,t,r){if(e>11){return r?"pm":"PM"}else{return r?"am":"AM"}}var le=makeGetSet("Hours",true);var ce={calendar:a,longDateFormat:l,invalidDate:c,ordinal:u,dayOfMonthOrdinalParse:d,relativeTime:g,months:Q,monthsShort:X,week:ee,weekdays:te,weekdaysMin:ie,weekdaysShort:re,meridiemParse:ae};var ue={};var de={};var ge;function normalizeLocale(e){return e?e.toLowerCase().replace("_","-"):e}function chooseLocale(e){var t=0,r,i,n,o;while(t0){n=loadLocale(o.slice(0,r).join("-"));if(n){return n}if(i&&i.length>=r&&compareArrays(o,i,true)>=r-1){break}r--}t++}return ge}function loadLocale(t){var r=null;if(!ue[t]&&"object"!=="undefined"&&e&&e.exports){try{r=ge._abbr;var i=commonjsRequire;i("./locale/"+t);getSetGlobalLocale(r)}catch(e){}}return ue[t]}function getSetGlobalLocale(e,t){var r;if(e){if(isUndefined(t)){r=getLocale(e)}else{r=defineLocale(e,t)}if(r){ge=r}else{if(typeof console!=="undefined"&&console.warn){console.warn("Locale "+e+" not found. Did you forget to load it?")}}}return ge._abbr}function defineLocale(e,t){if(t!==null){var r,i=ce;t.abbr=e;if(ue[e]!=null){deprecateSimple("defineLocaleOverride","use moment.updateLocale(localeName, config) to change "+"an existing locale. moment.defineLocale(localeName, "+"config) should only be used for creating a new locale "+"See http://momentjs.com/guides/#/warnings/define-locale/ for more info.");i=ue[e]._config}else if(t.parentLocale!=null){if(ue[t.parentLocale]!=null){i=ue[t.parentLocale]._config}else{r=loadLocale(t.parentLocale);if(r!=null){i=r._config}else{if(!de[t.parentLocale]){de[t.parentLocale]=[]}de[t.parentLocale].push({name:e,config:t});return null}}}ue[e]=new Locale(mergeConfigs(i,t));if(de[e]){de[e].forEach((function(e){defineLocale(e.name,e.config)}))}getSetGlobalLocale(e);return ue[e]}else{delete ue[e];return null}}function updateLocale(e,t){if(t!=null){var r,i,n=ce;i=loadLocale(e);if(i!=null){n=i._config}t=mergeConfigs(n,t);r=new Locale(t);r.parentLocale=ue[e];ue[e]=r;getSetGlobalLocale(e)}else{if(ue[e]!=null){if(ue[e].parentLocale!=null){ue[e]=ue[e].parentLocale}else if(ue[e]!=null){delete ue[e]}}}return ue[e]}function getLocale(e){var t;if(e&&e._locale&&e._locale._abbr){e=e._locale._abbr}if(!e){return ge}if(!isArray(e)){t=loadLocale(e);if(t){return t}e=[e]}return chooseLocale(e)}function listLocales(){return s(ue)}function checkOverflow(e){var t;var r=e._a;if(r&&getParsingFlags(e).overflow===-2){t=r[V]<0||r[V]>11?V:r[x]<1||r[x]>daysInMonth(r[B],r[V])?x:r[$]<0||r[$]>24||r[$]===24&&(r[H]!==0||r[j]!==0||r[Y]!==0)?$:r[H]<0||r[H]>59?H:r[j]<0||r[j]>59?j:r[Y]<0||r[Y]>999?Y:-1;if(getParsingFlags(e)._overflowDayOfYear&&(tx)){t=x}if(getParsingFlags(e)._overflowWeeks&&t===-1){t=G}if(getParsingFlags(e)._overflowWeekday&&t===-1){t=z}getParsingFlags(e).overflow=t}return e}function defaults(e,t,r){if(e!=null){return e}if(t!=null){return t}return r}function currentDateArray(e){var t=new Date(hooks.now());if(e._useUTC){return[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]}return[t.getFullYear(),t.getMonth(),t.getDate()]}function configFromArray(e){var t,r,i=[],n,o,s;if(e._d){return}n=currentDateArray(e);if(e._w&&e._a[x]==null&&e._a[V]==null){dayOfYearFromWeekInfo(e)}if(e._dayOfYear!=null){s=defaults(e._a[B],n[B]);if(e._dayOfYear>daysInYear(s)||e._dayOfYear===0){getParsingFlags(e)._overflowDayOfYear=true}r=createUTCDate(s,0,e._dayOfYear);e._a[V]=r.getUTCMonth();e._a[x]=r.getUTCDate()}for(t=0;t<3&&e._a[t]==null;++t){e._a[t]=i[t]=n[t]}for(;t<7;t++){e._a[t]=i[t]=e._a[t]==null?t===2?1:0:e._a[t]}if(e._a[$]===24&&e._a[H]===0&&e._a[j]===0&&e._a[Y]===0){e._nextDay=true;e._a[$]=0}e._d=(e._useUTC?createUTCDate:createDate).apply(null,i);o=e._useUTC?e._d.getUTCDay():e._d.getDay();if(e._tzm!=null){e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm)}if(e._nextDay){e._a[$]=24}if(e._w&&typeof e._w.d!=="undefined"&&e._w.d!==o){getParsingFlags(e).weekdayMismatch=true}}function dayOfYearFromWeekInfo(e){var t,r,i,n,o,s,a,l;t=e._w;if(t.GG!=null||t.W!=null||t.E!=null){o=1;s=4;r=defaults(t.GG,e._a[B],weekOfYear(createLocal(),1,4).year);i=defaults(t.W,1);n=defaults(t.E,1);if(n<1||n>7){l=true}}else{o=e._locale._week.dow;s=e._locale._week.doy;var c=weekOfYear(createLocal(),o,s);r=defaults(t.gg,e._a[B],c.year);i=defaults(t.w,c.week);if(t.d!=null){n=t.d;if(n<0||n>6){l=true}}else if(t.e!=null){n=t.e+o;if(t.e<0||t.e>6){l=true}}else{n=o}}if(i<1||i>weeksInYear(r,o,s)){getParsingFlags(e)._overflowWeeks=true}else if(l!=null){getParsingFlags(e)._overflowWeekday=true}else{a=dayOfYearFromWeeks(r,i,n,o,s);e._a[B]=a.year;e._dayOfYear=a.dayOfYear}}var he=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;var fe=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;var pe=/Z|[+-]\d\d(?::?\d\d)?/;var me=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,false],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,false],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,false],["YYYYDDD",/\d{7}/]];var Se=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]];var Ie=/^\/?Date\((\-?\d+)/i;function configFromISO(e){var t,r,i=e._i,n=he.exec(i)||fe.exec(i),o,s,a,l;if(n){getParsingFlags(e).iso=true;for(t=0,r=me.length;t0){getParsingFlags(e).unusedInput.push(s)}t=t.slice(t.indexOf(i)+i.length);l+=i.length}if(I[o]){if(i){getParsingFlags(e).empty=false}else{getParsingFlags(e).unusedTokens.push(o)}addTimeToArrayFromToken(o,i,e)}else if(e._strict&&!i){getParsingFlags(e).unusedTokens.push(o)}}getParsingFlags(e).charsLeftOver=a-l;if(t.length>0){getParsingFlags(e).unusedInput.push(t)}if(e._a[$]<=12&&getParsingFlags(e).bigHour===true&&e._a[$]>0){getParsingFlags(e).bigHour=undefined}getParsingFlags(e).parsedDateParts=e._a.slice(0);getParsingFlags(e).meridiem=e._meridiem;e._a[$]=meridiemFixWrap(e._locale,e._a[$],e._meridiem);configFromArray(e);checkOverflow(e)}function meridiemFixWrap(e,t,r){var i;if(r==null){return t}if(e.meridiemHour!=null){return e.meridiemHour(t,r)}else if(e.isPM!=null){i=e.isPM(r);if(i&&t<12){t+=12}if(!i&&t===12){t=0}return t}else{return t}}function configFromStringAndArray(e){var t,r,i,n,o;if(e._f.length===0){getParsingFlags(e).invalidFormat=true;e._d=new Date(NaN);return}for(n=0;nthis?this:e}else{return createInvalid()}}));function pickBy(e,t){var r,i;if(t.length===1&&isArray(t[0])){t=t[0]}if(!t.length){return createLocal()}r=t[0];for(i=1;ithis.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function isDaylightSavingTimeShifted(){if(!isUndefined(this._isDSTShifted)){return this._isDSTShifted}var e={};copyConfig(e,this);e=prepareConfig(e);if(e._a){var t=e._isUTC?createUTC(e._a):createLocal(e._a);this._isDSTShifted=this.isValid()&&compareArrays(e._a,t.toArray())>0}else{this._isDSTShifted=false}return this._isDSTShifted}function isLocal(){return this.isValid()?!this._isUTC:false}function isUtcOffset(){return this.isValid()?this._isUTC:false}function isUtc(){return this.isValid()?this._isUTC&&this._offset===0:false}var Ae=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;var Me=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function createDuration(e,t){var r=e,i=null,n,o,s;if(isDuration(e)){r={ms:e._milliseconds,d:e._days,M:e._months}}else if(isNumber(e)){r={};if(t){r[t]=e}else{r.milliseconds=e}}else if(!!(i=Ae.exec(e))){n=i[1]==="-"?-1:1;r={y:0,d:toInt(i[x])*n,h:toInt(i[$])*n,m:toInt(i[H])*n,s:toInt(i[j])*n,ms:toInt(absRound(i[Y]*1e3))*n}}else if(!!(i=Me.exec(e))){n=i[1]==="-"?-1:1;r={y:parseIso(i[2],n),M:parseIso(i[3],n),w:parseIso(i[4],n),d:parseIso(i[5],n),h:parseIso(i[6],n),m:parseIso(i[7],n),s:parseIso(i[8],n)}}else if(r==null){r={}}else if(typeof r==="object"&&("from"in r||"to"in r)){s=momentsDifference(createLocal(r.from),createLocal(r.to));r={};r.ms=s.milliseconds;r.M=s.months}o=new Duration(r);if(isDuration(e)&&hasOwnProp(e,"_locale")){o._locale=e._locale}return o}createDuration.fn=Duration.prototype;createDuration.invalid=createInvalid$1;function parseIso(e,t){var r=e&&parseFloat(e.replace(",","."));return(isNaN(r)?0:r)*t}function positiveMomentsDifference(e,t){var r={};r.months=t.month()-e.month()+(t.year()-e.year())*12;if(e.clone().add(r.months,"M").isAfter(t)){--r.months}r.milliseconds=+t-+e.clone().add(r.months,"M");return r}function momentsDifference(e,t){var r;if(!(e.isValid()&&t.isValid())){return{milliseconds:0,months:0}}t=cloneWithOffset(t,e);if(e.isBefore(t)){r=positiveMomentsDifference(e,t)}else{r=positiveMomentsDifference(t,e);r.milliseconds=-r.milliseconds;r.months=-r.months}return r}function createAdder(e,t){return function(r,i){var n,o;if(i!==null&&!isNaN(+i)){deprecateSimple(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). "+"See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.");o=r;r=i;i=o}r=typeof r==="string"?+r:r;n=createDuration(r,i);addSubtract(this,n,e);return this}}function addSubtract(e,t,r,i){var n=t._milliseconds,o=absRound(t._days),s=absRound(t._months);if(!e.isValid()){return}i=i==null?true:i;if(s){setMonth(e,get(e,"Month")+s*r)}if(o){set$1(e,"Date",get(e,"Date")+o*r)}if(n){e._d.setTime(e._d.valueOf()+n*r)}if(i){hooks.updateOffset(e,o||s)}}var Re=createAdder(1,"add");var we=createAdder(-1,"subtract");function getCalendarFormat(e,t){var r=e.diff(t,"days",true);return r<-6?"sameElse":r<-1?"lastWeek":r<0?"lastDay":r<1?"sameDay":r<2?"nextDay":r<7?"nextWeek":"sameElse"}function calendar$1(e,t){var r=e||createLocal(),i=cloneWithOffset(r,this).startOf("day"),n=hooks.calendarFormat(this,i)||"sameElse";var o=t&&(isFunction(t[n])?t[n].call(this,r):t[n]);return this.format(o||this.localeData().calendar(n,this,createLocal(r)))}function clone(){return new Moment(this)}function isAfter(e,t){var r=isMoment(e)?e:createLocal(e);if(!(this.isValid()&&r.isValid())){return false}t=normalizeUnits(t)||"millisecond";if(t==="millisecond"){return this.valueOf()>r.valueOf()}else{return r.valueOf()9999){return formatMoment(r,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ")}if(isFunction(Date.prototype.toISOString)){if(t){return this.toDate().toISOString()}else{return new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",formatMoment(r,"Z"))}}return formatMoment(r,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function inspect(){if(!this.isValid()){return"moment.invalid(/* "+this._i+" */)"}var e="moment";var t="";if(!this.isLocal()){e=this.utcOffset()===0?"moment.utc":"moment.parseZone";t="Z"}var r="["+e+'("]';var i=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY";var n="-MM-DD[T]HH:mm:ss.SSS";var o=t+'[")]';return this.format(r+i+n+o)}function format(e){if(!e){e=this.isUtc()?hooks.defaultFormatUtc:hooks.defaultFormat}var t=formatMoment(this,e);return this.localeData().postformat(t)}function from(e,t){if(this.isValid()&&(isMoment(e)&&e.isValid()||createLocal(e).isValid())){return createDuration({to:this,from:e}).locale(this.locale()).humanize(!t)}else{return this.localeData().invalidDate()}}function fromNow(e){return this.from(createLocal(),e)}function to(e,t){if(this.isValid()&&(isMoment(e)&&e.isValid()||createLocal(e).isValid())){return createDuration({from:this,to:e}).locale(this.locale()).humanize(!t)}else{return this.localeData().invalidDate()}}function toNow(e){return this.to(createLocal(),e)}function locale(e){var t;if(e===undefined){return this._locale._abbr}else{t=getLocale(e);if(t!=null){this._locale=t}return this}}var _e=deprecate("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",(function(e){if(e===undefined){return this.localeData()}else{return this.locale(e)}}));function localeData(){return this._locale}var ve=1e3;var De=60*ve;var Fe=60*De;var Oe=(365*400+97)*24*Fe;function mod$1(e,t){return(e%t+t)%t}function localStartOfDate(e,t,r){if(e<100&&e>=0){return new Date(e+400,t,r)-Oe}else{return new Date(e,t,r).valueOf()}}function utcStartOfDate(e,t,r){if(e<100&&e>=0){return Date.UTC(e+400,t,r)-Oe}else{return Date.UTC(e,t,r)}}function startOf(e){var t;e=normalizeUnits(e);if(e===undefined||e==="millisecond"||!this.isValid()){return this}var r=this._isUTC?utcStartOfDate:localStartOfDate;switch(e){case"year":t=r(this.year(),0,1);break;case"quarter":t=r(this.year(),this.month()-this.month()%3,1);break;case"month":t=r(this.year(),this.month(),1);break;case"week":t=r(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=r(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=r(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf();t-=mod$1(t+(this._isUTC?0:this.utcOffset()*De),Fe);break;case"minute":t=this._d.valueOf();t-=mod$1(t,De);break;case"second":t=this._d.valueOf();t-=mod$1(t,ve);break}this._d.setTime(t);hooks.updateOffset(this,true);return this}function endOf(e){var t;e=normalizeUnits(e);if(e===undefined||e==="millisecond"||!this.isValid()){return this}var r=this._isUTC?utcStartOfDate:localStartOfDate;switch(e){case"year":t=r(this.year()+1,0,1)-1;break;case"quarter":t=r(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=r(this.year(),this.month()+1,1)-1;break;case"week":t=r(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=r(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=r(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf();t+=Fe-mod$1(t+(this._isUTC?0:this.utcOffset()*De),Fe)-1;break;case"minute":t=this._d.valueOf();t+=De-mod$1(t,De)-1;break;case"second":t=this._d.valueOf();t+=ve-mod$1(t,ve)-1;break}this._d.setTime(t);hooks.updateOffset(this,true);return this}function valueOf(){return this._d.valueOf()-(this._offset||0)*6e4}function unix(){return Math.floor(this.valueOf()/1e3)}function toDate(){return new Date(this.valueOf())}function toArray(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function toObject(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function toJSON(){return this.isValid()?this.toISOString():null}function isValid$2(){return isValid(this)}function parsingFlags(){return extend({},getParsingFlags(this))}function invalidAt(){return getParsingFlags(this).overflow}function creationData(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}addFormatToken(0,["gg",2],0,(function(){return this.weekYear()%100}));addFormatToken(0,["GG",2],0,(function(){return this.isoWeekYear()%100}));function addWeekYearFormatToken(e,t){addFormatToken(0,[e,e.length],0,t)}addWeekYearFormatToken("gggg","weekYear");addWeekYearFormatToken("ggggg","weekYear");addWeekYearFormatToken("GGGG","isoWeekYear");addWeekYearFormatToken("GGGGG","isoWeekYear");addUnitAlias("weekYear","gg");addUnitAlias("isoWeekYear","GG");addUnitPriority("weekYear",1);addUnitPriority("isoWeekYear",1);addRegexToken("G",D);addRegexToken("g",D);addRegexToken("GG",b,y);addRegexToken("gg",b,y);addRegexToken("GGGG",w,E);addRegexToken("gggg",w,E);addRegexToken("GGGGG",_,T);addRegexToken("ggggg",_,T);addWeekParseToken(["gggg","ggggg","GGGG","GGGGG"],(function(e,t,r,i){t[i.substr(0,2)]=toInt(e)}));addWeekParseToken(["gg","GG"],(function(e,t,r,i){t[i]=hooks.parseTwoDigitYear(e)}));function getSetWeekYear(e){return getSetWeekYearHelper.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)}function getSetISOWeekYear(e){return getSetWeekYearHelper.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function getISOWeeksInYear(){return weeksInYear(this.year(),1,4)}function getWeeksInYear(){var e=this.localeData()._week;return weeksInYear(this.year(),e.dow,e.doy)}function getSetWeekYearHelper(e,t,r,i,n){var o;if(e==null){return weekOfYear(this,i,n).year}else{o=weeksInYear(e,i,n);if(t>o){t=o}return setWeekAll.call(this,e,t,r,i,n)}}function setWeekAll(e,t,r,i,n){var o=dayOfYearFromWeeks(e,t,r,i,n),s=createUTCDate(o.year,0,o.dayOfYear);this.year(s.getUTCFullYear());this.month(s.getUTCMonth());this.date(s.getUTCDate());return this}addFormatToken("Q",0,"Qo","quarter");addUnitAlias("quarter","Q");addUnitPriority("quarter",7);addRegexToken("Q",C);addParseToken("Q",(function(e,t){t[V]=(toInt(e)-1)*3}));function getSetQuarter(e){return e==null?Math.ceil((this.month()+1)/3):this.month((e-1)*3+this.month()%3)}addFormatToken("D",["DD",2],"Do","date");addUnitAlias("date","D");addUnitPriority("date",9);addRegexToken("D",b);addRegexToken("DD",b,y);addRegexToken("Do",(function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}));addParseToken(["D","DD"],x);addParseToken("Do",(function(e,t){t[x]=toInt(e.match(b)[0])}));var Le=makeGetSet("Date",true);addFormatToken("DDD",["DDDD",3],"DDDo","dayOfYear");addUnitAlias("dayOfYear","DDD");addUnitPriority("dayOfYear",4);addRegexToken("DDD",R);addRegexToken("DDDD",P);addParseToken(["DDD","DDDD"],(function(e,t,r){r._dayOfYear=toInt(e)}));function getSetDayOfYear(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return e==null?t:this.add(e-t,"d")}addFormatToken("m",["mm",2],0,"minute");addUnitAlias("minute","m");addUnitPriority("minute",14);addRegexToken("m",b);addRegexToken("mm",b,y);addParseToken(["m","mm"],H);var ke=makeGetSet("Minutes",false);addFormatToken("s",["ss",2],0,"second");addUnitAlias("second","s");addUnitPriority("second",15);addRegexToken("s",b);addRegexToken("ss",b,y);addParseToken(["s","ss"],j);var Ue=makeGetSet("Seconds",false);addFormatToken("S",0,0,(function(){return~~(this.millisecond()/100)}));addFormatToken(0,["SS",2],0,(function(){return~~(this.millisecond()/10)}));addFormatToken(0,["SSS",3],0,"millisecond");addFormatToken(0,["SSSS",4],0,(function(){return this.millisecond()*10}));addFormatToken(0,["SSSSS",5],0,(function(){return this.millisecond()*100}));addFormatToken(0,["SSSSSS",6],0,(function(){return this.millisecond()*1e3}));addFormatToken(0,["SSSSSSS",7],0,(function(){return this.millisecond()*1e4}));addFormatToken(0,["SSSSSSSS",8],0,(function(){return this.millisecond()*1e5}));addFormatToken(0,["SSSSSSSSS",9],0,(function(){return this.millisecond()*1e6}));addUnitAlias("millisecond","ms");addUnitPriority("millisecond",16);addRegexToken("S",R,C);addRegexToken("SS",R,y);addRegexToken("SSS",R,P);var Ne;for(Ne="SSSS";Ne.length<=9;Ne+="S"){addRegexToken(Ne,v)}function parseMs(e,t){t[Y]=toInt(("0."+e)*1e3)}for(Ne="S";Ne.length<=9;Ne+="S"){addParseToken(Ne,parseMs)}var Be=makeGetSet("Milliseconds",false);addFormatToken("z",0,0,"zoneAbbr");addFormatToken("zz",0,0,"zoneName");function getZoneAbbr(){return this._isUTC?"UTC":""}function getZoneName(){return this._isUTC?"Coordinated Universal Time":""}var Ve=Moment.prototype;Ve.add=Re;Ve.calendar=calendar$1;Ve.clone=clone;Ve.diff=diff;Ve.endOf=endOf;Ve.format=format;Ve.from=from;Ve.fromNow=fromNow;Ve.to=to;Ve.toNow=toNow;Ve.get=stringGet;Ve.invalidAt=invalidAt;Ve.isAfter=isAfter;Ve.isBefore=isBefore;Ve.isBetween=isBetween;Ve.isSame=isSame;Ve.isSameOrAfter=isSameOrAfter;Ve.isSameOrBefore=isSameOrBefore;Ve.isValid=isValid$2;Ve.lang=_e;Ve.locale=locale;Ve.localeData=localeData;Ve.max=Ee;Ve.min=Pe;Ve.parsingFlags=parsingFlags;Ve.set=stringSet;Ve.startOf=startOf;Ve.subtract=we;Ve.toArray=toArray;Ve.toObject=toObject;Ve.toDate=toDate;Ve.toISOString=toISOString;Ve.inspect=inspect;Ve.toJSON=toJSON;Ve.toString=toString;Ve.unix=unix;Ve.valueOf=valueOf;Ve.creationData=creationData;Ve.year=W;Ve.isLeapYear=getIsLeapYear;Ve.weekYear=getSetWeekYear;Ve.isoWeekYear=getSetISOWeekYear;Ve.quarter=Ve.quarters=getSetQuarter;Ve.month=getSetMonth;Ve.daysInMonth=getDaysInMonth;Ve.week=Ve.weeks=getSetWeek;Ve.isoWeek=Ve.isoWeeks=getSetISOWeek;Ve.weeksInYear=getWeeksInYear;Ve.isoWeeksInYear=getISOWeeksInYear;Ve.date=Le;Ve.day=Ve.days=getSetDayOfWeek;Ve.weekday=getSetLocaleDayOfWeek;Ve.isoWeekday=getSetISODayOfWeek;Ve.dayOfYear=getSetDayOfYear;Ve.hour=Ve.hours=le;Ve.minute=Ve.minutes=ke;Ve.second=Ve.seconds=Ue;Ve.millisecond=Ve.milliseconds=Be;Ve.utcOffset=getSetOffset;Ve.utc=setOffsetToUTC;Ve.local=setOffsetToLocal;Ve.parseZone=setOffsetToParsedOffset;Ve.hasAlignedHourOffset=hasAlignedHourOffset;Ve.isDST=isDaylightSavingTime;Ve.isLocal=isLocal;Ve.isUtcOffset=isUtcOffset;Ve.isUtc=isUtc;Ve.isUTC=isUtc;Ve.zoneAbbr=getZoneAbbr;Ve.zoneName=getZoneName;Ve.dates=deprecate("dates accessor is deprecated. Use date instead.",Le);Ve.months=deprecate("months accessor is deprecated. Use month instead",getSetMonth);Ve.years=deprecate("years accessor is deprecated. Use year instead",W);Ve.zone=deprecate("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",getSetZone);Ve.isDSTShifted=deprecate("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",isDaylightSavingTimeShifted);function createUnix(e){return createLocal(e*1e3)}function createInZone(){return createLocal.apply(null,arguments).parseZone()}function preParsePostFormat(e){return e}var xe=Locale.prototype;xe.calendar=calendar;xe.longDateFormat=longDateFormat;xe.invalidDate=invalidDate;xe.ordinal=ordinal;xe.preparse=preParsePostFormat;xe.postformat=preParsePostFormat;xe.relativeTime=relativeTime;xe.pastFuture=pastFuture;xe.set=set;xe.months=localeMonths;xe.monthsShort=localeMonthsShort;xe.monthsParse=localeMonthsParse;xe.monthsRegex=monthsRegex;xe.monthsShortRegex=monthsShortRegex;xe.week=localeWeek;xe.firstDayOfYear=localeFirstDayOfYear;xe.firstDayOfWeek=localeFirstDayOfWeek;xe.weekdays=localeWeekdays;xe.weekdaysMin=localeWeekdaysMin;xe.weekdaysShort=localeWeekdaysShort;xe.weekdaysParse=localeWeekdaysParse;xe.weekdaysRegex=weekdaysRegex;xe.weekdaysShortRegex=weekdaysShortRegex;xe.weekdaysMinRegex=weekdaysMinRegex;xe.isPM=localeIsPM;xe.meridiem=localeMeridiem;function get$1(e,t,r,i){var n=getLocale();var o=createUTC().set(i,t);return n[r](o,e)}function listMonthsImpl(e,t,r){if(isNumber(e)){t=e;e=undefined}e=e||"";if(t!=null){return get$1(e,t,r,"month")}var i;var n=[];for(i=0;i<12;i++){n[i]=get$1(e,i,r,"month")}return n}function listWeekdaysImpl(e,t,r,i){if(typeof e==="boolean"){if(isNumber(t)){r=t;t=undefined}t=t||""}else{t=e;r=t;e=false;if(isNumber(t)){r=t;t=undefined}t=t||""}var n=getLocale(),o=e?n._week.dow:0;if(r!=null){return get$1(t,(r+o)%7,i,"day")}var s;var a=[];for(s=0;s<7;s++){a[s]=get$1(t,(s+o)%7,i,"day")}return a}function listMonths(e,t){return listMonthsImpl(e,t,"months")}function listMonthsShort(e,t){return listMonthsImpl(e,t,"monthsShort")}function listWeekdays(e,t,r){return listWeekdaysImpl(e,t,r,"weekdays")}function listWeekdaysShort(e,t,r){return listWeekdaysImpl(e,t,r,"weekdaysShort")}function listWeekdaysMin(e,t,r){return listWeekdaysImpl(e,t,r,"weekdaysMin")}getSetGlobalLocale("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10,r=toInt(e%100/10)===1?"th":t===1?"st":t===2?"nd":t===3?"rd":"th";return e+r}});hooks.lang=deprecate("moment.lang is deprecated. Use moment.locale instead.",getSetGlobalLocale);hooks.langData=deprecate("moment.langData is deprecated. Use moment.localeData instead.",getLocale);var $e=Math.abs;function abs(){var e=this._data;this._milliseconds=$e(this._milliseconds);this._days=$e(this._days);this._months=$e(this._months);e.milliseconds=$e(e.milliseconds);e.seconds=$e(e.seconds);e.minutes=$e(e.minutes);e.hours=$e(e.hours);e.months=$e(e.months);e.years=$e(e.years);return this}function addSubtract$1(e,t,r,i){var n=createDuration(t,r);e._milliseconds+=i*n._milliseconds;e._days+=i*n._days;e._months+=i*n._months;return e._bubble()}function add$1(e,t){return addSubtract$1(this,e,t,1)}function subtract$1(e,t){return addSubtract$1(this,e,t,-1)}function absCeil(e){if(e<0){return Math.floor(e)}else{return Math.ceil(e)}}function bubble(){var e=this._milliseconds;var t=this._days;var r=this._months;var i=this._data;var n,o,s,a,l;if(!(e>=0&&t>=0&&r>=0||e<=0&&t<=0&&r<=0)){e+=absCeil(monthsToDays(r)+t)*864e5;t=0;r=0}i.milliseconds=e%1e3;n=absFloor(e/1e3);i.seconds=n%60;o=absFloor(n/60);i.minutes=o%60;s=absFloor(o/60);i.hours=s%24;t+=absFloor(s/24);l=absFloor(daysToMonths(t));r+=l;t-=absCeil(monthsToDays(l));a=absFloor(r/12);r%=12;i.days=t;i.months=r;i.years=a;return this}function daysToMonths(e){return e*4800/146097}function monthsToDays(e){return e*146097/4800}function as(e){if(!this.isValid()){return NaN}var t;var r;var i=this._milliseconds;e=normalizeUnits(e);if(e==="month"||e==="quarter"||e==="year"){t=this._days+i/864e5;r=this._months+daysToMonths(t);switch(e){case"month":return r;case"quarter":return r/3;case"year":return r/12}}else{t=this._days+Math.round(monthsToDays(this._months));switch(e){case"week":return t/7+i/6048e5;case"day":return t+i/864e5;case"hour":return t*24+i/36e5;case"minute":return t*1440+i/6e4;case"second":return t*86400+i/1e3;case"millisecond":return Math.floor(t*864e5)+i;default:throw new Error("Unknown unit "+e)}}}function valueOf$1(){if(!this.isValid()){return NaN}return this._milliseconds+this._days*864e5+this._months%12*2592e6+toInt(this._months/12)*31536e6}function makeAs(e){return function(){return this.as(e)}}var He=makeAs("ms");var je=makeAs("s");var Ye=makeAs("m");var Ge=makeAs("h");var ze=makeAs("d");var We=makeAs("w");var Ke=makeAs("M");var qe=makeAs("Q");var Qe=makeAs("y");function clone$1(){return createDuration(this)}function get$2(e){e=normalizeUnits(e);return this.isValid()?this[e+"s"]():NaN}function makeGetter(e){return function(){return this.isValid()?this._data[e]:NaN}}var Xe=makeGetter("milliseconds");var Je=makeGetter("seconds");var Ze=makeGetter("minutes");var et=makeGetter("hours");var tt=makeGetter("days");var rt=makeGetter("months");var it=makeGetter("years");function weeks(){return absFloor(this.days()/7)}var nt=Math.round;var ot={ss:44,s:45,m:45,h:22,d:26,M:11};function substituteTimeAgo(e,t,r,i,n){return n.relativeTime(t||1,!!r,e,i)}function relativeTime$1(e,t,r){var i=createDuration(e).abs();var n=nt(i.as("s"));var o=nt(i.as("m"));var s=nt(i.as("h"));var a=nt(i.as("d"));var l=nt(i.as("M"));var c=nt(i.as("y"));var u=n<=ot.ss&&["s",n]||n0;u[4]=r;return substituteTimeAgo.apply(null,u)}function getSetRelativeTimeRounding(e){if(e===undefined){return nt}if(typeof e==="function"){nt=e;return true}return false}function getSetRelativeTimeThreshold(e,t){if(ot[e]===undefined){return false}if(t===undefined){return ot[e]}ot[e]=t;if(e==="s"){ot.ss=t-1}return true}function humanize(e){if(!this.isValid()){return this.localeData().invalidDate()}var t=this.localeData();var r=relativeTime$1(this,!e,t);if(e){r=t.pastFuture(+this,r)}return t.postformat(r)}var st=Math.abs;function sign(e){return(e>0)-(e<0)||+e}function toISOString$1(){if(!this.isValid()){return this.localeData().invalidDate()}var e=st(this._milliseconds)/1e3;var t=st(this._days);var r=st(this._months);var i,n,o;i=absFloor(e/60);n=absFloor(i/60);e%=60;i%=60;o=absFloor(r/12);r%=12;var s=o;var a=r;var l=t;var c=n;var u=i;var d=e?e.toFixed(3).replace(/\.?0+$/,""):"";var g=this.asSeconds();if(!g){return"P0D"}var h=g<0?"-":"";var f=sign(this._months)!==sign(g)?"-":"";var p=sign(this._days)!==sign(g)?"-":"";var m=sign(this._milliseconds)!==sign(g)?"-":"";return h+"P"+(s?f+s+"Y":"")+(a?f+a+"M":"")+(l?p+l+"D":"")+(c||u||d?"T":"")+(c?m+c+"H":"")+(u?m+u+"M":"")+(d?m+d+"S":"")}var at=Duration.prototype;at.isValid=isValid$1;at.abs=abs;at.add=add$1;at.subtract=subtract$1;at.as=as;at.asMilliseconds=He;at.asSeconds=je;at.asMinutes=Ye;at.asHours=Ge;at.asDays=ze;at.asWeeks=We;at.asMonths=Ke;at.asQuarters=qe;at.asYears=Qe;at.valueOf=valueOf$1;at._bubble=bubble;at.clone=clone$1;at.get=get$2;at.milliseconds=Xe;at.seconds=Je;at.minutes=Ze;at.hours=et;at.days=tt;at.weeks=weeks;at.months=rt;at.years=it;at.humanize=humanize;at.toISOString=toISOString$1;at.toString=toISOString$1;at.toJSON=toISOString$1;at.locale=locale;at.localeData=localeData;at.toIsoString=deprecate("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",toISOString$1);at.lang=_e;addFormatToken("X",0,0,"unix");addFormatToken("x",0,0,"valueOf");addRegexToken("x",D);addRegexToken("X",L);addParseToken("X",(function(e,t,r){r._d=new Date(parseFloat(e,10)*1e3)}));addParseToken("x",(function(e,t,r){r._d=new Date(toInt(e))}));hooks.version="2.24.0";setHookCallback(createLocal);hooks.fn=Ve;hooks.min=min;hooks.max=max;hooks.now=now;hooks.utc=createUTC;hooks.unix=createUnix;hooks.months=listMonths;hooks.isDate=isDate;hooks.locale=getSetGlobalLocale;hooks.invalid=createInvalid;hooks.duration=createDuration;hooks.isMoment=isMoment;hooks.weekdays=listWeekdays;hooks.parseZone=createInZone;hooks.localeData=getLocale;hooks.isDuration=isDuration;hooks.monthsShort=listMonthsShort;hooks.weekdaysMin=listWeekdaysMin;hooks.defineLocale=defineLocale;hooks.updateLocale=updateLocale;hooks.locales=listLocales;hooks.weekdaysShort=listWeekdaysShort;hooks.normalizeUnits=normalizeUnits;hooks.relativeTimeRounding=getSetRelativeTimeRounding;hooks.relativeTimeThreshold=getSetRelativeTimeThreshold;hooks.calendarFormat=getCalendarFormat;hooks.prototype=Ve;hooks.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"};return hooks}))}));function isClientUsingEnglishBasedDateLocale(){const e=new Date(2016,11,3,18,0,0,0);return e.toLocaleTimeString(undefined,{weekday:"long"}).indexOf("Saturday")>-1}function constructValueTransformerOptions(e,t,r){return Object.assign(new ValueTransformerOptions,{transformer:e,propertyName:t,rawValue:r})}function constructDateFormatter(e){const t=Object.assign(new DateFormattingOptions,e);const r=new DateFormatter(t);return r}function constructDateDescriptor(e){const t=new Date(e);const r=t.getTime()/1e3;return Object.assign(new DateDescriptor,{timestamp:r})}function constructDateRangeDescriptor(e,t){const r=new Date(e);const i=new Date(t);const n=r.getTime()/1e3;const o=i.getTime()/1e3;return Object.assign(new DateRangeDescriptor,{startTimestamp:n,endTimestamp:o})}function dateFormat(e,t){return new Promise(r=>{const i=new DateFormatter;i.dateFormat(e,t,e=>{r(e)})})}function isUsing24HourLocaleSync(){return isUsing24HourLocaleSync.is24HourLocale}function initializeIsUsing24HourLocale(){return dateFormat("j").then(e=>e.indexOf("a")<0).then(e=>{isUsing24HourLocaleSync.is24HourLocale=e;return e})}function getLanguageTag(){return getBagValueSync("language-tag")}function formatDate(e,t){if(!(e instanceof Date)||Number.isNaN(e.getTime())){return}const r=e.toLocaleDateString(getLanguageTag(),t);return r}function getLastUpdated(e,t){const r=moment(e).startOf("day");const i=moment(t).startOf("day");const n=moment(t).startOf("day").subtract(1,"day");const o=moment(t).startOf("day").subtract(7,"day");const s=moment(t).startOf("day").subtract(14,"day");const a=moment(t).startOf("day").subtract(21,"day");let l=" ";if(r.isSame(i)){l=localize("FUSE.Social.Profile.Playlist.Updated.Today")}else if(r.isSame(n)){l=localize("FUSE.Social.Profile.Playlist.Updated.Yesterday")}else if(r.isAfter(o)){const t=new Date(e);const r=t.toLocaleString(getLanguageTag(),{weekday:"long"});l=localize("FUSE.Social.Profile.Playlist.Updated.Day",{day:r})}else if(r.isAfter(s)){l=localize("FUSE.Social.Profile.Playlist.Updated.LastWeek")}else if(r.isBetween(a,s)){const e=i.diff(r,"weeks");l=localize("FUSE.Social.Profile.Playlist.Updated.Weeks",{weeks:e})}return l}function getFormatedDurationFromSeconds(e){const t=moment().startOf("day").seconds(e);const r=t.format("ss");let i;if(e>=3600){const e=t.format("H");const n=t.format("mm");i=localize("FUSE.Artist.Bio.Duration.Hour",{hours:e,minutes:n,seconds:r})}else{const e=t.format("m");i=localize("FUSE.Artist.Bio.Duration",{minutes:e,seconds:r})}return i}function formatDateWithUTC(e){const t=new Date(e);const r={month:"short",day:"numeric",year:"numeric",timeZone:"UTC"};return formatDate(t,r)}function isDateOnOrAfter(e,t={},r=new Date){const i=moment(e).startOf("day").add(t.val,t.unit);const n=moment(r).startOf("day");return n.isSameOrAfter(i)}function localizedYearStringFromReleaseDate(e){if(!e){return""}const t=new Date(e.toString());const r=t.toLocaleString(getLanguageTag(),{year:"numeric",timeZone:"UTC"});return r}function localizedMonthDayStringFromReleaseDate(e){if(!e){return""}const t=new Date(e.toString());const r=t.toLocaleString(getLanguageTag(),{month:"long",day:"numeric",timeZone:"UTC"});return r}function localizedMonthDayYearStringFromReleaseDate(e){if(!e){return""}const t=new Date(e.toString());const r=t.toLocaleString(getLanguageTag(),{month:"long",day:"numeric",year:"numeric",timeZone:"UTC"});return r}function convertNumberToLocaleString(e){if(!e){return""}const t=getLanguageTag();if(t){return e.toLocaleString(t)}return e}function timezoneOffsetISOString(e=new Date){const t=e.getTimezoneOffset();const r=Math.abs(t);const i=Math.floor(r/60);const n=r%60;const o=t>0?"-":"+";const s=i.toString().padStart(2,"0");const a=n.toString().padStart(2,"0");return`${o}${s}:${a}`}const nameSymbol=Symbol("name");const withSymbol=Symbol("with");const extendSymbol=Symbol("extend");const typesSymbol=Symbol("types");const displayFilterKindSymbol=Symbol("displayFilterKind");const sparseSymbol=Symbol("sparse");const shouldIncludeTimezoneOffsetSymbol=Symbol("shouldIncludeTimezoneOffset");const shouldIncludeLanguageSymbol=Symbol("shouldIncludeLanguage");const shouldIncludePlatformSymbol=Symbol("shouldIncludePlatform");const shouldIncludeFormatResourcesMapSymbol=Symbol("shouldIncludeFormatResourcesMap");class MusicAPIURLQueryString extends QueryString{constructor(){super();this.shouldIncludeLanguage=true;this.shouldIncludePlatform=true;this.shouldIncludeFormatResourcesMap=true;this.shouldIncludeTimezoneOffset=false}get name(){return this[nameSymbol]}set name(e){this[nameSymbol]=e}get extend(){let e=this[extendSymbol];if(!e){e=new Set;this[extendSymbol]=e}return e}set extend(e){if(!(e instanceof Set)){throw new Error(`${this.constructor.name}: extend must be an instance of a Set.`)}this[extendSymbol]=e}get with(){let e=this[withSymbol];if(!e){e=new Set;this[withSymbol]=e}return e}set with(e){if(!(e instanceof Set)){throw new Error(`${this.constructor.name}: with must be an instance of a Set.`)}this[withSymbol]=e}get types(){let e=this[typesSymbol];if(!e){e=new Set;this[typesSymbol]=e}return e}set types(e){if(!(e instanceof Set)){throw new Error(`${this.constructor.name}: types must be an instance of a Set.`)}this[typesSymbol]=e}get displayFilterKind(){let e=this[displayFilterKindSymbol];if(!e){e=new Set;this[displayFilterKindSymbol]=e}return e}set displayFilterKind(e){if(!(e instanceof Set)){throw new Error(`${this.constructor.name}: displayFilterKind must be an instance of a Set.`)}this[displayFilterKindSymbol]=e}get sparse(){let e=this[sparseSymbol];if(!e){e=new Set;this[sparseSymbol]=e}return e}set sparse(e){if(!(e instanceof Set)){throw new Error(`${this.constructor.name}: sparse must be an instance of a Set.`)}this[sparseSymbol]=e}get shouldIncludeLanguage(){return this[shouldIncludeLanguageSymbol]}set shouldIncludeLanguage(e){this[shouldIncludeLanguageSymbol]=e}get shouldIncludePlatform(){return this[shouldIncludePlatformSymbol]}set shouldIncludePlatform(e){this[shouldIncludePlatformSymbol]=e}get shouldIncludeFormatResourcesMap(){return this[shouldIncludeFormatResourcesMapSymbol]}set shouldIncludeFormatResourcesMap(e){this[shouldIncludeFormatResourcesMapSymbol]=e}get shouldIncludeTimezoneOffset(){return this[shouldIncludeTimezoneOffsetSymbol]}set shouldIncludeTimezoneOffset(e){this[shouldIncludeTimezoneOffsetSymbol]=e}object(){return Promise.all([super.object(),this.language()]).then(([e,t])=>{const r=Object.assign({},e);if(this.name){r.name=this.name}if(this.with&&this.with.size>0){r.with=Array.from(this.with).join(",")}if(this.extend&&this.extend.size>0){r.extend=Array.from(this.extend).join(",")}if(this.types&&this.types.size>0){r.types=Array.from(this.types).join(",")}if(this.displayFilterKind&&this.displayFilterKind.size>0){r["displayFilter[kind]"]=Array.from(this.displayFilterKind).join(",")}if(this.sparse&&this.sparse.size>0){r.sparse=Array.from(this.sparse).join(",")}if(this.shouldIncludeLanguage){r.l=t}if(this.shouldIncludePlatform){r.platform=Device.model==="iPad"?"ipad":"iphone"}if(this.shouldIncludeFormatResourcesMap){r["format[resources]"]="map"}if(this.shouldIncludeTimezoneOffset){r.timezone=timezoneOffsetISOString()}return r})}language(){return getBagValue("language-tag")}}const pathSymbol=Symbol("path");const queryStringSymbol=Symbol("queryString");class MusicAPIURL{constructor(e){this.path=e}get path(){return this[pathSymbol]}set path(e){this[pathSymbol]=e}get queryString(){let e=this[queryStringSymbol];if(!e){e=new MusicAPIURLQueryString;this[queryStringSymbol]=e}return e}set queryString(e){if(!(e instanceof MusicAPIURLQueryString)){throw new Error(`${this.constructor.name}: queryString must be an instance of a MusicAPIURLQueryString.`)}this[queryStringSymbol]=e}domain(){return getBagValue("ampMusicAPIDomains.default")}string(){return Promise.all([this.domain(),this.queryString.object()]).then(([e,t])=>{const r=`https://${e}`;const i=URLFromBaseURLandPath(r,this.path);return constructURL(i,{params:t})})}}const ONBOARD_COMPLETE="ONBOARD_COMPLETE";class OnboardingController extends ComponentController{didLoad(){super.didLoad();OnboardingController.isPresenting=true;logger$5.log("onboarding did load");this.viewModel=createOnboardingViewModel();this.viewModel.onOnboardingCompleted=()=>{publish(ONBOARD_COMPLETE)}}didDisappear(e,t){super.didDisappear(e,t);OnboardingController.isPresenting=false;logger$5.log("Onboarding did disappear.")}}function requestIsOnboardingRequired(){const e=new MusicAPIURL("/v1/me/account");e.queryString.extend.add("hasTastePreferences");return e.string().then(e=>requestMusicAPIResource(e,{shouldIgnoreCache:true})).then(e=>{const t=e?.resources?.accounts?.me?.attributes?.hasTastePreferences;if(typeof t==="undefined"){throw new Error("hasTastePreferences is undefined.")}return!t})}OnboardingController.isOnboardingRequired=()=>{logger$5.log("Checking onboarding required status.");return requestIsOnboardingRequired().then(e=>{logger$5.log(`Is onboarding required: ${e}`);return e}).catch(e=>{logger$5.error("OnboardingController requiresOnboarding error",e);return false})};OnboardingController.isPresenting=false;function createPresentationSegue(e){return Object.assign(new PresentationSegue,e)}function presentOnboardingController(e){const t=OnboardingController.isPresenting;if(t){logger$5.log("An OnboardingController is already being presented.");return}logger$5.log("Attempting OnboardingController Presentation Segue.");const r=new OnboardingController;e(createPresentationSegue({componentController:r}))}function presentOnboardingControllerIfRequired(e){OnboardingController.isOnboardingRequired().then(t=>{logger$5.log(`Account requires onboarding: ${t}`);if(!t){return}presentOnboardingController(e)})}function considerCreatingOnboardingSeguePromise(){return OnboardingController.isOnboardingRequired().then(e=>{logger$5.log(`Account requires onboarding from segue promise: ${e}`);if(!e){publish(ONBOARD_COMPLETE);return Promise.resolve()}if(OnboardingController.isPresenting){logger$5.log("An OnboardingController is already being presented.");return}const t=new OnboardingController;return createPresentationSegue({componentController:t})})}function createFamilyCircleSegue(e){return Object.assign(new FamilyCircleSegue,e)}const loggerName="FamilyCirclePresentationManager";function isFamilySubscription(){return getSubscriptionStatus().then(e=>{logger$5.log(`${loggerName}: subscription status: ${JSON.stringify(e)}`);return Promise.resolve(e.isFamilySubscription)})}function presentFamilyCircleSheet(e,t,r){const i=Object.assign({},e,{params:{mustDisplay:false,requestor:"SubscriptionPurchase"}});logger$5.log(`${loggerName}: familyCircleOptions: ${JSON.stringify(i)}, shouldSuppressOnboarding: ${t}`);const n=createFamilyCircleSegue(i);if(!t){n.didDismissFamilyCircle=()=>presentOnboardingControllerIfRequired(r)}r(n)}var punycode=createCommonjsModule((function(e,t){(function(r){var i=t&&!t.nodeType&&t;var n=e&&!e.nodeType&&e;var o=typeof commonjsGlobal=="object"&&commonjsGlobal;if(o.global===o||o.window===o||o.self===o){r=o}var s,a=2147483647,l=36,c=1,u=26,d=38,g=700,h=72,f=128,p="-",m=/^xn--/,S=/[^\x20-\x7E]/,I=/[\x2E\u3002\uFF0E\uFF61]/g,C={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},y=l-c,P=Math.floor,E=String.fromCharCode,T;function error(e){throw RangeError(C[e])}function map(e,t){var r=e.length;var i=[];while(r--){i[r]=t(e[r])}return i}function mapDomain(e,t){var r=e.split("@");var i="";if(r.length>1){i=r[0]+"@";e=r[1]}e=e.replace(I,".");var n=e.split(".");var o=map(n,t).join(".");return i+o}function ucs2decode(e){var t=[],r=0,i=e.length,n,o;while(r=55296&&n<=56319&&r65535){e-=65536;t+=E(e>>>10&1023|55296);e=56320|e&1023}t+=E(e);return t})).join("")}function basicToDigit(e){if(e-48<10){return e-22}if(e-65<26){return e-65}if(e-97<26){return e-97}return l}function digitToBasic(e,t){return e+22+75*(e<26)-((t!=0)<<5)}function adapt(e,t,r){var i=0;e=r?P(e/g):e>>1;e+=P(e/t);for(;e>y*u>>1;i+=l){e=P(e/y)}return P(i+(y+1)*e/(e+d))}function decode(e){var t=[],r=e.length,i,n=0,o=f,s=h,d,g,m,S,I,C,y,E,T;d=e.lastIndexOf(p);if(d<0){d=0}for(g=0;g=128){error("not-basic")}t.push(e.charCodeAt(g))}for(m=d>0?d+1:0;m=r){error("invalid-input")}y=basicToDigit(e.charCodeAt(m++));if(y>=l||y>P((a-n)/I)){error("overflow")}n+=y*I;E=C<=s?c:C>=s+u?u:C-s;if(yP(a/T)){error("overflow")}I*=T}i=t.length+1;s=adapt(n-S,i,S==0);if(P(n/i)>a-o){error("overflow")}o+=P(n/i);n%=i;t.splice(n++,0,o)}return ucs2encode(t)}function encode(e){var t,r,i,n,o,s,d,g,m,S,I,C=[],y,T,b,A;e=ucs2decode(e);y=e.length;t=f;r=0;o=h;for(s=0;s=t&&IP((a-r)/T)){error("overflow")}r+=(d-t)*T;t=d;for(s=0;sa){error("overflow")}if(I==t){for(g=r,m=l;;m+=l){S=m<=o?c:m>=o+u?u:m-o;if(g0&&a>s){a=s}for(var l=0;l=0){d=c.substr(0,u);g=c.substr(u+1)}else{d=c;g=""}h=decodeURIComponent(d);f=decodeURIComponent(g);if(!hasOwnProperty$b(n,h)){n[h]=f}else if(Array.isArray(n[h])){n[h].push(f)}else{n[h]=[n[h],f]}}return n};var stringifyPrimitive$1=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};var encode$1=function(e,t,r,i){t=t||"&";r=r||"=";if(e===null){e=undefined}if(typeof e==="object"){return Object.keys(e).map((function(i){var n=encodeURIComponent(stringifyPrimitive$1(i))+r;if(Array.isArray(e[i])){return e[i].map((function(e){return n+encodeURIComponent(stringifyPrimitive$1(e))})).join(t)}else{return n+encodeURIComponent(stringifyPrimitive$1(e[i]))}})).join(t)}if(!i)return"";return encodeURIComponent(stringifyPrimitive$1(i))+r+encodeURIComponent(stringifyPrimitive$1(e))};var querystring=createCommonjsModule((function(e,t){t.decode=t.parse=decode$1;t.encode=t.stringify=encode$1}));var querystring_1=querystring.decode;var querystring_2=querystring.parse;var querystring_3=querystring.encode;var querystring_4=querystring.stringify;var parse=urlParse;var resolve=urlResolve;var resolveObject=urlResolveObject;var format=urlFormat;var Url_1=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null}var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true};function urlParse(e,t,r){if(e&&util.isObject(e)&&e instanceof Url)return e;var i=new Url;i.parse(e,t,r);return i}Url.prototype.parse=function(e,t,r){if(!util.isString(e)){throw new TypeError("Parameter 'url' must be a string, not "+typeof e)}var i=e.indexOf("?"),n=i!==-1&&i127){P+="x"}else{P+=y[E]}}if(!P.match(hostnamePartPattern)){var b=I.slice(0,h);var A=I.slice(h+1);var M=y.match(hostnamePartStart);if(M){b.push(M[1]);A.unshift(M[2])}if(A.length){a="/"+A.join(".")+a}this.hostname=b.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!S){this.hostname=punycode.toASCII(this.hostname)}var R=this.port?":"+this.port:"";var w=this.hostname||"";this.host=w+R;this.href+=this.host;if(S){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(a[0]!=="/"){a="/"+a}}}if(!unsafeProtocol[u]){for(var h=0,C=autoEscape.length;h0?r.host.split("@"):false;if(P){r.auth=P.shift();r.host=r.hostname=P.shift()}}r.search=e.search;r.query=e.query;if(!util.isNull(r.pathname)||!util.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.href=r.format();return r}if(!C.length){r.pathname=null;if(r.search){r.path="/"+r.search}else{r.path=null}r.href=r.format();return r}var E=C.slice(-1)[0];var T=(r.host||e.host||C.length>1)&&(E==="."||E==="..")||E==="";var b=0;for(var A=C.length;A>=0;A--){E=C[A];if(E==="."){C.splice(A,1)}else if(E===".."){C.splice(A,1);b++}else if(b){C.splice(A,1);b--}}if(!S&&!I){for(;b--;b){C.unshift("..")}}if(S&&C[0]!==""&&(!C[0]||C[0].charAt(0)!=="/")){C.unshift("")}if(T&&C.join("/").substr(-1)!=="/"){C.push("")}var M=C[0]===""||C[0]&&C[0].charAt(0)==="/";if(y){r.hostname=r.host=M?"":C.length?C.shift():"";var P=r.host&&r.host.indexOf("@")>0?r.host.split("@"):false;if(P){r.auth=P.shift();r.host=r.hostname=P.shift()}}S=S||r.host&&C.length;if(S&&!M){C.unshift("")}if(!C.length){r.pathname=null;r.path=null}else{r.pathname=C.join("/")}if(!util.isNull(r.pathname)||!util.isNull(r.search)){r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")}r.auth=e.auth||r.auth;r.slashes=r.slashes||e.slashes;r.href=r.format();return r};Url.prototype.parseHost=function(){var e=this.host;var t=portPattern.exec(e);if(t){t=t[0];if(t!==":"){this.port=t.substr(1)}e=e.substr(0,e.length-t.length)}if(e)this.hostname=e};var url={parse:parse,resolve:resolve,resolveObject:resolveObject,format:format,Url:Url_1};function createNoopSegue(e){return Object.assign(new NoopSegue,e)}function createMessageViewModel(e){const t={accessoryButtonTitle:localize("FUSE.Error.TryAgain")};return Object.assign(new MessageViewModel,t,e)}function createRetryHandler(e){return()=>{e.viewModel=null;if(e.loadPage){e.loadPage()}return createNoopSegue()}}function userFacingMessageForError(e){let t;if(e instanceof RequestError){switch(e.statusCode){case HTTP.STATUS_CODES.CLIENT_TIMEOUT:t=localize("FUSE.Error.PoorNetworkConnection");break;case HTTP.STATUS_CODES.CLIENT_PARSING_ERROR:t=localize("FUSE.Error.AnErrorOccurred");break;case 403:t=localize("FUSE.ComingSoon");break;default:t=localize("FUSE.Error.GenericDataError");break}}if(!t){t=localize("FUSE.Error.AnErrorOccurred")}return t}function userFacingButtonTitleForError(){return localize("FUSE.Error.TryAgain")}const _cachedApplicationRef=Symbol("_cachedApplicationRef");const _mixinRef=Symbol("_mixinRef");const _originalMixin=Symbol("_originalMixin");const wrap=(e,t)=>{Object.setPrototypeOf(t,e);if(!e[_originalMixin]){e[_originalMixin]=e}return t};const Cached=e=>wrap(e,t=>{let r=e[_cachedApplicationRef];if(!r){r=e[_cachedApplicationRef]=Symbol(e.name)}if(t.hasOwnProperty(r)){return t[r]}let i=e(t);t[r]=i;return i});const HasInstance=e=>{if(Symbol.hasInstance&&!e.hasOwnProperty(Symbol.hasInstance)){Object.defineProperty(e,Symbol.hasInstance,{value:function(e){const t=this[_originalMixin];while(e!=null){if(e.hasOwnProperty(_mixinRef)&&e[_mixinRef]===t){return true}e=Object.getPrototypeOf(e)}return false}})}return e};const BareMixin=e=>wrap(e,t=>{let r=e(t);r.prototype[_mixinRef]=e[_originalMixin];return r});const Mixin=e=>Cached(HasInstance(BareMixin(e)));const mix=e=>new MixinBuilder(e);class MixinBuilder{constructor(e){this.superclass=e}with(){return Array.from(arguments).reduce((e,t)=>t(e),this.superclass)}}const pageFieldsKey=Symbol("pageFields");const pageBannerMetricsKey=Symbol("pageBannerMetrics");const pageContextKey=Symbol("pageContext");const xhrMetricsKey=Symbol("xhrMetrics");const pageMetricsKey=Symbol("pageMetrics");const launchParamsKey=Symbol("launchParams");const pagePerformanceKey=Symbol("pagePerformanceMetrics");const visibilityKey=Symbol("visible");const metricsEnabledKey=Symbol("metricsEnabled");const shouldRecordPerformanceMetricsKey=Symbol("shouldRecordPerformanceMetrics");const shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEventKey=Symbol("shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent");const notifyWhenOnScreenResourcesLoadedKey=Symbol("notifyWhenOnScreenResourcesLoaded");const PAGE_PERFORMANCE_FIELD={PAGE_REQUEST_TIME:"pageRequestTime",PRIMARY_DATA_REQUEST_START_TIME:"primaryDataRequestStartTime",PRIMARY_DATA_RESPONSE_START_TIME:"primaryDataResponseStartTime",PRIMARY_DATA_RESPONSE_END_TIME:"primaryDataResponseEndTime",IS_PRIMARY_DATA_RESPONSE_CACHED:"isPrimaryDataResponseCached",PRIMARY_DATA_PARSE_START_TIME:"primaryDataParseStartTime",PRIMARY_DATA_PARSE_END_TIME:"primaryDataParseEndTime",SECONDARY_DATA_REQUEST_START_TIME:"secondaryData.requestStartTime",SECONDARY_DATA_RESPONSE_END_TIME:"secondaryData.responseEndTime",PAGE_APPEAR_TIME:"pageAppearTime",PAGE_USER_INTERACTIVE_TIME:"pageUserInteractiveTime",PAGE_ON_SCREEN_RESOURCES_APPEAR_END_TIME:"onScreenResourcesAppearEndTime",PAGE_INTERRUPT_TIME:"pageInterruptTime",PAGE_END_TIME:"pageEndTime",XP_SAMPLING_PERCENTAGE_USERS_PAGE_RENDER:"xpSamplingPercentageUsersPageRender",IS_APP_LAUNCH:"isAppLaunch"};const NATIVE_NETWORKING_PERFORMANCE_FIELD={JSON_PARSE_START_TIME:"JSONParseStartTimeInMilliseconds",JSON_PARSE_END_TIME:"JSONParseEndTimeInMilliseconds",REQUEST_START_TIME:"requestStartTime",RESPONSE_START_TIME:"responseStartTime",RESPONSE_END_TIME:"responseEndTime",RESPONSE_WAS_CACHED:"wasResourceFetchedFromLocalCache"};let isAppLaunch=true;class PageMetricsController{constructor({extRefUrl:e,refApp:t}={}){if(e||t){this.launchParams={extRefUrl:e,refApp:t}}registerGlobalCallback(Application,"onEnteringBackground",this.onEnteringBackground.bind(this));this.metricsEnabled=true;this.shouldRecordPerformanceMetrics=false;this.shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent=true;this.hasSentPageEventForPresentation=false}get metricsEnabled(){return this[metricsEnabledKey]}set metricsEnabled(e){this[metricsEnabledKey]=e}get shouldRecordPerformanceMetrics(){return this[shouldRecordPerformanceMetricsKey]}set shouldRecordPerformanceMetrics(e){this[shouldRecordPerformanceMetricsKey]=e}get shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent(){return this[shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEventKey]}set shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent(e){this[shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEventKey]=e}get notifyWhenOnScreenResourcesLoaded(){return this[notifyWhenOnScreenResourcesLoadedKey]}set notifyWhenOnScreenResourcesLoaded(e){this[notifyWhenOnScreenResourcesLoadedKey]=e}didAppear(){this.isVisible=true;this.hasSentPageEventForPresentation=false;this.considerRecordingPageEvent();this.onPageAppear()}willDisappear(){this.isVisible=false;this.onPageDisappear()}didDisappear(e){this.reportImpressionsEvent(e)}reportImpressionsForApplicationWillResignActiveEvent(e){this.reportImpressionsEvent(e)}onEnteringBackground(){this.isVisible=false;this.onPageDisappear()}onPagePresentationChanged(){this.hasSentPageEventForPresentation=false;this.considerRecordingPageEvent()}considerRecordingPageEvent(){if(!this.metricsEnabled||!this.isVisible||this.hasSentPageEventForPresentation){return}const e=this.combinedPageFields;if(!this.pageMetrics&&!this.xhrMetrics&&!e){return}const t=this.primaryMetricsForXhrMetrics(this.xhrMetrics);const r=this.launchParams;this.launchParams=undefined;recordPageEvent(e,t,this.pageMetrics,r);this.hasSentPageEventForPresentation=true}get pageFields(){return this[pageFieldsKey]}set pageFields(e){this[pageFieldsKey]=e}get pageBannerMetrics(){return this[pageBannerMetricsKey]}set pageBannerMetrics(e){this[pageBannerMetricsKey]=e}get pageContext(){return this[pageContextKey]}set pageContext(e){this[pageContextKey]=e}get xhrMetrics(){return this[xhrMetricsKey]}set xhrMetrics(e){this[xhrMetricsKey]=e}get pageMetrics(){return this[pageMetricsKey]}set pageMetrics(e){this[pageMetricsKey]=e}get launchParams(){return this[launchParamsKey]}set launchParams(e){this[launchParamsKey]=e}onPageRequest(){this.setPagePerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_REQUEST_TIME,Date.now())}onSecondaryDataRequest(){this.setPagePerformanceField(PAGE_PERFORMANCE_FIELD.SECONDARY_DATA_REQUEST_START_TIME,Date.now())}onSecondaryDataResponse(){this.setPagePerformanceField(PAGE_PERFORMANCE_FIELD.SECONDARY_DATA_RESPONSE_END_TIME,Date.now())}onPageViewModelSet(){this.addFenceForPerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_USER_INTERACTIVE_TIME,()=>{if(this.shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent){this.recordPerformanceFieldAfterCurrentlyVisibleContentLoadingCompletes()}else{this.considerRecordingPagePerformanceEvent()}})}onPageError(){}onPageAppear(){this.setPagePerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_APPEAR_TIME,Date.now());this.considerRecordingPagePerformanceEvent()}onPageDisappear(){this.considerRecordingPagePerformanceEvent(true)}reportImpressionsEvent(e){if(!e){return}const t=this.primaryMetricsForXhrMetrics(this.xhrMetrics);const r=Object.assign({},this.combinedPageFields,t,this.pageMetrics);if(this.metricsEnabled){recordImpressionsEvent(sanitizeImpressionsForPrivacyCompliance(e.impressions,r),r)}}recordPerformanceFieldAfterCurrentlyVisibleContentLoadingCompletes(){if(typeof this.notifyWhenOnScreenResourcesLoaded!=="function"){logger$5.warn(`${this.constructor.name} couldn't capture render metrics, notifyWhenOnScreenResourcesLoaded not provided.`);return}this.notifyWhenOnScreenResourcesLoaded(e=>{this.setPagePerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_ON_SCREEN_RESOURCES_APPEAR_END_TIME,e.getTime());this.considerRecordingPagePerformanceEvent()})}addFenceForPerformanceField(e,t,r=NativeExecutionFence.KIND.REGULAR){const i=new NativeExecutionFence;i.kind=r;i.onCompletion=r=>{this.setPagePerformanceField(e,r.getTime());if(t){t()}};i.register()}get isVisible(){return this[visibilityKey]}set isVisible(e){this[visibilityKey]=e}get combinedPageFields(){let e;if(this.pageFields){e=Object.assign({},this.pageFields);if(this.pageContext){e.pageContext=this.pageContext}if(this.pageBannerMetrics){e.pageBanner=this.pageBannerMetrics}}return e}get pagePerformanceMetrics(){if(!this[pagePerformanceKey]){this[pagePerformanceKey]={}}return this[pagePerformanceKey]}set pagePerformanceMetrics(e){this[pagePerformanceKey]=e}setPagePerformanceField(e,t){set(this.pagePerformanceMetrics,e,t)}getPagePerformanceField(e){return get(this.pagePerformanceMetrics,e)}get hasPerformanceEventBeenRecorded(){return!!this.getPagePerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_INTERRUPT_TIME)||!!this.getPagePerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_END_TIME)}considerRecordingPagePerformanceEvent(e=false){if(this.hasPerformanceEventBeenRecorded){return}if(e){const e=false;this.recordPagePerformanceEvent(e,Date.now());return}const t=this.getPagePerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_APPEAR_TIME);const r=this.getPagePerformanceField(PAGE_PERFORMANCE_FIELD.PAGE_USER_INTERACTIVE_TIME);if(r{const t=class extends e{constructor({extRefUrl:e,refApp:t}={}){super(...arguments);this.pageMetricsController=new PageMetricsController({extRefUrl:e,refApp:t});if(this.notifyWhenCurrentlyVisibleContentLoadingCompletes){this.notifyWhenOnScreenResourcesLoaded=this.notifyWhenCurrentlyVisibleContentLoadingCompletes.bind(this)}}get metricsEnabled(){return this.pageMetricsController.metricsEnabled}set metricsEnabled(e){this.pageMetricsController.metricsEnabled=e}get shouldRecordPerformanceMetrics(){return this.pageMetricsController.shouldRecordPerformanceMetrics}set shouldRecordPerformanceMetrics(e){this.pageMetricsController.shouldRecordPerformanceMetrics=e}get shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent(){return this.pageMetricsController.shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent}set shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent(e){this.pageMetricsController.shouldWaitForOnScreenResourcesLoadBeforeFinalizingPerformanceEvent=e}get notifyWhenOnScreenResourcesLoaded(){return this.pageMetricsController.notifyWhenOnScreenResourcesLoaded}set notifyWhenOnScreenResourcesLoaded(e){this.pageMetricsController.notifyWhenOnScreenResourcesLoaded=e}didAppear(...e){super.didAppear(...e);this.pageMetricsController.didAppear()}willDisappear(...e){super.willDisappear(...e);this.pageMetricsController.willDisappear()}didDisappear(e,t){super.didDisappear(e,t);this.pageMetricsController.didDisappear(t)}reportImpressionsForApplicationWillResignActiveEvent(e){super.reportImpressionsForApplicationWillResignActiveEvent(e);this.pageMetricsController.reportImpressionsForApplicationWillResignActiveEvent(e)}onPagePresentationChanged(){this.pageMetricsController.onPagePresentationChanged()}considerRecordingPageEvent(){this.pageMetricsController.considerRecordingPageEvent()}onPageRequest(){this.pageMetricsController.onPageRequest()}onSecondaryDataRequest(){this.pageMetricsController.onSecondaryDataRequest()}onSecondaryDataResponse(){this.pageMetricsController.onSecondaryDataResponse()}onPageAppear(){this.pageMetricsController.onPageAppear()}onPageDisappear(){this.pageMetricsController.onPageDisappear()}onPageViewModelSet(){this.pageMetricsController.onPageViewModelSet()}get pageFields(){return this.pageMetricsController.pageFields}set pageFields(e){this.pageMetricsController.pageFields=e}get pageBannerMetrics(){return this.pageMetricsController.pageBannerMetrics}set pageBannerMetrics(e){this.pageMetricsController.pageBannerMetrics=e}get pageContext(){return this.pageMetricsController.pageContext}set pageContext(e){this.pageMetricsController.pageContext=e}get xhrMetrics(){return this.pageMetricsController.xhrMetrics}set xhrMetrics(e){this.pageMetricsController.xhrMetrics=e}get pageMetrics(){return this.pageMetricsController.pageMetrics}get combinedPageFields(){return this.pageMetricsController.combinedPageFields}set pageMetrics(e){this.pageMetricsController.pageMetrics=e}get launchParams(){return this.pageMetricsController.launchParams}set launchParams(e){this.pageMetricsController.launchParams=e}createPageMetrics(){}};return t});const PAF_FIELDS={grouping_page:"grouping",music_browse:"browse",room_page:"room",multi_room_page:"multi_room",top_charts_page:"top_charts",album_page:"album_detail",playlist_page:"playlist_detail",music_video_page:"music_video_detail",artist_page:"artist_detail",artist_see_all_page:"artist_see_all",brand_page:"brand_detail",itunes_brand_page:"curator_detail",activity_page:"activity_detail",post_page:"connect_post",social_profile:"social_profile",show_brand_page:"show_brand_page",movie_page:"movie_page",episode_page:"episode_page"};function fetchMissingStorePlatformData(e,t=[],r=false,i=true){return fetchContent({ids:t,profile:"lockup",isPersonalized:r,shouldCacheStorePlatformData:i}).then(t=>{const r=get(e,"storePlatformData.lockup.results");if(r){Object.assign(r,t)}else{set(e,"storePlatformData.lockup.results",t)}return e})}function fetchJSONWithStorePlatformData(e,{fetchOptions:t={},getIdsMissingStorePlatformData:r=(()=>[]),isPersonalized:i=false,shouldCacheStorePlatformData:n=true}){return fetchJSON(e,t).then(e=>{if(n){cacheStorePlatformData(get(e,"storePlatformData",{}))}const t=r(e);return fetchMissingStorePlatformData(e,t,i,n)})}function StorePageMixin(e){const t=mix(e).with(MetricsMixin);const r=class extends t{constructor({url:e,pageData:t,id:r,isPersonalized:i,originalUrl:n}={}){super(...arguments);this.shouldRecordPerformanceMetrics=true;this.url=e;this.pageData=t;this.id=r;this.isPersonalized=i;this.originalUrl=n;this.onPageRequest();if(this.headerItem){this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}}set playActivityFeatureName(e){this.pafName=e}get playActivityFeatureName(){return this.pafName}didAppear(...e){this.pageContext=currentPageContext();super.didAppear(...e)}getURL(){let e;if(this.url){e=Promise$1.resolve(this.url)}else if(this.id){e=this.getURLForId()}else{throw new Error("getURL: No page URL or ID specified")}return e}fetchPageData(e,t){let r;if(this.pageData){r=Promise$1.resolve(this.pageData)}else{r=fetchJSON(e,t)}return r.then(e=>{cacheStorePlatformData(get(e,"storePlatformData",{}));return e})}getURLForId(){const e=this.isPersonalized;return fetchContent({ids:[this.id.toString()],profile:"lockup",isPersonalized:e}).then((e={})=>get(e[this.id],"url"))}getMissingContentIds(){return[]}fetchAdditionalData(e){const t=this.getMissingContentIds(e);const r=this.isPersonalized;return Promise$1.all([e,fetchContent({ids:t,profile:"lockup",isPersonalized:r})]).then(([e,t])=>{const r=get(e,"storePlatformData.lockup.results");if(r){Object.assign(r,t)}else{set(e,"storePlatformData.lockup.results",t)}return e})}createViewModel(){}getFetchOptions(){const e=this.id&&!this.url;const t={shouldSuppressResponseDialogs:!!e};return Promise$1.resolve(t)}updatePlayActivityFeatureName(e){if(!this.playActivityFeatureName){const t=get(e,"pageData.componentName")||get(e,"componentName");this.playActivityFeatureName=PAF_FIELDS[t]}}appendPlayActivity(e,t){this.updatePlayActivityFeatureName(t);if(e&&this.playActivityFeatureName){e.playActivityFeatureName=this.playActivityFeatureName}}updateViewModel(e){return Promise$1.resolve(this.createViewModel(e)).then(t=>{this.appendPlayActivity(t,e);this.viewModel=t})}handleLoadingError(e){logger$5.error(e);const t=userFacingMessageForError(e);if(t){this.viewModel=createMessageViewModel({message:t,onAccessoryButtonSelect:createRetryHandler(this)})}}createPageMetrics(e){const[t,r,i]=getStoreMetricsFields(e);t.pageUrl=this.originalUrl||this.url;if(this.viewModel?.hasSharedContent===true){t.sharedContent=true}this.pageFields=t;this.xhrMetrics=r;this.pageMetrics=i}loadPage(){return waitForLocInitialization().then(()=>Promise$1.all([this.getURL(),this.getFetchOptions()])).then(([e,t])=>{this.url=e;return this.fetchPageData(e,t)}).then(e=>{this.createPageMetrics(e);this.onSecondaryDataRequest();return this.fetchAdditionalData(e)}).then(e=>{this.onSecondaryDataResponse();return e}).then(e=>Promise$1.all([e,this.updateViewModel(e)])).then(([e])=>{this.onPageViewModelSet();this.loadLater(e).then((...e)=>{if(e.length===0){return}this.updateViewModelLater(...e)}).catch(e=>logger$5.error("Failed to loadLater",e))}).then(()=>{this.considerRecordingPageEvent()}).catch(e=>this.handleLoadingError(e))}loadLater(){return Promise$1.resolve()}updateViewModelLater(){}};return r}var StorePageController=mix(ComponentController).with(StorePageMixin);function debounce(e,t,r){let i;return(...n)=>{const clearTimer=()=>{if(i){i.cancel();i=undefined}};const runFunc=()=>{clearTimer();e.apply(this,n)};if(!r){clearTimer();i=new Timer;i.delay=t;i.onTimeout=runFunc;i.schedule()}else if(!i){i=new Timer;i.delay=t;i.onTimeout=clearTimer;e.apply(this,n);i.schedule()}return i}}const refreshTTLKey=Symbol("refreshTTL");const lastReloadKey=Symbol("lastReload");const loadingKey=Symbol("loading");const reloadKey=Symbol("reload");var RefreshMixin=e=>{const t=class extends e{constructor(...e){super(...e);this.refreshWithDebounce=debounce(this.reloadPage.bind(this),1e3);this.hasSetInitializers=false}willUnload(){super.willUnload();this.hasSetInitializers=false}get isLoading(){return this[loadingKey]}set isLoading(e){this[loadingKey]=e}get reloadPromise(){return this[reloadKey]}set reloadPromise(e){this[reloadKey]=e}get refreshTTL(){return this[refreshTTLKey]}set refreshTTL(e){this[refreshTTLKey]=e}get lastReload(){return this[lastReloadKey]}set lastReload(e){this[lastReloadKey]=e}refreshPageContent(){return Promise$1.resolve({})}setInitializersForRefresh(){}reloadPage(...e){let t;if(e&&e.length>1){t=e[1]}if(t&&t===Store.ACCOUNT_CHANGE_REASON.USER_SOCIAL_PROFILE_CHANGED){return false}if(!this.isLoading){this.isLoading=true;this.reloadPromise=this.refreshPageContent().then(()=>{this.setInitializersForRefresh();this.hasSetInitializers=true;this.isLoading=false;this.lastReload=Date.now()}).catch(e=>{this.isLoading=false;logger$5.error("reloading error uncaught",e)})}return true}needsRefresh(){return Date.now()-this.lastReload>this.refreshTTL}considerLoadingPage(){if(!this.viewModel&&!this.isLoading){this.reloadPage()}else if(this.needsRefresh()){this.reloadPage()}}};return t};function createRedirectSegue(e){return Object.assign(new RedirectSegue,e)}function createRadioPlaybackIntent(e){return Object.assign(new RadioPlaybackIntent,e)}function createCatalogPlaybackIntent(e){return Object.assign(new CatalogPlaybackIntent,e)}const BEATS_1_ID="ra.978194965";function getPlaybackIntentForContent(e={}){let t;if(e.mediaKind){const r=e;t=createRadioPlaybackIntent({radioStationStorePlatformDictionary:r});return t}switch(e.kind){case"radioStation":{const r=e;t=createRadioPlaybackIntent({radioStationStorePlatformDictionary:r});break}default:{const r=e;t=createCatalogPlaybackIntent({containerStorePlatformDictionary:r});break}}return t}function playbackIntentForIdentifierSet(e={}){const t=e.contentKind;if(!t){return null}let r=null;if(t==="radioStation"){const t=e;r=createRadioPlaybackIntent({radioStationIdentifierSet:t})}else{const t=e;r=createCatalogPlaybackIntent({containerIdentifierSet:t})}return r}function fetchDataForID(e){return fetchContent({ids:[e]}).then((t={})=>{const r=get(t,e);return r})}function fetchDataForBeats1(){return fetchDataForID(BEATS_1_ID)}function fetchMediaAPIContentForIdentifier(e,t,r=true){return getBagValue("countryCode").then(i=>{const n=new MusicAPIURL(`/v1/catalog/${i}/${t}/${e}`);if(r){n.queryString.with.add("voice");n.queryString.addParameters({meta:"vacToken","extend[playlists]":"versionHash","extend[albums]":"versionHash"})}return n.string()}).then(e=>requestMusicAPIResource(e)).then(e=>{const t=e.data?.[0];return t}).catch(e=>Promise.reject(new Error(`Error fetching preview media: ${e}.`)))}const NOW_PLAYING_URL="music://shownowplaying";function createNowPlayingSegue(e){const t=getSubscriptionStatusSync();const r=NOW_PLAYING_URL;const i=get(e,"storePlatformDictionary");let n;if(i){n=getPlaybackIntentForContent(i)}if(!t){logger$5.log("Now Playing segue disabled for Non Subscribers and Apple Music Voice.");return createNoopSegue({playbackIntent:n})}return createRedirectSegue({url:r,playbackIntent:n})}function createItemizedTextListViewModel(e){return Object.assign(new ItemizedTextListViewModel,e)}function createItemizedTextListItem(e){return Object.assign(new ItemizedTextListItem,e)}function createGroupedTextListViewModel(e){return Object.assign(new GroupedTextListViewModel,e)}function createGroupedTextListItem(e){return Object.assign(new GroupedTextListItem,e)}function createBadgingViewModel(e){return Object.assign(new BadgingViewModel,e)}function createBadgingItem(e){return Object.assign(new BadgingItem,e)}function isFeaturedNode(e){return!!e.fcKind}function isContentNode(e){return e.contentId||e.type==="content"}function isMarkerNode(e){return["332","388","389","401"].indexOf(e.fcKind)!==-1}function toUpperCase(e){const t=getBagValueSync("language");if(t&&t.toLowerCase().match(/tr-tr|el-gr/i)){return e}return e&&typeof e==="string"?e.toUpperCase():e}function walkFCModel(e,t){return function recurse(r){if(e(r)){t(r)}if(r.children){r.children.forEach(recurse)}if(r.content){if(r.content instanceof Array){r.content.forEach(recurse)}else{recurse(r.content)}}if(r.links&&r.links instanceof Array){r.links.forEach(recurse)}if(r.link){recurse(r.link)}}}function findContentIds(e,t){const r=[];if(e){walkFCModel(isContentNode,e=>{if(!t[e.contentId]){r.push(e.contentId)}})(e)}return r}function parseRadioMarkerResponse(e){cacheStorePlatformData(get(e,"storePlatformData",{}));return get(e,"contentIds")||[]}function findFcKindIdsInModel(e,t=[]){if(!e||!t.length){return false}let r=false;walkFCModel(e=>t.indexOf(get(e,"fcKind"))!==-1,()=>{r=true})(e);return r}const RADIO_MARKER_LIMIT=30;function findMarkers(e,t){const r=[];if(e){walkFCModel(isMarkerNode,e=>{let i;function transformRadioMarkerToSwoosh(t,r="children"){e[r]=t.map(e=>{e.contentId=e.id;e.type="content";return e}).slice(0,RADIO_MARKER_LIMIT);return e}switch(e.fcKind){case"332":i=new Promise$1(t=>{getBagValue("radioTab.recent").then(fetchJSON).then(parseRadioMarkerResponse).then(transformRadioMarkerToSwoosh).then(()=>t(e)).catch(r=>{t(e);logger$5.log("radio recents call failed",r)})});break;case"388":i=new Promise$1(t=>{getBagValue("radioTab.targetedRadio").then(fetchJSON).then(parseRadioMarkerResponse).then(t=>{let r;if(t&&t.length>0){r=transformRadioMarkerToSwoosh(t,"content")}else{r=e}return r}).then(e=>t(e)).catch(r=>{t(e);logger$5.log("radio targeted call failed",r)})});break;case"389":i=new Promise$1(r=>{const i=get(t,"pageData.id")||get(t,"pageData.iTunesBrandAdamId");fetchContent({ids:[i]}).then(t=>{const n=get(t,[i,"playlistIds"],[]);e.children=n.map(e=>({contentId:e,type:"content"}));if(!e.name){e.name=localize("FUSE.Profile.Playlists")}r(e)}).catch(t=>{r(e);logger$5.log("converting playlists marker failed",t)})});break;case"401":i=new Promise$1(r=>{const i=get(t,"pageData.liveURLData.upcomingShows",[]);const n=i.reduce((e,t)=>{if(t.curatorId){e.push(t.curatorId.toString())}return e},[]);e.children=n.map(e=>({contentId:e,type:"content"}));r(e)});break}if(i){r.push(i)}})(e)}return r}function fetchMarkers(e){const t=get(e,"pageData.fcStructure.model");const r=t?findMarkers(t,e):[];return Promise$1.all([e,...r]).then(([e])=>e)}function addContentIdAndTypeToMarkerResponse(e){const t=e.slice(0,RADIO_MARKER_LIMIT);const r=t.map(e=>{e.contentId=e.id;e.type="content";return e});return r}function fetchRecentlyPlayedRadio(){return getBagValue("radioTab.recent").then(fetchJSON).then(parseRadioMarkerResponse).then(e=>addContentIdAndTypeToMarkerResponse(e)).catch(e=>logger$5.error("Failed to fetch recently played radio",e))}function findAvailableContentIds(e){const t=get(e,"pageData.unAvailableContentIds",{});const r=get(e,"pageData.fcStructure.model");const i=r?findContentIds(r,t):[];const n=get(e,"pageData.id")||get(e,"pageData.iTunesBrandAdamId");if(n){i.push(n)}return i}function fetchAvailableStoreContent(e){const t=findAvailableContentIds(e);return Promise$1.all([e,fetchContent({ids:t})]).then(([e,t])=>{Object.assign(e,{storePlatformData:t});return e})}const RadioStationKinds={SONG_SEEDED:"songSeeded",ARTIST_SEEDED:"artistSeeded",FORMAT:"format",EDITORIAL:"editorial",STREAMING:"streaming",GENRE:"genre",QUERY:"query",USER:"user",PLAYLIST_SEEDED:"playlistSeeded",ALBUM_SEEDED:"albumSeeded",LIBRARY_PLAYLIST_SEEDED:"libraryPlaylistSeeded",ARTIST_ONLY:"artistOnly",DISCOVERY:"discovery"};const RadioStationKindsForAlgoStation=new Set([RadioStationKinds.SONG_SEEDED,RadioStationKinds.ARTIST_SEEDED,RadioStationKinds.EDITORIAL,RadioStationKinds.STREAMING,RadioStationKinds.GENRE,RadioStationKinds.QUERY,RadioStationKinds.USER,RadioStationKinds.PLAYLIST_SEEDED,RadioStationKinds.ALBUM_SEEDED,RadioStationKinds.ARTIST_ONLY]);const AllRadioStationKinds=new Set([RadioStationKinds.SONG_SEEDED,RadioStationKinds.ARTIST_SEEDED,RadioStationKinds.FORMAT,RadioStationKinds.EDITORIAL,RadioStationKinds.STREAMING,RadioStationKinds.GENRE,RadioStationKinds.QUERY,RadioStationKinds.USER,RadioStationKinds.PLAYLIST_SEEDED,RadioStationKinds.ALBUM_SEEDED,RadioStationKinds.LIBRARY_PLAYLIST_SEEDED,RadioStationKinds.ARTIST_ONLY]);function isBrandShowContent(e={}){return e.kind==="iTunesBrand"&&e.iTunesBrandType==="Show"&&e.showHostName}function isBroadcastRadioShowContent(e={}){const t=e.stationProviderName;return e.kind==="radioStation"&&t}function isRadioContent(e={}){const t=e.stationProviderName;return e.kind==="radioStation"&&!t}function isAlgoGeneratedStationForMusicAPIAttributes(e={}){if(get(e,"playParams.kind")!=="radioStation"){return false}return RadioStationKindsForAlgoStation.has(e.kind)}function getBroadcastRadioShowSubtitle(e={},t=false){const r=isBroadcastRadioShowContent(e);const i=e?.radioStationTypeId;let n=null;if(r){n=t?r:localize("FUSE.RadioStation.Attribution",{stationProviderName:r})}else if(i){const e=[...AllRadioStationKinds][i-1];if(RadioStationKindsForAlgoStation.has(e)&&e!==RadioStationKinds.STREAMING&&e!==RadioStationKinds.EDITORIAL){n=""}}return n}function isBroadcastRadioShowContentForMusicAPIAttributes(e={}){const t=e.stationProviderName;return get(e,"playParams.kind")==="radioStation"&&t}function getBroadcastRadioShowSubtitleForMusicAPIAttributes(e={},t=false){const r=isBroadcastRadioShowContentForMusicAPIAttributes(e);const i=e?.plainEditorialNotes?.short;let n=null;if(r){n=t?r:localize("FUSE.RadioStation.Attribution",{stationProviderName:r})}else if(i){n=i}else if(isAlgoGeneratedStationForMusicAPIAttributes(e)){n=""}return n}function getEpisodeNumberHeadline(e={}){let t=null;const r=e.episodeNumber;if(r){t=localize("FUSE.Radio.Episode",{num:r})}return t}function shouldDisplayMultiply(e){const t=get(e,"pageData.liveURLDataArray");if(!t){return false}const r=get(e,"pageData.fcStructure.model");const i=findFcKindIdsInModel(r,["489","488"]);return i}function getWordMarkString(e){if(!e){return}const t=e.replace("Apple Music"," Music");return t}function checkDataForIdenticalNotes(e=[],t){let r;const i=e.slice(0,3);const n=i.find(e=>{const i=t[e]?.itunesNotes?.standard;if(i&&!r){r=i}else if(i&&i===r){return true}return false});return!!n}const MetricsClickHandlers={baseItem:{onSelectionPerformed(e,t){recordClickEvent(...clickMetricsForImpressions(e,t));if(e.radioStationType==="discovery"){const e={eventType:"discoveryStationClicked"};Application.forwardEventForMessageEvaluation(e)}},onActionPerformed(e,t,r,i,n){const o=get(n,"target.kind");const s=get(n,"target.id");const a=get(n,"targetId");const l=metricsFieldsForBaseItemAction(t,r,o,s,a);if(l){recordClickEvent(...clickMetricsForImpressions(e,i,l))}}},searchLandingItem:{onSelectionPerformed(e,t){const r=metricsFieldsForSearchLandingItem(e.id);recordClickEvent(...clickMetricsForImpressions(e,t,r))}},searchLandingUpsell:{onSelectionPerformed(e,t){const r=metricsFieldsForSearchLandingUpsell(e,t,SearchLandingUpsell.ACTION.SELECT);recordClickEvent(...clickMetricsForImpressions(e,t,r))},onAccessoryButtonSelectionPerformed(e,t){const r=metricsFieldsForSearchLandingUpsell(e,t,SearchLandingUpsell.ACTION.ACCESSORY_BUTTON_SELECT);const i={targetId:r?.targetId,locationType:r?.targetType,name:e?.accessoryButtonTitle};recordClickEvent(...clickMetricsForImpressions(e,t,r,[i]))},onCloseButtonSelectionPerformed(e,t){const r=metricsFieldsForSearchLandingUpsell(e,t,SearchLandingUpsell.ACTION.CLOSE_BUTTON_SELECT);const i={id:r?.targetId,locationType:r?.targetType,name:e?.headline};if(e?.headline){Object.assign(i,{actionDetails:{title:e?.headline}})}recordClickEvent(...clickMetricsForImpressions(e,t,r,[i]))}},listenNowMusicSiriUpsell:{onSelectionPerformed(e,t){const r=metricsFieldsForListenNowMusicSiriUpsell(e,t);recordClickEvent(...clickMetricsForImpressions(e,t,r))}},shelf:{onAccessoryButtonSelectionPerformed(e,t){const r=metricsFieldsForShelfAccessoryButtonItem();const i={id:r?.targetId,locationType:r?.targetType,name:e?.accessoryButtonTitle};recordClickEvent(...clickMetricsForImpressions(e,t,r,[i]))}},containerDetailLink:{onSelectionPerformed(e,t){const r=metricsFieldsForContainerDetailLinkButtonItem(e);let i;if(r.targetId){i={id:r?.targetId,locationType:"button"}}if(r.targetId==="seeAll"){i.name="See All"}else if(e?.type){i.name=e?.title}if(e?.type){i.kind=e?.type}recordClickEvent(...clickMetricsForImpressions(e,t,r,[i]))}}};function createVideoArtwork(e){return Object.assign(new VideoArtwork,e)}function containsMotionArtistVideoForUbers(e){if(e?.motionArtistWide16x9||e?.motionArtistSquare1x1){return true}return false}function containsMotionDetailVideo(e){return!!(e?.motionDetailSquare||e?.motionDetailTall)}function getMotionDetailVideo(e){const t={};if(e.motionDetailSquare){t.motionDetailSquare=e.motionDetailSquare}if(e.motionDetailTall){t.motionDetailTall=e.motionDetailTall}return t}function excludeMotionDetailVideo(e){if(containsMotionDetailVideo(e)){const t=cloneDeep(e);if(t.motionDetailSquare){delete t.motionDetailSquare}if(t.motionDetailTall){delete t.motionDetailTall}return t}return e}function isMotionExcluded(){const e=["tr-tr","tr","nl-nl","nl","ar-sa","ar","th-th","th","ro-ro","ro","hi-in","hi","vi","vi-vn"];const t=getLanguageTag().toLowerCase();return e.indexOf(t)!==-1}function languageDoesNotSupportUberArtwork(){if(languageDoesNotSupportUberArtwork.uberSupportFlag!==null){return languageDoesNotSupportUberArtwork.uberSupportFlag}languageDoesNotSupportUberArtwork.uberSupportFlag=isMotionExcluded();return isMotionExcluded()}languageDoesNotSupportUberArtwork.uberSupportFlag=null;function containsMotionDetailTallVideo(e){return!!e?.motionDetailTall}function updateUberSupportFlag(){languageDoesNotSupportUberArtwork.uberSupportFlag=null;languageDoesNotSupportUberArtwork()}function createShelf(e){return Object.assign(new Shelf,e)}function createShelfSection(e){return Object.assign(new ShelfSection,e)}function createShelfItem(e){const t=createDefaultOptions(e);t.onFollowButtonSelectionPerformed=t=>{const r=get(e,"storePlatformDictionary");checkShouldSocialUpsellOnFollow(t,r)};if(e&&e.storePlatformDictionary){if(e.storePlatformDictionary.itunesNotes){e.storePlatformDictionary=sanitizeItunesNotes(e.storePlatformDictionary)}e.storePlatformDictionary=fixPlaylistCrop(e.storePlatformDictionary);if(!e.shouldNotOverride){Object.assign(e,overrideStorePlatformDictionary(e))}if(e.date){e.subtitle=getLastUpdated(get(e,"storePlatformDictionary.lastModifiedDate"))}const t=e.storePlatformDictionary.editorialVideo;if(containsMotionDetailVideo(t)){e.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(t),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(t)})}}const r=Object.assign(new ShelfItem,t,e);if(e&&e.sectionName){addClickMetricsHandlerToItem(r,()=>({actionDetails:{sectionName:e.sectionName}}))}return r}function createShelfFromLockups(e,t,{options:r={},sectionOptions:i={},itemOptions:n={}}={}){let o;const s=e.reduce((e,r)=>{const i=t[r];if(i&&CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){e.push(createShelfItem(Object.assign({storePlatformDictionary:i},n)))}return e},[]);if(i.uniformCellType&&i.uniformCellType===ShelfSection.UNIFORM_CELL_TYPE.ALBUM&&s.length<4){const e={height:ShelfSection.HEIGHT.COMPACT};Object.assign(i,e)}if(s.length>0){const e=[createShelfSection(Object.assign({items:s},i))];o=createShelf(Object.assign({sections:e},r,MetricsClickHandlers.shelf))}return o}function createItemsWithIterator(e,t,r){if(!r||!t){return null}const i=[];e.forEach(e=>{const n=e.contentId||e.id||e;const o=t[n];if(!o){return}const s=r(e,o);if(s){i.push(s)}});return i}function createShelfWithIterator(e,t,r,i,n){if(!r||!i||!n){return null}const o=createItemsWithIterator(e,t,r);if(!o||o.length===0){return null}const s=i();if(!s){return null}s.items=o;return n(Object.assign({sections:[s]}))}function createTopChartsShelfFromLockups(e,t,{options:r={},sectionOptions:i={}}={}){let n;const o=e.reduce((e,r)=>{const n=t[r];const o={};if(n&&CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){const t=get(n,"kind");if(t==="playlist"){i.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.ALBUM;e.push(createShelfItem(Object.assign({storePlatformDictionary:n},o)))}else{e.push(createShelfItem(Object.assign({storePlatformDictionary:n},o)))}}return e},[]);if(o.length>0){const e=[createShelfSection(Object.assign({items:o},i))];n=createShelf(Object.assign({sections:e},r))}return n}function createProfileShelfFromLockups(e,t={},{options:r={},sectionOptions:i={},itemOptions:n={}}={}){let o;const s=e.reduce((e,r)=>{const i=t[r.contentId];if(i&&CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){n.subtitle=getBroadcastRadioShowSubtitle(i);e.push(createShelfItem(Object.assign({storePlatformDictionary:i},n)))}return e},[]);if(s.length>0){if(e[0].contentType==="user"){i.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.ARTIST}else{i.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.ALBUM}const t=[createShelfSection(Object.assign({items:s},i))];o=createShelf(Object.assign({sections:t},r))}return o}function createSocialShelfItemWithFollowButton(e={}){const{storePlatformDictionary:t}=e;if(t){createSocialProfile({followState:SocialProfile.FOLLOW_STATE.NOT_FOLLOWING,storePlatformDictionary:t})}return createShelfItem(e)}const TV_SHOW_BRAND_TYPE_LINEAR="Linear";const TV_SHOW_BRAND_TYPE_NON_LINEAR="Non-Linear";const TV_SHOW_BRAND_TYPE_STANDALONE="Standalone";function findIsHD(e){let t;if(e.kind==="showBrand"){t=get(e,"hasHD")}else{const r=get(e,"offers[0].assets",[]);t=r.find(e=>e.flavor==="1080pHdVideo")}return!!t}function ratingsText(e){const t=get(e,"contentRatingsBySystem",{});const r=Object.keys(t);let i;if(r.length>0){const e=r[0];const n=t[e];i=get(n,"name")}return i}function findLanguageAttribute(e){let t;let r;const i=getBagValueSync("language");const n=get(e,"languageAttributes",[]);r=n.findIndex(e=>e.tag===i);if(r===-1){r=n.findIndex(e=>i.includes(e.tag))}if(r>0){t=n[r]}return t}function createBadgingItemsFromDictionary(e,t){const r=[{textGetter:e=>{let t;if(e.kind!=="tvEpisode"){t=get(e,"genreNames[0].name")||get(e,"genres[0].name")}return t}},{textGetter:e=>{let t;const r=get(e,"releaseDate");if(e.kind==="tvEpisode"){if(r){const e=new Date(r);t=e.toLocaleString(undefined,{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"})}}else{if(r){t=localizedYearStringFromReleaseDate(r)}}return t}},{textGetter:e=>{let t;const r=get(e,"offers[0].assets[0].duration");if(r&&(e.kind==="tvEpisode"||e.kind==="movie")){const e=Math.round(r/60);t=localize("FUSE.OC.Minutes",{minutes:convertNumberToLocaleString(e)})}return t}},{textGetter:e=>ratingsText(e),wantsTextBorderized:true},{textGetter:e=>{let r;let i;if(e.kind==="movie"){r=get(t,"languages.primary.hasClosedCaptioning")}else{const t=findLanguageAttribute(e);r=get(t,"hasClosedCaptioning")}if(r){i=localize("FUSE.Music.Show.Information.CC")}return i},wantsTextBorderized:true},{textGetter:e=>{let r;let i;if(e.kind==="movie"){r=get(t,"languages.primary.hasAudioDescription")}else{const t=findLanguageAttribute(e);r=get(t,"hasAudioDescription")}if(r){i=localize("FUSE.Music.Shows.Accessibility.Show.hasAD")}return i},wantsTextBorderized:true},{textGetter:e=>{let t;const r=findIsHD(e);if(r){t="HD"}return t},wantsTextBorderized:true}];return r.map(t=>({text:t.textGetter(e),wantsTextBorderized:t.wantsTextBorderized})).filter(e=>!!e.text).map(e=>createBadgingItem({text:e.text,wantsTextBorderized:e.wantsTextBorderized}))}function createCastItemsFromDictionary(e){let t;let r=[];const i=localize("FUSE.Music.Show.CastCrew");const n=[{key:"cast",title:"FUSE.Music.Show.Actors"},{key:"guests",title:"FUSE.Music.Show.Guest"},{key:"hosts",title:"FUSE.Music.Show.Hosts"},{key:"producers",title:"FUSE.Music.Show.Producer",canPlural:true},{key:"directors",title:"FUSE.Music.Show.Director",canPlural:true},{key:"screenwriters",title:"FUSE.Music.Show.Screenwriter",canPlural:true},{key:"performers",title:"FUSE.Music.Show.Performer"}];const o=get(e,"credits");if(o){const e=n.map(e=>{let t=get(e,"title");const r=get(o,e.key,[]);if(r.length&&r.length>1&&e.canPlural){t=localize(`${t}s`)}else{t=localize(t)}const i=r.map(e=>get(e,"name"));return{title:t,items:i}}).filter(e=>e.items.length>0);r=e.map(e=>createGroupedTextListItem(e))}if(r.length>0){t=createGroupedTextListViewModel({title:i,items:r})}return t}function buildLanguageFromDictionary(e){const t=get(e,"name");const r=["hasDolby71","hasDolby","hasStereo","hasSubtitles","hasClosedCaptioning","hasSDH"];const i=["FUSE.Music.Show.Languages.hasDolby71","FUSE.Music.Show.Languages.hasDolby","FUSE.Music.Show.Languages.hasStereo","FUSE.Music.Show.Languages.hasSubtitles","FUSE.Music.Show.Languages.hasClosedCaptioning","FUSE.Music.Show.Languages.hasSDH"];const n=r.map((t,r)=>{let n;const o=get(e,t);if(o){n=localize(i[r])}return n}).filter(e=>!!e);if(n.length>0){const e=n.join(", ");return`${t} (${e})`}return t}function accessibilityParse(e={}){let t;const r=[];if(e.kind==="showBrand"||e.kind==="tvEpisode"){t=findLanguageAttribute(e)}else if(e.componentName==="movie_page"){t=get(e,"languages.primary")}if(t){const e=get(t,"hasClosedCaptioning");const i=get(t,"hasAudioDescription");if(e){r.push(createItemizedTextListItem({title:localize("FUSE.OC.Languages.hasSDH"),text:localize("FUSE.Music.Shows.Accessibility.Show.SDH"),wantsTitleAsBadge:true}))}if(i){r.push(createItemizedTextListItem({title:localize("FUSE.Music.Shows.Accessibility.Show.hasAD"),text:localize("FUSE.Music.Shows.Accessibility.Show.AD"),wantsTitleAsBadge:true}))}}return r}function informationParse(e={}){const t=[];const r=get(e,"studioName");if(r){t.push(createItemizedTextListItem({title:localize("FUSE.Music.Show.Information.Studio"),text:r}))}const i=get(e,"releaseDate");if(i){t.push(createItemizedTextListItem({title:localize("FUSE.Music.Show.Information.Released"),text:localizedYearStringFromReleaseDate(i)}))}const n=get(e,"genreNames[0]");if(n){t.push(createItemizedTextListItem({title:localize("FUSE.Music.Show.Information.Genre"),text:n}))}const o=findIsHD(e);if(o){t.push(createItemizedTextListItem({title:localize("FUSE.Music.Show.Information.HD"),text:localize("FUSE.Music.Show.Information.HDVersions")}))}const s=ratingsText(e);if(s){t.push(createItemizedTextListItem({title:localize("FUSE.Music.Show.Information.Rating"),text:s}))}const a=get(e,"copyright");if(a){t.push(createItemizedTextListItem({text:a,wantsLeadingLineBreak:true}))}return t}function languageParseShows(e={}){const t=get(e,"languageAttributes");const r=[];const i=[];let n=[];if(t){let e=true;t.forEach(t=>{const n=buildLanguageFromDictionary(t);let o;if(t.isPrimary){o=localize("FUSE.Music.Show.Languages.Primary");r.push(createItemizedTextListItem({title:o,text:n}))}else{if(e){o=localize("FUSE.Music.Show.Languages.Additional");e=false}i.push(createItemizedTextListItem({title:o,text:n}))}})}n=r.concat(i);return n}function languageParseMovies(e={}){const t=get(e,"languages.primary");const r=get(e,"languages.additional");const i=[];if(t){const e=buildLanguageFromDictionary(t);const r=createItemizedTextListItem({title:localize("FUSE.Music.Show.Languages.Primary"),text:e});i.push(r)}if(r){let e=true;const t=r.map(t=>{const r=buildLanguageFromDictionary(t);let i;if(e){i=localize("FUSE.Music.Show.Languages.Additional");e=false}return createItemizedTextListItem({title:i,text:r})});i.push(...t)}return i}function createAccessibilityItemsFromDictionary(e={}){let t;const r=accessibilityParse(e);if(r.length>0){t=createItemizedTextListViewModel({title:localize("FUSE.Music.Show.Accessibility"),items:r})}return t}function createLanguageItemsFromDictionary(e={}){let t;let r=[];if(e.kind==="showBrand"){r=languageParseShows(e)}else if(e.componentName==="movie_page"||e.componentName==="episode_page"){r=languageParseMovies(e)}if(r&&r.length>0){t=createItemizedTextListViewModel({title:localize("FUSE.Music.Show.Languages"),items:r})}return t}function getHeadlineForEpisodeSubType(e){let t;switch(e){case"tvextra":t=localize("FUSE.Music.Show.Extra");break;case"seasonbonus":t=localize("FUSE.Music.Show.Extra");break;case"episodebonus":t=localize("FUSE.Music.Show.Extra");break;case"tvinterview":t=localize("FUSE.Music.Show.Interview");break;case"tvtrailer":t=localize("FUSE.Music.Show.Trailer");break;case"movie":t=localize("FUSE.Music.Show.Movie");break;default:t=localize("FUSE.Music.Show.Video");break}return t}function getBookKeeperForIds(e){return new Promise((t,r)=>{const i=new StorePlaybackPositionRequest;i.identifiers=e;i.onResponse=e=>{if(e){t(e)}else{r(new Error("No Bookkeeper response"))}};i.send()})}function brandTypeIsShow(e){return e===TV_SHOW_BRAND_TYPE_LINEAR||e===TV_SHOW_BRAND_TYPE_NON_LINEAR||e===TV_SHOW_BRAND_TYPE_STANDALONE}function getArtistSectionTitle(e){let t;const r=get(e,"kind","");switch(r){case"movie":t=localize("FUSE.OC.Show.ArtistsOnThisMovie");break;case"tvEpisode":t=localize("FUSE.OC.Episode.ArtistsOnThisEpisode");break;default:t=localize("FUSE.Music.Show.ArtistsOnShow");break}return t}function createArtistsInEpisode(e={},t){const r=get(e,"musicArtists",[]);let i;if(r.length>0){const n=t[e.id];const o=getArtistSectionTitle(n);i=createShelfFromLockups(r,t,{options:{title:o}})}return i}function createInformationItemsFromDictionary(e={}){const t=informationParse(e);let r;if(t&&t.length>0){r=createItemizedTextListViewModel({title:localize("FUSE.Music.Show.Information"),items:t})}return r}function createGrid(e){return Object.assign(new Grid,e)}function createGridSection(e){return Object.assign(new GridSection,e)}function createGridItem(e){const t=createDefaultOptions(e);t.onFollowButtonSelectionPerformed=t=>{const r=get(e,"storePlatformDictionary");checkShouldSocialUpsellOnFollow(t,r)};if(e&&e.storePlatformDictionary){e.storePlatformDictionary=fixPlaylistCrop(e.storePlatformDictionary);Object.assign(e,overrideStorePlatformDictionary(e));const t=e.storePlatformDictionary.editorialVideo;if(containsMotionDetailVideo(t)){e.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(t),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(t)})}}const r=Object.assign(new GridItem,t,e);if(e&&e.sectionName){addClickMetricsHandlerToItem(r,()=>({actionDetails:{sectionName:e.sectionName}}))}return r}function createGridItemButton(e){const t=createDefaultOptions(e);return Object.assign(new GridItemButton,t,e)}function createGridFromLockups(e,t,{options:r={},sectionOptions:i={},itemOptions:n={}}={}){let o;const s=e.reduce((e,r)=>{const i=t[r];if(i&&CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){e.push(createGridItem(Object.assign({storePlatformDictionary:i},n)))}return e},[]);if(s.length>0){const e=[createGridSection(Object.assign({items:s},i))];o=createGrid(Object.assign({sections:e},r))}return o}function createTopChartsGridFromLockups(e,t,{options:r={},sectionOptions:i={}}={}){let n;const o=e.reduce((e,r)=>{const n=t[r];const o={};if(n){const t=get(n,"kind");if(t==="playlist"){i.uniformCellType=GridSection.UNIFORM_CELL_TYPE.ALBUM;e.push(createGridItem(Object.assign({storePlatformDictionary:n},o)))}else{e.push(createGridItem(Object.assign({storePlatformDictionary:n},o)))}}return e},[]);if(o.length>0){const e=[createGridSection(Object.assign({items:o},i))];n=createGrid(Object.assign({sections:e},r))}return n}function createGridWithButtons(e=[],t){const r=createGridSection({items:e,title:t});const i=createGrid({sections:[r]});return i}function createGridWithButtonProperties(e=[],t){const r=e.map(createGridItemButton);return createGridWithButtons(r,t)}function createItemsWithIterator$1(e,t,r){if(!r||!t){return null}const i=[];e.forEach(e=>{const n=e.contentId||e.id||e;const o=t[n];if(!o){return}const s=r(e,o);if(s){i.push(s)}});return i}function createGridWithIterator(e,t,r,i,n){if(!r||!i||!n){return null}const o=createItemsWithIterator$1(e,t,r);if(!o||o.length===0){return null}const s=i({items:o});if(!s){return null}return n({sections:[s]})}function createVerticalStack(e){return Object.assign(new VerticalStack,e)}const BaseClass=mix(ComponentController).with(MetricsMixin);function createChildViewModels(e=[],t){const r=[];const i=[];e.forEach(e=>{const r=t[e];if(r){i.push(createGridItem({storePlatformDictionary:r}))}});if(i.length>0){r.push(createGrid({sections:[createGridSection({items:i})]}))}return r}class SeeAllController extends BaseClass{constructor({contentIds:e,title:t,pageMetrics:r,pageFields:i,nextPageURL:n,onDidRequestNextPageURL:o,gridItemCreator:s}={}){super(...arguments);this.contentIds=e;if(t){this.headerItem.title=t;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}this.pageMetrics=r;this.pageFields=i;this.nextPageURL=n;this.gridItemCreator=s;if(o){this.onDidRequestNextPageURL=o}}didLoad(){super.didLoad();this.loadPage()}didAppear(){this.pageContext=currentPageContext();super.didAppear()}createPageMetrics(){if(this.pageFields){const e=combineWithSeparator(this.pageFields.pageType,"SeeAll");this.pageFields.pageType=e;this.pageFields.page=combineWithSeparator(e,this.pageFields.pageId)}}onDidRequestNextPageURL(){}onNeedsAdditionalChildViewModels(e){if(!e){return}this.viewModel.onNeedsAdditionalChildViewModels=null;fetchJSONWithStorePlatformData(e,{getIdsMissingStorePlatformData:e=>get(e,"ids",[])}).then(e=>{const t=get(e,"ids",[]);const r=get(e,"storePlatformData.lockup.results",{});const i=createChildViewModels(t,r);const n=get(e,"next");this.onDidRequestNextPageURL(t);if(i.length>0){this.viewModel.appendChildViewModels(i)}if(n){this.viewModel.onNeedsAdditionalChildViewModels=this.onNeedsAdditionalChildViewModels.bind(this,n)}})}createViewModel(e=[],t,r){const i=this.gridItemCreator?this.gridItemCreator:createGridItem;let n;const o=e.reduce((e,r)=>{const n=t[r];if(n){e.push(i({storePlatformDictionary:n}))}return e},[]);if(o.length>0){const e=[createGridSection({items:o})];const t=o[0]?.storePlatformDictionary?.kind==="artist"||e[0]?.uniformCellType==="artist";const i=t?Grid.ADAPTIVE_LAYOUT_STYLE.COMPACT_LIST:Grid.ADAPTIVE_LAYOUT_STYLE.DEFAULT;const s={sections:e,adaptiveLayoutStyle:i};const a=[createGrid(s)];n=createVerticalStack({childViewModels:a});if(r){n.onNeedsAdditionalChildViewModels=this.onNeedsAdditionalChildViewModels.bind(this,r)}}return n}loadPage(){return fetchContent({ids:this.contentIds}).then(e=>this.createViewModel(this.contentIds,e,this.nextPageURL)).then(e=>{this.createPageMetrics();this.viewModel=e}).then(()=>{this.considerRecordingPageEvent()}).catch(e=>{logger$5.error(e);const t=userFacingMessageForError(e);if(t){this.viewModel=createMessageViewModel({message:t})}})}}function createParagraph(e){return Object.assign(new ParagraphViewModel,e)}function createContainerDetailLink(e){return Object.assign(new ContainerDetailLink,e)}function createSplitWidgetViewModel(e){return Object.assign(new SplitWidgetViewModel,e)}function createBiographyViewModel(e){return Object.assign(new BiographyViewModel,e)}function createBiographyItem(e){return Object.assign(new BiographyItem,e)}const MAX_SHELF_ITEMS=8;const MAX_GRID_ITEMS=8;const MULTIROOM_MAX_SHELF_ITEMS=24;function decorateShelfWithSeeAll(e={},t){const{seeAllUrl:r,contentIds:i=[],title:n}=t;const o=createContainerDetailLink({onSelect:()=>{if(r){return createPushSegueForURL(r)}return createPushSegue({componentController:new SeeAllController({contentIds:i,title:n})})}});Object.assign(o,MetricsClickHandlers.containerDetailLink);Object.assign(e,{containerDetailLink:o});return e}function getPhoneArtistPromoArt(e={}){const t=get(e,"editorialArtwork.vipSquare");const r=get(e,"hero.[0].content.[0].artwork");const i={};if(t){i.dictionary=t;i.cropStyle="sr";return i}if(r){i.dictionary=r;i.cropStyle="sr";return i}}function getPadArtistPromoArt(e={},t={}){if(Device.model==="iPad"){const r=get(e,"editorialArtwork.centeredFullscreenBackground");const i=get(t,"heroImage.safeCropCodes",{});const n=get(t,"heroImage.artwork");const o={};if(r){o.dictionary=r;o.cropStyle="eo";return o}if(i.vc){o.dictionary=n;o.cropStyle="vc";return o}}}function shouldUseSplitView(e){const t=get(e,"[0].sectionName");const r=get(e,"[1].sectionName");const i=["featuredRelease","latestRelease"].indexOf(t)!==-1;if(i){return r==="topSongs"}return false}function getPreReleaseDate(e={}){const t=get(e,"offers",[]);const r=t.find(e=>e.type==="preorder");return get(r,"expectedReleaseDate")}function getReleaseYear(e,t){const r=e.isPreorder?getPreReleaseDate(e):e.releaseDate;let i;if(r){i=localizedYearStringFromReleaseDate(e.releaseDate)}else if(e?.collectionId){const r=t?.lockup?.results[e.collectionId];i=localizedYearStringFromReleaseDate(r?.releaseDate)}return i}function getTrackCountCopy(e=0){let t;const r=parseInt(e,10);if(r){t=r>1?localize("FUSE.Artist.Bio.TrackCount.Plural",{trackCount:r}):localize("FUSE.Artist.Bio.TrackCount.Singular",{trackCount:r})}return t}function getFeaturedContentGridHeadline(e={},t={}){let r;let i=t.title;const n=e.kind;const o=t.sectionName;const s=e.isPreorder?getPreReleaseDate(e):e.releaseDate;if(s){r=formatDateWithUTC(s);if(e.isPreorder){r=localize("FUSE.Artist.Bio.PreRelease.Date",{date:r})}}switch(n){case"movie":case"iTunesBrand":case"showBrand":r=Device.model==="iPad"?" ":i;break;case"tvEpisode":{r=Device.model==="iPad"?formatDateWithUTC(get(e,"releaseDate")):i;break}case"playlist":{if(Device.model==="iPad"){const t=getLastUpdated(e.lastModifiedDate);if(t){i=t}}r=i;break}case"uploadedAudio":case"uploadedVideo":{if(Device.model==="iPad"){const t=formatDateWithUTC(e.uploadDate);if(t){i=localize("FUSE.Artist.Bio.Upload.Date",{uploadDate:t})}}r=i;break}default:{if(Device.model!=="iPad"&&o==="featuredRelease"&&!e.isPreorder){r=i}}}return r}function getDurationFromOffers(e=[]){const t=e.find(e=>e.type==="subscription");const r=get(t,"assets",[]);const i=r.find(e=>e.duration);const n=get(i,"duration");if(n){return getFormatedDurationFromSeconds(n)}}function getFeaturedContentGridSubtitle(e={}){let t=null;const r=e.kind;switch(r){case"movie":{const r=getDurationFromOffers(e.offers);const i=localizedYearStringFromReleaseDate(e.releaseDate);if(r&&i){t=`${i} • ${r}`}break}case"playlist":{const r=get(e,"childrenIds",[]);t=getTrackCountCopy(r.length);break}case"tvEpisode":t=e.artistName;break;case"iTunesBrand":{const r=sanitizeItunesNotes(e);t=r.itunesNotes?.tagline||"";break}case"showBrand":{break}case"musicVideo":t=getDurationFromOffers(e.offers);break;case"uploadedAudio":case"uploadedVideo":t=getFormatedDurationFromSeconds(get(e,"duration"));break;case"radioStation":{const r=sanitizeItunesNotes(e);t=r.itunesNotes?.standard||"";break}default:t=getTrackCountCopy(e.trackCount)}return t}function createFeaturedContentGrid(e={},t){const r=e.adamIds||[];const i=e.sectionName;const n=r.slice(0,1);const o=t[n[0]];if(!o){return}const s=getFeaturedContentGridHeadline(o,e);const a=getFeaturedContentGridSubtitle(o);const l=get(o,"kind");let c;let u;if(Device.model==="iPad"){c=e.title}if(l==="showBrand"){u=createArtwork({dictionary:o.artwork,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP})}if(l==="movie"){if(o.editorialArtwork?.browseCover){o.artwork=o.editorialArtwork?.browseCover}u=createArtwork({dictionary:o.artwork})}const d={storePlatformDictionary:o,sectionName:i,headline:s,subtitle:a};if(u){d.backgroundArtwork=u}const g=createGridFromLockups(n,t,{itemOptions:d,sectionOptions:{title:c,uniformCellType:GridSection.UNIFORM_CELL_TYPE.SHOWCASE}});return g}function shelfSectionUniformCellTypeForSectionName(e){if(!e){return null}let t=null;switch(e){case"featuredAlbums":t=ShelfSection.UNIFORM_CELL_TYPE.FEATURED_PLAYLIST;break;case"recentVideos":if(Device.model!=="iPad"){t=ShelfSection.UNIFORM_CELL_TYPE.FEATURED_MUSIC_VIDEO}break;case"radioShows":t=ShelfSection.UNIFORM_CELL_TYPE.FEATURED_PLAYLIST;break;case"moreToHear":case"playlists":t=ShelfSection.UNIFORM_CELL_TYPE.ALBUM;break;default:t=null}return t}function getFeaturedArtistSubtitle(e={}){const{storePlatformDictionary:t,artistId:r,sectionName:i,storePlatformData:n}=e;const o=["appearsOnAlbums","playlists"].indexOf(i)!==-1;if(!t||o){return null}const s=t.kind;const a=["moreToHear","moreToSee"];const l=a.indexOf(i)!==-1;const c=["liveAlbums","albums","fullAlbums","recentVideos"];const u=c.indexOf(i)!==-1;let d=null;switch(s){case"uploadedAudio":if(t.uploadingBrandShortName){d=t.uploadingBrandShortName}break;case"uploadedVideo":case"movie":case"tvEpisode":{const e=get(t,"duration");d=e?getFormatedDurationFromSeconds(Math.round(e)):getDurationFromOffers(get(t,"offers"));break}case"iTunesBrand":{const e=sanitizeItunesNotes(t);const r=e.itunesNotes?.short;if(r){d=r}break}case"radioStation":{const e=sanitizeItunesNotes(t);const r=e.itunesNotes?.standard;if(r){d=r}break}default:{const e=getReleaseYear(t,n);if(t.artistId===r&&!l){const r=t.collectionName;const i=isMusicVideoKind(get(t,"kind"));d=r&&!i?`${r} · ${e}`:e}else{d=u?e:`${t.artistName} · ${e}`}}}return d}function createArtistContentShelf(e={},t,r,i=MAX_SHELF_ITEMS,n){const o=e.adamIds||[];const s=o.slice(0,i);const a=e.sectionName;const itemIteratorCallback=(e,t)=>{const i={};if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(t)){return null}if(a==="featuredAlbums"){i.description=t?.itunesNotes?.standard}else if(a==="radioShows"){i.description=t?.itunesNotes?.short}if(a){i.sectionName=a}i.subtitle=getFeaturedArtistSubtitle({storePlatformDictionary:t,artistId:r,sectionName:a,storePlatformData:n});Object.assign(i,getVerticalVideoArtworkProperties(t));return createShelfItem(Object.assign({storePlatformDictionary:t},i))};const sectionIteratorCallback=()=>{const e=shelfSectionUniformCellTypeForSectionName(a);const t={uniformCellType:e};return createShelfSection(t)};const shelfCallback=t=>{const r={title:e.title};return createShelf(Object.assign(t,r))};const l=createShelfWithIterator(s,t,itemIteratorCallback,sectionIteratorCallback,shelfCallback);if(l&&s.lengthcreateNowPlayingSegue({storePlatformDictionary:t})}else if(isMusicVideoKind(r));else{i=createPushSegueHandler(e)}return i}function createDefaultOptions(e={}){let t;if(get(e,"target")==="external"){t=()=>createRedirectSegue(e)}else if(get(e,"target")==="overlay"){t=()=>createStoreFlowSegue(e)}else{t=createOnSelectHandler(e)}return Object.assign({onSelect:t},MetricsClickHandlers.baseItem)}function fixPlaylistCrop(e={}){const t=get(e,"kind");if(t==="playlist"){const t=get(e,"artwork.url","");const r=get(e,"editorialArtwork.subscriptionCover.url","");if(t){e.artwork.url=t.replace("{c}","cc")}if(r){e.editorialArtwork.subscriptionCover.url=r.replace("{c}","cc")}}return e}function fixBrickPlaylistCrop(e={}){const t=get(e,"kind");if(t==="playlist"){const t=get(e,"editorialArtwork.subscriptionCover.url","");if(t){e.editorialArtwork.subscriptionCover.url=t.replace("{h}cc","{h}{c}")}}return e}function overrideSocialProfile(e){let t;if(e){const r=get(e,"kind");if(r==="socialProfile"){t=cloneDeep(e);t.handle=`@${t.handle}`}else{t=e}}return t}function overrideStorePlatformDictionary(e){const t=get(e,"storePlatformDictionary");const r=get(t,"kind");const i=get(t,"iTunesBrandType");const n=brandTypeIsShow(i);if(r==="iTunesBrand"&&!n){const r=get(t,"editorialArtwork.brandLogo");if(r){const i=get(t,"iTunesBrandType");let n=Artwork.TREATMENT.DEFAULT;if(i!=="Show"){n=Artwork.TREATMENT.CIRCLE}const o=get(t,"broadcastLocation");if(o){e.subtitle=o}const s=createArtwork({dictionary:r,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP,treatment:n});Object.assign(e,{storePlatformDictionary:t,backgroundArtwork:s})}}if(r==="brand"||r==="activity"){const r=get(t,"editorialArtwork.brandLogo");if(r){const i=createArtwork({dictionary:r,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP});Object.assign(e,{storePlatformDictionary:t,backgroundArtwork:i})}}if(r==="user"){const r=get(t,"artwork");if(r){const i=createArtwork({dictionary:r,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP,treatment:Artwork.TREATMENT.CIRCLE});Object.assign(e,{storePlatformDictionary:t,backgroundArtwork:i})}}if(r==="uploadedAudio"){const r=get(t,"artwork");if(r){const i=createArtwork({dictionary:r,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP});Object.assign(e,{storePlatformDictionary:t,backgroundArtwork:i})}}if(r==="socialProfile"){e.storePlatformDictionary=overrideSocialProfile(t)}if(e.featuredArtistSubtitle){const t=getFeaturedArtistSubtitle(e);Object.assign(e,{subtitle:t})}return e}function replaceAndAmpWithAmpersand(e){let t="";if(e&&e.replace){t=e.replace(/&|\\u0026amp;/gi,"&")}return t}function sanitizeString(e){let t="";if(e&&e.replace){t=e.replace(/(<([^>]+)>)/gi,"");t=replaceAndAmpWithAmpersand(t)}return t}function sanitizeStringAndEnableTags(e){let t="";if(e&&e.replace){t=e.replace("
","
");t=replaceAndAmpWithAmpersand(t)}return t}function sanitizeItunesNotes(e={}){const t=e.itunesNotes?.short;const r=e.itunesNotes?.standard;const i=e.itunesNotes?.tagline;if(t){e.itunesNotes.short=sanitizeString(t)}if(r){e.itunesNotes.standard=sanitizeString(r)}if(i){e.itunesNotes.tagline=sanitizeString(i)}return e}function getContentIdList(e=[]){return e.map(e=>e.contentId||e.entityId)}function findChildren(e){let t=[];if(e instanceof VerticalStack){t=e.childViewModels}else if(e instanceof PlaylistDetail){t=e.footerViewModels}else if(Array.isArray(e)){t=e}return t}function setChildren(e,t){if(t&&Array.isArray(t)){if(e instanceof VerticalStack){e.childViewModels=t}else if(e instanceof PlaylistDetail){e.footerViewModels=t}}}function removeItemFromParent(e,t){const r={Shelf:createShelfSection,Grid:createGridSection};let i;const n=findChildren(e);const o=n.findIndex(e=>e===t);if(o>=0){n.splice(o,1);return n}const s=n.findIndex(e=>{const r=get(e,"sections[0].items",[]);const n=r.findIndex(e=>e===t);if(n>=0){i=n;return true}return false});const a=get(n,`[${s}]`,{});const l=get(a,"sections[0]");const c=r[a.constructor.name];if(l&&l.items&&c){const t=get(l,"items",[]);if(t&&t.length===1&&a.sections&&a.sections.length===1){n.splice(s,1);setChildren(e,n)}else if(t&&t.length>0){const e=c();t.splice(i,1);Object.assign(e,l);e.items=t;n[s].sections=[e]}}return n}function containsMixedContent({ids:e=[],lockupData:t={}}){let r;const i=e.find(e=>{const i=get(t[e],"kind");if(i&&!r){r=i}else if(i&&i!==r){return true}return false});return!!i}function getMixedContentTypes({ids:e=[],lockupData:t={}}){const r=new Map;e.forEach(e=>{const i=e?.contentId||e;const n=t[i]?.kind;if(n&&!r.get(n)){r.set(n,1)}else if(n&&r.get(n)){r.set(n,r.get(n)+1)}});return r}function getKindsFromMixedContent(e=[],t={}){const r=[];let i;e.forEach(e=>{const n=t[e]?.kind;if(n&&!i){i=n;r.push(i)}else if(n&&n!==i&&r.indexOf(n)===-1){r.push(n)}});return r}function createSocialProfile(e){return Object.assign(new SocialProfile,e)}function createSocialProfileCollection(e){return Object.assign(new SocialProfileCollection,e)}function createSocialProfileCollectionItem(e){return Object.assign(new SocialProfileCollectionItem,e)}function createSocialProfileCollectionFromLockups({ids:e=[],lockupData:t={},followStates:r={},collectionStyle:i=SocialProfileCollection.COLLECTION_STYLE.DEFAULT}={}){const n=e.filter(e=>!!t[e]).map(e=>{const i=overrideSocialProfile(t[e]);return createSocialProfileCollectionItem({profile:createSocialProfile({storePlatformDictionary:i,followState:r[e]}),onSelect:()=>createPushSegueForStoreContent(i)})});if(n.length===0){return}return createSocialProfileCollection({items:n,collectionStyle:i})}const actionForFollowState={[SocialProfile.FOLLOW_STATE.NOT_FOLLOWING]:"follow",[SocialProfile.FOLLOW_STATE.FOLLOWING]:"unfollow",[SocialProfile.FOLLOW_STATE.BLOCKED]:"unblock",[SocialProfile.FOLLOW_STATE.REQUESTED]:"cancelRequest"};function followButtonActionForSocialProfileId(e){const t=get(Store,["account","userSocialProfile","followeeStates",e],SocialProfile.FOLLOW_STATE.NOT_FOLLOWING);return actionForFollowState[t]}function badgingClickMetricsHandler(e){const t=get(e,"accessorySocialProfiles.length",0);if(t>0){return{actionDetails:{badgeCount:t}}}}function recordFollowButtonClick(e){const t=followButtonActionForSocialProfileId(e);recordClickEvent({actionType:"select",actionDetails:{action:t},targetType:"button"},{pageContext:currentPageContext()})}let badgingDataCache;let badgingDataExpiryTime;let userFolloweesHaveChangedSinceLastBadgingDataFetch=false;let badgingDataFetchPromise;function onUserFolloweesDidChange(){userFolloweesHaveChangedSinceLastBadgingDataFetch=true}function isBadgingDataFresh(){return!!badgingDataCache&&!userFolloweesHaveChangedSinceLastBadgingDataFetch&&Date.now(){const t={shouldIgnoreCache:userFolloweesHaveChangedSinceLastBadgingDataFetch};return requestMusicAPIResponse(e,t)}).then(e=>{userFolloweesHaveChangedSinceLastBadgingDataFetch=false;badgingDataCache=e||{};badgingDataExpiryTime=e?.expirationDate;badgingDataFetchPromise=null;return cloneDeep(badgingDataCache)});badgingDataFetchPromise=e}return e}function fetchSocialProfiles(e){return fetchContent({ids:e}).then(e=>{const t={};Object.keys(e).forEach(r=>{const i=e[r];const n=createSocialProfile({storePlatformDictionary:i,backgroundArtwork:createArtwork({dictionary:i.avatarArtwork})});t[r]=n});return t})}function walkSection(e,t){e.items.forEach(e=>t(e))}function walkSections(e,t){e.forEach(e=>walkSection(e,t))}function walkViewModelForBadgableItems(e,t){if(!e){return}switch(e.constructor){case VerticalStack:case SocialProfileVerticalStack:if(e.childViewModels){e.childViewModels.forEach(e=>walkViewModelForBadgableItems(e,t))}break;case Grid:case Shelf:if(e.sections){walkSections(e.sections,t)}break}}function collectViewModelItemsWithSocialNetworkActivity(e,t,r=[]){const i={};const n=new Set;walkViewModelForBadgableItems(e,e=>{let o=get(e,"storePlatformDictionary.id");if(e.doNotSocialBadge){return}if(!o){o=get(e,"identifierSet.storeAdamID")}if(!o){const r=get(e,"identifierSet.catalogIds");if(r){o=r.find(e=>!!t[e])}}let s=t[o]||[];if(r.length&&s.length){s=s.filter(e=>r.indexOf(e)===-1)}if(s.length){s=s.slice(0,3);const t=i[o]||[];t.push(e);i[o]=t;s.forEach(e=>n.add(e))}else if(e.accessorySocialProfiles&&e.accessorySocialProfiles.length){e.accessorySocialProfiles=[]}});return Promise$1.resolve([i,n])}function removeBadgingFromViewModel(e){walkViewModelForBadgableItems(e,e=>{if(e.accessorySocialProfiles&&e.accessorySocialProfiles.length){e.accessorySocialProfiles=[]}})}function badgeViewModelItems(e,t,r){Object.keys(t).forEach(i=>{const n=t[i];const o=e[i];const s=[];o.forEach(e=>{if(r[e]){s.push(r[e])}});n.forEach(e=>{e.accessorySocialProfiles=s;addClickMetricsHandlerToItem(e,badgingClickMetricsHandler)})});return Promise$1.resolve(e)}const excludedSocialProfileIDsFromBadgingSymbol=Symbol("excludedSocialProfileIDsFromBadging");class SocialProfileBadgingController{static initializeBadging(){return Promise$1.all([shouldSocial(),isSocialOnboarded()]).then(([e,t])=>{if(!e){return Promise$1.resolve()}if(!t){subscribe(USER_SOCIAL_PROFILE_DID_CHANGE,SocialProfileBadgingController.initializeBadging);return Promise$1.resolve()}unsubscribe(USER_SOCIAL_PROFILE_DID_CHANGE,SocialProfileBadgingController.initializeBadging);subscribe(USER_FOLLOWEES_DID_CHANGE,onUserFolloweesDidChange);return fetchBadgingData()})}static isContentBeingListenedToByFriends(e){return!!badgingDataCache?.body?.results?.badgingMap?.[e]}static clearBadgingDataCache(){badgingDataCache=null}badgeViewModel(e,t=false){return Promise$1.all([shouldSocial(),isSocialOnboarded()]).then(([r,i])=>{if(!r||!i){this.removeBadging(e);return Promise$1.resolve()}return fetchBadgingData().then(r=>{const i=r?.body?.meta?.versionHash;const n=t||!this.badgingVersionHash||this.badgingVersionHash!==i;if(!n){return Promise$1.resolve()}const o=r?.body?.results?.badgingMap??{};return this.performBadging(e,o,i)})}).catch(e=>logger$5.error("Failed to badge view model",this.badgingVersionHash,e))}get excludedSocialProfileIDsFromBadging(){return this[excludedSocialProfileIDsFromBadgingSymbol]}set excludedSocialProfileIDsFromBadging(e){this[excludedSocialProfileIDsFromBadgingSymbol]=e}performBadging(e,t,r){this.badgingVersionHash=r;const i=this.excludedSocialProfileIDsFromBadging||[];return collectViewModelItemsWithSocialNetworkActivity(e,t,i).then(([e,t])=>Promise$1.all([e,fetchSocialProfiles(t)])).then(([e,r])=>badgeViewModelItems(t,e,r))}removeBadging(e){if(this.badgingVersionHash){removeBadgingFromViewModel(e);this.badgingVersionHash=null}}}function SocialProfileBadgingMixin(e){const t=class extends e{constructor(...e){super(...e);this.socialProfileBadgingController=new SocialProfileBadgingController}badgeViewModel(e=false){this.socialProfileBadgingController.badgeViewModel(this.viewModel,e)}get excludedSocialProfileIDsFromBadging(){return this.socialProfileBadgingController.excludedSocialProfileIDsFromBadging}set excludedSocialProfileIDsFromBadging(e){this.socialProfileBadgingController.excludedSocialProfileIDsFromBadging=e}};return t}function createFlowcase(e){const t={playActivityFeatureName:"flowcase"};return Object.assign(new Flowcase,e,t)}function createFlowcaseItem(e){const t=createDefaultOptions(e);return Object.assign(new FlowcaseItem,t,e)}function getLiveURLData(e,t){const r=get(e,"liveURL");const i=get(t,"pageData.liveURLData");let n;if(r&&i&&i.upcomingShows&&i.upcomingShows instanceof Array){n=i}return n}function getLiveURLHeroData(e={},t={},r={}){const i={width:4320,height:1080,url:e.heroArtworkUrl,supportsLayeredImage:false};const n=createArtwork({dictionary:i,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});const o=createArtwork({dictionary:get(t,"artwork")});const s=FlowcaseItem.THUMBNAIL_HORIZONTAL_ALIGNMENT.TRAILING;return Object.assign({storePlatformDictionary:t,thumbnailArtwork:o,thumbnailHorizontalAlignment:s,backgroundArtwork:n,title:e.title,subtitle:e.subtitle,descriptionTitle:localize("FUSE.Radio.ListenNowButton"),description:e.description},r)}const timerMap=new WeakMap;function addTimer(e,t){let r=timerMap.get(e);if(!r){r=new Set;timerMap.set(e,r)}r.add(t)}function removeTimer(e,t){const r=timerMap.get(e);r.delete(t)}function setTimer(e,t){const r=new Timer;r.delay=e;r.onTimeout=()=>{removeTimer(this,r);t.call(this)};addTimer(this,r);r.schedule()}function addLiveRadioTimer(e,t,r){const i=5e3;const onTimeout=()=>{const n=r()+i;t(e);setTimer.call(this,n,onTimeout)};onTimeout()}function clearLiveRadioTimers(e){const t=timerMap.get(e);if(t){t.forEach(e=>e.cancel());t.clear()}}function constructLiveRadioCaseDateFormatter(e){if(!DateFormattingOptions){return}const t=[];const r=isUsing24HourLocaleSync();if(isClientUsingEnglishBasedDateLocale()){t.push(" ");if(!r){t.push(":00")}}const i=r?"HHm":"hm";const n={template:i,dateStyle:DateFormattingOptions.STYLE.SHORT,timeStyle:DateFormattingOptions.STYLE.SHORT,stringFormat:e,excludedPatterns:t};return constructDateFormatter(n)}function getFormattedDayString(e){let t="";if(e){const r=new Date(e);const i=new Date(Date.now());const n=undefined;const o=i.toLocaleString(n,{month:"short",day:"numeric"});const s=localize("FUSE.Date.today");t=r.toLocaleString(n,{month:"short",day:"numeric"});t=o===t?s:t}return t}function getRemainingTime(e={}){const t=get(e,"endTime");const r=144e5;const i=Date.now();const n=new Date(t);const o=Math.abs(n.getTime()-i);return o=i.getTime()){o=a[s];o.showIndex=s}}}}return o}function getCurrentShow(e){let t;if(e){t=getCurrentRadioShowFromLiveData(e)}return t}function resetItems(e,t,r){const i=processChildFeaturedNodes.call(this,e,t);r.items=i}const MEDIA_PICKER_TYPES_FOR_STORE_PLATFORM_KIND={activity:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.RADIO_STATION]),album:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG]),artist:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MOVIE,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MUSIC_VIDEO,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.RADIO_STATION,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG]),brand:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MUSIC_VIDEO]),iTunesBrand:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MUSIC_VIDEO,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.RADIO_STATION]),movie:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MOVIE,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MUSIC_VIDEO,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG]),musicVideo:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MUSIC_VIDEO]),playlist:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MUSIC_VIDEO,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG]),radioStation:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.RADIO_STATION]),showBrand:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG,MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.TV_EPISODE]),song:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG]),tvEpisode:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.TV_EPISODE]),tvSeason:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.TV_EPISODE]),uploadedAudio:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.SONG]),uploadedVideo:new Set([MediaPickerEnvironment.MUSIC_TYPE_IDENTIFIER.MUSIC_VIDEO])};const MediaPicker={typeIdentifiersFromMediaPickerEnvironment(e){if(!e){return}const t=e.musicTypeIdentifiers;if(!t||t.length===0){return}return t},shouldShowItemWithKind(e,t){if(!e){return true}const r=MEDIA_PICKER_TYPES_FOR_STORE_PLATFORM_KIND[e];if(!r){return true}const i=t.find(e=>r.has(e));return!!i},shouldShowItemWithStorePlaformDictionary(e,t){if(!(t instanceof ComponentController)){logger$5.warn("shouldShowItemWithStorePlaformDictionary must be called with ComponentController instance.")}const r=get(t,"environment.mediaPickerEnvironment");const i=MediaPicker.typeIdentifiersFromMediaPickerEnvironment(r);if(!i){return true}const n=get(e,"kind");if(!n){return false}return MediaPicker.shouldShowItemWithKind(n,i)}};function resetItems$1(e,t,r){const i=processChildFeaturedNodes.call(this,e,t);r.items=i}function processFlowcaseItemLive(e,t){const onSelect=()=>{const r=get(e,"curatorId");const i=r?createPushSegueForID(r.toString()):createPushSegueForURL("https://itunes.apple.com/beats1");const n=createRadioPlaybackIntent({radioStationStorePlatformDictionary:t});i.playbackIntent=n;return i};const r=getLiveURLHeroData(e,t,{onSelect:onSelect});const i=createFlowcaseItem(r);const n=constructDateRangeDescriptor(e.startTime,e.endTime);const o=constructLiveRadioCaseDateFormatter(`${localize("FUSE.Radio.Beats1Live")} • %@`);const s=constructValueTransformerOptions(o,"headline",n);i.applyValueTransformer(s);return i}function getFlowcaseDescription({storePlatformDictionary:e,subtitle:t}){const r=e?.kind;const i=["artist","album","brand","song","playlist","movie","musicVideo","uploadedVideo","uploadedAudio","tvEpisode","radioStation"].indexOf(r)!==-1;const n=e?.iTunesBrandType;const o=e?.itunesNotes?.short??"";let s="";let a;if(o!==""&&(i||r==="iTunesBrand"&&(n==="Show"||n==="Genre"||n==="Curator"))){a=sanitizeString(o);if(t!==a){s=a}}return s}function getFlowcaseThumbnailHorizontalAlignment({storePlatformDictionary:e}){const t=get(e,"kind");const r=["artist","album","song","playlist","musicVideo","uploadedVideo","uploadedAudio"].indexOf(t)!==-1;let i;if(t==="tvEpisode"){const t=get(e,"artwork");if(t){i=FlowcaseItem.THUMBNAIL_HORIZONTAL_ALIGNMENT.RIGHT}}else if(r){i=FlowcaseItem.THUMBNAIL_HORIZONTAL_ALIGNMENT.TRAILING}return i}function getFlowcaseSubtitle({storePlatformDictionary:e}){const t=get(e,"kind");const r=["album","song","playlist","musicVideo","uploadedVideo","uploadedAudio"].indexOf(t)!==-1;const i=get(e,"itunesNotes.tagline");const n=get(e,"genreNames.[0]");const o=get(e,"itunesNotes.short");const s=get(e,"itunesNotes.standard");const a=o||s||"";const l=get(e,"iTunesBrandType");const c=["Curator","Genre","Show","Linear","Non-Linear"].indexOf(l)!==-1;const u=e?.artistName;let d;switch(t){case"movie":d=i||n;break;case"artist":d=n;break;case"activity":d=i||o;break;case"brand":d=i;break;case"iTunesBrand":if(l==="Show"&&c){d=i}else if(c){d=i}else{d=a}break;case"showBrand":if(c){d=i||o}else{d=a}break;case"tvEpisode":if(u){d=u}break;case"radioStation":d=e?.streamingRadioSubType==="Episode"?s:i;break;default:if(r){d=e.curatorName||e.artistName}else{d=a}}return sanitizeString(d)}function processFlowcaseImageDictionaryDimensions(e={}){if(e.width<1e3){e.width=4320;e.height=1080}return e}function processFlowcaseItemStorePlatform(e,t){const r=get(t,"kind");const i=get(t,"name");const n=get(e,"designBadge");const o=get(t,"editorialArtwork.subscriptionCover");const s=get(t,"editorialArtwork.subscriptionHero");const a=get(t,"url");const l={};const c=["playlist","radioStation","iTunesBrand","brand","activity","uploadedAudio","uploadedVideo"].indexOf(r)!==-1;const u=["tvEpisode","song","musicVideo","album","uploadedVideo","uploadedAudio"];let d=c?s||o:s;let g;if(d){d=processFlowcaseImageDictionaryDimensions(d);const e=createArtwork({dictionary:d,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});const o=getFlowcaseSubtitle({storePlatformDictionary:t});Object.assign(l,{storePlatformDictionary:t,backgroundArtwork:e,headline:n,title:i,subtitle:o,description:getFlowcaseDescription({storePlatformDictionary:t,subtitle:o}),thumbnailHorizontalAlignment:getFlowcaseThumbnailHorizontalAlignment({storePlatformDictionary:t})});if(u.indexOf(r)!==-1){const e=get(t,"artwork");if(e){l.thumbnailArtwork=createArtwork({dictionary:e})}}const s=t?.editorialVideo;if(containsMotionDetailVideo(s)){l.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(s),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(s)})}if(r==="song"&&a){const onSelect=()=>{const e=createPushSegueForURL(a);return e};g=createFlowcaseItem(Object.assign(l,{onSelect:onSelect}))}else{g=createFlowcaseItem(l)}}return g}function processFlowcaseItemCustom(e,t){const r=t?.storePlatformData;const i=r[e?.link?.contentId];const n=e?.adamId;if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(i,this)){return null}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){return}const o=e?.link?.type;const s=e?.designTag;const a=e?.link?.label;const{artwork:l,designBadge:c}=e;const u=createArtwork({dictionary:l});const d={headline:c,title:s,subtitle:"",backgroundArtwork:u,controllerTitle:a};if(n){const e=new IdentifierSet;e.contentKind=IdentifierSet.CONTENT_KIND.CURATOR;e.storeAdamID=n;d.identifierSet=e}if(o==="content"&&i){const e=i.kind;d.storePlatformDictionary=i;if(e==="musicVideo"){d.subtitle=""}d.url=i.url||i.postUrl}else if(o==="link"){d.url=e?.link?.url;d.target=e?.link?.target}if(!d.url){return null}return createFlowcaseItem(d)}function dataContainsLiveFlowcase(e){const t=get(e,"children",[]);return t.some(e=>e.fcKind==="383")}function processFlowcase(e,t){if(get(this,"showMultiply")&&dataContainsLiveFlowcase(e)){return null}const r=processChildFeaturedNodes.call(this,e,t);const i=get(e,"adamId");let n=null;if(r.length>0){n=createFlowcase({editorialID:i,items:r});const o=get(e,"children",[]);const s=o.some(e=>e.fcKind==="383");if(s){addLiveRadioTimer.call(this,n,r=>{resetItems$1.call(this,e,t,r)},()=>{const e=get(t,"pageData.liveURLData");return getRemainingTime(getCurrentShow(e))})}}return n}function processFlowcaseItem(e,t){const r=get(t,"storePlatformData");const i=r[get(e,"link.contentId")];if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(i,this)){return null}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){return}const n=getCurrentShow(getLiveURLData(e,t));let o=null;if(!n){if(i){o=processFlowcaseItemStorePlatform(e,i)}}else{o=processFlowcaseItemLive(n,i)}return o}function createLiveRadioCase(e){const t={playActivityFeatureName:"flowcase"};return Object.assign(new LiveRadioCase,e,t)}function createLiveRadioCaseItem(e){const t=createDefaultOptions(e);return Object.assign(new LiveRadioCaseItem,t,e)}const BaseClass$1=mix(ComponentController).with(MetricsMixin);class LiveRadioCaseScheduleController extends BaseClass$1{constructor({contentIds:e,title:t,currentStation:r,storeContent:i}={}){super(...arguments);this.contentIds=e;if(t){this.headerItem.title=t;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE}this.storeContent=i;this.currentStation=r}didLoad(){super.didLoad();this.loadPage()}didAppear(){this.pageContext=currentPageContext();super.didAppear()}createPageMetrics(){this.pageFields={pageId:this.currentStation.stationId,pageType:"Schedule"};this.pageFields.page=combineWithSeparator(this.pageFields.pageType,this.pageFields.pageId)}createViewModel(){const e=this.processRadioScheduleGrid(this.storeContent,this.currentStation);const t=[e];return createVerticalStack({childViewModels:t})}loadPage(){fetchContent({ids:this.contentIds}).then(e=>this.createViewModel(this.contentIds,e)).then(e=>{this.createPageMetrics();this.viewModel=e}).then(()=>{this.considerRecordingPageEvent()}).catch(e=>{logger$5.error(e)})}processRadioScheduleGrid(e={},t={}){const r=get(t,"upcomingShows",[]);const i=getCurrentShow(t);const n=get(i,"showIndex",0);const o=localize("FUSE.Radio.UpcomingShows");const s=r.slice(n,r.length);const a=GridSection.UNIFORM_CELL_TYPE.FEATURED_RADIO_SHOW;const l=[];const c=constructLiveRadioCaseDateFormatter(`${localize("FUSE.Radio.Live")} · %@`);const u=constructLiveRadioCaseDateFormatter();s.forEach((r,i)=>{let n;let o=e[r.curatorId];let s;let a;o=cloneDeep(o)||{};if(i===0){s=get(GridItem,"HEADLINE_COLOR.TINT_COLOR");a=c}else{a=u}const d=get(r,"description");const g=r.artwork||r.heroArtwork;const h=createArtwork({dictionary:g,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP});const f=get(r,"title");if(Object.keys(o).length>0){o.editorialArtwork=null;n=createGridItem({storePlatformDictionary:o,headlineColor:s,subtitle:d,backgroundArtwork:h,title:f})}else{o.kind="radioStation";o.id=t.stationId;n=createGridItem({headlineColor:s,subtitle:d,backgroundArtwork:h,storePlatformDictionary:o,title:f,onSelect:()=>createNoopSegue()})}const p=constructDateRangeDescriptor(get(r,"startTime"),get(r,"endTime"));const m=constructValueTransformerOptions(a,"headline",p);n.applyValueTransformer(m);if(n){l.push(n)}});if(l.length===0){return null}const d=createGridSection({items:l,uniformCellType:a,title:o});return createGrid({adaptiveLayoutStyle:Grid.ADAPTIVE_LAYOUT_STYLE.DEFAULT,sections:[d]})}}function getCurrentShowWithClosestEndTime(e=[]){let t={};let r;if(e){e.forEach(({stationId:e,upcomingShows:i})=>{if(e&&i){t=getCurrentRadioShowFromLiveData({upcomingShows:i});if(!r){r=t}else{const e=new Date(get(t,"endTime"));const i=new Date(get(r,"endTime"));if(e.getTime(){recordClickEventForAccessoryButton(e);const t=new LiveRadioCaseScheduleController(c);return createPushSegue({componentController:t})};const u=r.itunesNotes?.tagline;return Object.assign({storePlatformDictionary:r,headerTitle:o,headerSubtitle:u,accessoryButtonTitle:l,videoBackgroundArtwork:a,onAccessoryButtonSelect:onAccessoryButtonSelect,backgroundArtwork:s,title:e.title,subtitle:e.description},n)}function processLiveRadioCaseItem(e,t){const r=get(t,"storePlatformData");const i=get(e,"link.contentId");const n=r[i];if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(n,this)){return null}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){return}if(!n){logger$5.warn(`No storePlatformDictionary for contentId ${i}`);return null}const o=get(t,"pageData.liveURLDataArray",[]);const s=o.find(e=>e.stationId===i);const a=getCurrentShow(s);let l=null;if(a){const onSelect=()=>{const e=get(a,"curatorId");const t=e?createPushSegueForID(e.toString()):createNoopSegue();const r=createRadioPlaybackIntent({radioStationStorePlatformDictionary:n});t.playbackIntent=r;return t};const e=getLiveRadioCaseItemData(a,s,n,r,{onSelect:onSelect});const t=createLiveRadioCaseItem(e);const i=constructDateRangeDescriptor(get(a,"startTime"),get(a,"endTime"));const o=constructLiveRadioCaseDateFormatter(`${localize("FUSE.Radio.Live")} · %@`);const c=constructValueTransformerOptions(o,"headline",i);t.applyValueTransformer(c);l=[t]}return l}function processLiveRadioCase(e,t){if(!this.showMultiply){return null}const r=processChildFeaturedNodes.call(this,e,t);let i=null;if(r.length>0){i=createLiveRadioCase({items:r});const n=get(e,"children",[]);const o=n.some(e=>e.fcKind==="489");if(o){addLiveRadioTimer.call(this,i,r=>{resetItems.call(this,e,t,r)},()=>{const e=get(t,"pageData.liveURLDataArray");return getRemainingTime(getCurrentShowWithClosestEndTime(e))})}}return i}function createBrick(e){return Object.assign(new Brick,e)}function createBrickItem(e){const t=createDefaultOptions(e);return Object.assign(new BrickItem,t,e)}function processBrick(e,t){const r=processChildFeaturedNodes.call(this,e,t);let i;if(r.length>0){const t=get(e,"name");const n=get(e,"adamId");i=createBrick({items:r,title:t,editorialID:n})}return i}function processBrickItem(e,t){const r=get(t,"storePlatformData");const i=get(e,"link.contentId");const n=r[i];if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(n,this)){return null}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){return null}const o=get(n,"kind");if(!o){return null}const s={};const{designBadge:a}=e;const l=["artist","album","song","musicVideo","uploadedVideo","uploadedAudio"].indexOf(o)!==-1;const c=["playlist","radioStation","iTunesBrand","brand","activity","uploadedAudio","uploadedVideo"].indexOf(o)!==-1;const u=get(n,"editorialArtwork.subscriptionCover");const d=get(n,"editorialArtwork.subscriptionHero");const g=Artwork.CROP_STYLE.SPECIFIC_RECTANGLE;const h=c?d||u:d;let f;s.headline=a;s.title=l?n?.artistName:n?.shortName??n?.name;fixBrickPlaylistCrop(n);if(h){f=createArtwork({dictionary:h,cropStyle:g})}if(!f){return null}Object.assign(s,{storePlatformDictionary:n,backgroundArtwork:f});return createBrickItem(s)}function processBrickItemCustom(e,t){const r=get(t,"storePlatformData");const i=r[get(e,"link.contentId")];if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(i,this)){return null}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){return null}const n=get(e,"link.type");const{artwork:o,designBadge:s,designTag:a}=e;const l=createArtwork({dictionary:o,cropStyle:"sr"});const c={headline:s,title:sanitizeString(a),backgroundArtwork:l};let u;if(n==="content"&&i){u=get(i,"url");c.storePlatformDictionary=i}else if(n==="link"){u=get(e,"link.url");c.target=get(e,"link.target")}else{logger$5.error(`Unsupported linkType ${n}`)}if(!u){return null}c.url=u;return createBrickItem(c)}function processTVGrid(e,t,r){const i=get(t,"storePlatformData");const n=e[r]||[];const o=[];n.forEach(e=>{const t=i[e.contentId];let r;if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(t,this)){return}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(t)){return}if(t){const e=get(t,"editorialArtwork.browseCover");r=createGridItem({storePlatformDictionary:t,title:toUpperCase(t.name),onSelect:()=>createPushSegueForStoreContent(t),backgroundArtwork:createArtwork({dictionary:e,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE})})}if(r){o.push(r)}});if(o.length===0){return null}const s=createGridSection({title:e.name,items:o,uniformCellType:get(GridSection,"UNIFORM_CELL_TYPE.TV_SHOW")});return createGrid({sections:[s]})}function processContentGrid(e,t,r){const i=get(t,"storePlatformData");const n=e[r]||[];const o=[];const s=constructLiveRadioCaseDateFormatter();n.forEach(e=>{const t=i[e.contentId];let r;if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(t,this)){return}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(t)){return}if(isContentNode(e)&&t){const e=get(t,"itunesNotes.tagline","");const i=getFormattedDayString(get(t,"startTime"));const n=get(t,"startTime");const o=get(t,"endTime");if(Object.keys(t).length>0){r=createGridItem({storePlatformDictionary:t,subtitle:e,overlayTitle:i});const a=constructDateRangeDescriptor(n,o);const l=constructValueTransformerOptions(s,"overlaySubtitle",a);r.applyValueTransformer(l)}}if(r){o.push(r)}});if(o.length===0){return null}const a=createGridSection({title:e.name||e.Name,items:o});return createGrid({sections:[a]})}function addSeeAllToViewModel(e,t,r){if(t){const i=createContainerDetailLink({onSelect:createPushSegueHandler({title:r,url:t})});Object.assign(i,MetricsClickHandlers.containerDetailLink);Object.assign(e,{containerDetailLink:i})}}function processChart(e,t){const r=get(t,"storePlatformData");const i=e.links||[];const n=[];i.forEach(e=>{const t=r[e.contentId];if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(t,this)){return}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(t)){return}let i;if(isContentNode(e)&&t){i=createShelfItem({storePlatformDictionary:t})}if(i){n.push(i)}});if(n.length===0){return null}const o=createShelf({title:e.name,sections:[createShelfSection({items:n,isRankedList:true})]});addSeeAllToViewModel(o,e.seeAllUrl,e.name);return o}function processChartSet(e,t){const r=get(t,"pageData.componentName");const i=r==="itunes_brand_page";let n;if(i){const r=e.children||[];if(r.length>0){n=processFeaturedNode.call(this,r[0],t)}}return n}function createMenu(e){return Object.assign(new Menu,e)}function createMenuSection(e){return Object.assign(new MenuSection,e)}function createMenuItem(e){const t=createDefaultOptions(e);return Object.assign(new MenuItem,t,e)}function processMenu(e,t){let r;const i=e.links||[];const n=e.appendURL;const o=e.showsLargeTitleHeader;const s=i.reduce((e,r)=>{let i;if(r.type==="link"){if(r.url){let e=r.url;if(n){const t=e.indexOf("?")===-1?"?":"&";e+=`${t}${n}`}const{label:t,controllerTitle:s,target:a,path:l}=r;i=createMenuItem({title:t,url:e,showsLargeTitleHeader:o,controllerTitle:s,target:a,path:l})}}else if(r.type==="genres"){const{label:e,label:n,menu:o}=r;if(o){let r;const s=o.reduce((e,r)=>{const i=processMenu.call(this,r,t);if(i){e.push(...i.sections)}return e},[]);if(s.length){r=createMenu({sections:s})}i=createMenuItem({title:e,submenu:r,submenuTitle:n})}}else if(r.type==="content"){const e=get(t,"storePlatformData");const s=e[r.contentId];if(s){const{name:e,shortName:t,target:r}=s;let a=s.url;if(n){const e=a.indexOf("?")===-1?"?":"&";a+=`${e}${n}`}i=createMenuItem({title:t||e,url:a,showsLargeTitleHeader:o,target:r})}}if(i){addClickMetricsHandlerToItem(i,()=>({actionDetails:{menuItemName:i.path||i.title}}));e.push(i)}return e},[]);const a=get(e,"adamId");if(s.length>0){r=createMenu({sections:[createMenuSection({title:e.name,items:s})],editorialID:a})}return r}function getRadioStationHeadlineString(e={},t={}){const r=get(e,"pageData.componentName");const i=getEpisodeNumberHeadline(t);const n=get(t,"itunesNotes.standard");let o=null;if(r==="itunes_brand_page"){o=i||localizedMonthDayYearStringFromReleaseDate(get(t,"airTime.start"))}else if(t.streamingRadioSubType==="Episode"){o=sanitizeString(n)}if(o){o=toUpperCase(o)}return o}function processShelf(e,t,r){const i=get(t,"storePlatformData");const n=e[r]||[];const o=[];let s;let a=false;n.forEach(r=>{const n=i[r.contentId];let l;if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(n,this)){return}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){return}if(isContentNode(r)&&n){if(!s){s=get(n,"kind")}const r={storePlatformDictionary:n};const i=get(n,"itunesNotes.short")||get(n,"itunesNotes.standard");const o=get(n,"kind");if(!a&&!isMusicVideoKind(o)){a=o!==s}if(isBrandShowContent(n)){r.subtitle=n.itunesNotes?.tagline}else if(isMusicVideoKind(o)){Object.assign(r,getVerticalVideoArtworkProperties(n));r.subtitle=n.artistName}else{r.subtitle=getBroadcastRadioShowSubtitle(n)}if(i&&e.fcKind==="328"){r.headline=e.name;r.description=sanitizeString(i)}if(o==="radioStation"){r.headline=getRadioStationHeadlineString(t,n)}l=createShelfItem(r)}if(l){o.push(l)}});let l=null;if(o.length>0){const t={items:o};const r=4;if(e.fcKind==="328"){t.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.FEATURED_SHOWCASE}else if(a){const e=getMixedContentTypes({ids:n,lockupData:i});if(e.get("radioStation")&&e.get("album")&&e.size===2){t.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.RADIO_STATION}else{t.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.ALBUM}}else if(s==="playlist"&&e.fcKind!=="387"||s==="activity"||s==="radioStation"&&e.displayStyle==="compact"){t.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.ALBUM}else if(isMusicVideoKind(s)&&e.fcKind==="387"){t.uniformCellType=ShelfSection.UNIFORM_CELL_TYPE.FEATURED_MUSIC_VIDEO}if((e.fcKind==="389"||e.displayStyle==="expanded")&&o.length>=r){t.height=ShelfSection.HEIGHT.REGULAR}const c=get(e,"adamId");l=createShelf({title:e.name,sections:[createShelfSection(t)],editorialID:c});if(o.length>MAX_SHELF_ITEMS&&e.fcKind!=="388"){addSeeAllToViewModel(l,e.seeAllUrl,e.name)}}return l}function createRecentlyPlayedRadioShelfItems(e,t){const r=[];t.forEach(t=>{const i=e[t.contentId];let n;if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(i,this)){return}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){return}if(isContentNode(t)&&i){const e={storePlatformDictionary:i};if(isBrandShowContent(i)){e.subtitle=get(i,"itunesNotes.tagline")}else{const t=true;e.title=getWordMarkString(get(i,"name"));i.name=getWordMarkString(get(i,"name"));e.subtitle=getBroadcastRadioShowSubtitle(i,t);if(i?.radioStationTypeId===13){Object.assign(e,{radioStationType:RadioStationKinds.DISCOVERY,subtitle:""})}}n=createShelfItem(e)}if(n){r.push(n)}});return r}function processRecentlyPlayedRadioShelf(e,t,r){const i=get(t,"storePlatformData");const n=e[r]||[];const o=createRecentlyPlayedRadioShelfItems.call(this,i,n);let s=null;if(o.length>0){const t={items:o,uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM};s=createShelf({title:e.name,sections:[createShelfSection(t)]})}return s}function processRadioScheduleShelf(e,t){if(this.showMultiply){return null}const r=get(t,"storePlatformData");const i=get(t,"pageData.liveURLData");const n=get(i,"upcomingShows",[]);const o=getCurrentShow(i);const s=get(o,"showIndex",0)+1;const a=localize("FUSE.Radio.UpcomingShows");const l=n.slice(s,n.length);const c=ShelfSection.UNIFORM_CELL_TYPE.FEATURED_RADIO_SHOW;const u=[];const d=constructLiveRadioCaseDateFormatter();l.forEach(e=>{let t;let i=r[e.curatorId];if(!MediaPicker.shouldShowItemWithStorePlaformDictionary(i,this)){return}if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(i)){return}i=cloneDeep(i)||{};const n=get(e,"startTime");const o=get(e,"endTime");const s=get(e,"description");const a=createArtwork({dictionary:{url:get(e,"artworkUrl"),height:1080,width:1080},cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP});const l=get(e,"title");if(Object.keys(i).length>0){i.editorialArtwork=null;t=createShelfItem({storePlatformDictionary:i,title:l,subtitle:s,backgroundArtwork:a})}else{i.kind="radioStation";i.id="ra.978194965";t=createShelfItem({title:l,subtitle:s,backgroundArtwork:a,storePlatformDictionary:i,onSelect:()=>createNoopSegue()})}const c=constructDateRangeDescriptor(n,o);const g=constructValueTransformerOptions(d,"headline",c);t.applyValueTransformer(g);if(t){u.push(t)}});if(u.length===0){return null}const g=createShelfSection({items:u,uniformCellType:c});return createShelf({title:a,sections:[g]})}function processChildFeaturedNodes(e,t){const r=e.children||[];const i=r.reduce((e,r)=>{let i;if(isFeaturedNode(r)){i=processFeaturedNode.call(this,r,t)}if(i){if(i instanceof Array){e.push(...i)}else{e.push(i)}}return e},[]);return i}function processVerticalStack(e,t){const r=processChildFeaturedNodes.call(this,e,t);let i;if(r.length>0){i=createVerticalStack({childViewModels:r})}return i}function processParagraph(e){let t;const r=sanitizeStringAndEnableTags(e.Description);const i=e.name;const n=e.separatorOverride;if(r){t=createParagraph({text:r,title:i,shouldHideDivider:n})}return t}function processTabRoot(e,t){let r;if(e.children instanceof Array){r=e.children.reduce((e,r)=>{const i=processFeaturedNode.call(this,r,t);if(i instanceof Array){e.push(...i)}else if(i){e.push(i)}return e},[])}return r}function processFeaturedNode(e,t){let r;switch(e.fcKind){case"315":r=processVerticalStack.call(this,e,t);break;case"316":r=processFlowcase.call(this,e,t);break;case"317":r=processFlowcaseItem.call(this,e,t);break;case"319":r=processFlowcaseItem.call(this,e,t);break;case"320":r=processFlowcaseItemCustom.call(this,e,t);break;case"321":r=processFlowcaseItem.call(this,e,t);break;case"322":break;case"323":r=processChartSet.call(this,e,t);break;case"326":r=processShelf.call(this,e,t,"content");break;case"327":r=processShelf.call(this,e,t,"content");break;case"328":r=processShelf.call(this,e,t,"content");break;case"329":r=processShelf.call(this,e,t,"content");break;case"347":r=processShelf.call(this,e,t,"content");break;case"368":r=processShelf.call(this,e,t,"content");break;case"332":r=processRecentlyPlayedRadioShelf.call(this,e,t,"children");break;case"336":r=processChart.call(this,e,t);break;case"337":r=processChart.call(this,e,t);break;case"338":r=processChart.call(this,e,t);break;case"339":r=processChart.call(this,e,t);break;case"340":r=processChart.call(this,e,t);break;case"341":r=processChart.call(this,e,t);break;case"353":r=processChart.call(this,e,t);break;case"354":r=processChart.call(this,e,t);break;case"355":r=processChart.call(this,e,t);break;case"356":r=processChart.call(this,e,t);break;case"367":r=processChart.call(this,e,t);break;case"382":r=processTabRoot.call(this,e,t);break;case"383":r=processFlowcaseItem.call(this,e,t);break;case"385":r=processBrick.call(this,e,t);break;case"386":r=processBrickItem.call(this,e,t);break;case"394":r=processBrickItemCustom.call(this,e,t);break;case"387":r=processShelf.call(this,e,t,"content");break;case"388":r=processShelf.call(this,e,t,"content");break;case"389":r=processShelf.call(this,e,t,"children");break;case"391":r=processMenu.call(this,e,t);break;case"401":r=processRadioScheduleShelf.call(this,e,t);break;case"402":r=processContentGrid.call(this,e,t,"content");break;case"407":r=processParagraph.call(this,e);break;case"410":r=processTVGrid.call(this,e,t,"content");break;case"488":r=processLiveRadioCase.call(this,e,t);break;case"489":r=processLiveRadioCaseItem.call(this,e,t);break}if(r){const t={impressions:extractMappedFields(e,"impressions"),location:extractMappedFields(e,"location")};if(Array.isArray(r)){r.forEach(e=>{if(!e.metrics){e.metrics=t}})}else{r.metrics=t}}return r}const MusicAPIResourceType={ACTIVITIES:"activities",ALBUMS:"albums",APPLE_CURATORS:"apple-curators",ARTISTS:"artists",CURATORS:"curators",EDITORIAL_ITEMS:"editorial-items",EDITORIAL_ELEMENTS:"editorial-elements",GROUPINGS:"groupings",LIBRARY_ALBUMS:"library-albums",LIBRARY_PLAYLISTS:"library-playlists",MARKETING_ITEMS:"marketing-items",MUSIC_MOVIES:"music-movies",MUSIC_VIDEOS:"music-videos",PLAYLISTS:"playlists",SOCIAL_PROFILES:"social-profiles",SOCIAL_UPSELLS:"social-upsells",SONGS:"songs",STATIONS:"stations",TV_EPISODES:"tv-episodes",TV_SHOWS:"tv-shows",UPLOADED_AUDIOS:"uploaded-audios",UPLOADED_VIDEOS:"uploaded-videos",RECORD_LABELS:"record-labels"};function registerOnCanShowRadioChange(e){registerGlobalCallback(CapabilitiesController,"onCanShowRadioChange",e)}function unregisterOnCanShowRadioChange(e){removeGlobalCallback(CapabilitiesController,"onCanShowRadioChange",e)}CapabilitiesController.restrictsRadioContent=()=>!CapabilitiesController.canShowRadio;CapabilitiesController.shouldShowItemWithStorePlatformDictionary=e=>{if(!CapabilitiesController.restrictsRadioContent()){return true}if(e?.kind==="radioStation"){return false}if(e?.iTunesBrandType==="Show"){return false}return true};CapabilitiesController.shouldShowItemWithMediaAPIResource=(e,t)=>{if(!CapabilitiesController.restrictsRadioContent()){return true}if(t.type===MusicAPIResourceType.STATIONS){return false}const r=e?.attributes;if(r?.kind===MusicAPIResourceType.STATIONS){return false}if(r?.resourceTypes?.length===1&&r?.resourceTypes?.[0]===MusicAPIResourceType.STATIONS){return false}return true};const BaseClass$2=mix(StorePageController).with(RefreshMixin,SocialProfileBadgingMixin);const REFRESH_TTL=3e5;const SHOW_MULTIPLY=false;class GroupingController extends BaseClass$2{constructor({controllerTitle:e}={}){super(...arguments);this.controllerTitle=e;this.refreshTTL=REFRESH_TTL;this.showMultiply=SHOW_MULTIPLY}fetchAdditionalData(e){return fetchMarkers(e).then(fetchAvailableStoreContent)}createViewModel(e){let t;const r=get(e,"pageData.fcStructure.model");if(r){if(!r.fcKind){r.fcKind="315"}this.showMultiply=shouldDisplayMultiply(e);this.responseData=e;t=processFeaturedNode.call(this,r,e)}if(!t){t=createVerticalStack()}this.updateHeaderTitle(r);return t}updateHeaderTitle(e={}){const t=get(e,"children[0]",{});if(!this.headerItem.title&&t.fcKind==="382"&&t.name){this.headerItem.title=t.name}if(!this.headerItem.title&&this.controllerTitle){this.headerItem.title=this.controllerTitle}}didLoad(){super.didLoad();this.reloadPage();registerOnCanShowRadioChange(this.refreshWithDebounce);subscribe(SUBSCRIBER_COOKIE_UPDATED,this.refreshWithDebounce)}willAppear(e){super.willAppear(e);this.considerLoadingPage();if(this.viewModel&&!this.isLoading){this.badgeViewModel()}}loadPage(){return super.loadPage().then(()=>this.badgeViewModel(true))}refreshPageContent(){return this.loadPage()}willUnload(...e){clearLiveRadioTimers(this);super.willUnload(...e);unsubscribe(SUBSCRIBER_COOKIE_UPDATED,this.refreshWithDebounce);unregisterOnCanShowRadioChange(this.refreshWithDebounce)}}var HeaderItemMixin=e=>{const t=class extends e{constructor({storePlatformDictionary:e={}}={}){super(...arguments);this.updateHeaderItem(e)}updateHeaderItem(e={}){const t=get(e,"editorialArtwork.bannerUber");const r=get(e,"editorialArtwork.subscriptionCover");const i=e.iTunesBrandType==="Show"||e.iTunesBrandType==="Curator";let n=r||t;if(i){n=t||r}if(n){this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:n})}this.headerItem.titleHeaderStyle=n?HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED:HeaderItem.TITLE_HEADER_STYLE.STANDARD;this.headerItem.storePlatformDictionary=e;this.headerItem.title=e.name}};return t};const BaseClass$3=mix(GroupingController).with(HeaderItemMixin);class CuratorController extends BaseClass$3{constructor({storePlatformDictionary:e={}}={}){super(...arguments);if(!this.url){this.url=e.url}if(!this.id){this.id=e.id}if(this.url){const e=url.parse(this.url,true);this.context=get(e,"query.context")}}updateHeaderItem(e={}){if(e.iTunesBrandType!=="Genre"){super.updateHeaderItem(e)}else{const t=e.shortName||e.name;this.headerItem.storePlatformDictionary=e;this.headerItem.title=t;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}}fetchPageData(...e){return super.fetchPageData(...e).then(e=>{let t=get(e,"pageData.fcStructure.model");if(!t){t={fcKind:"315",children:[]};set(e,"pageData.fcStructure.model",t)}if(!t.children){t.children=[]}const r=get(e,"pageData.id")||get(e,"pageData.iTunesBrandAdamId");const i=get(e,`storePlatformData.${r}.iTunesBrandType`);const n=i!=="Genre"&&t.children.length===0;if(n||this.context==="playlists"){t.children.push({fcKind:"389",name:localize("FUSE.Profile.Playlists")})}return e})}createViewModel(e){const t=get(e,"pageData.id")||get(e,"pageData.iTunesBrandAdamId");const r=get(e,`storePlatformData.${t}`);let i;let n;if(r){this.storePlatformDictionary=r;this.updateHeaderItem(r);i=get(r,"itunesNotes.standard")}const o=super.createViewModel(e);if(!this.context&&i&&o instanceof VerticalStack){const e=o.childViewModels||[];if(r.iTunesBrandType!=="Genre"){e.unshift(createParagraph({text:i,shouldHideDivider:true}))}else{n=localize("FUSE.Bio.About");e.push(createParagraph({title:n,text:i,shouldHideDivider:true}))}o.childViewModels=e}return o}}const BaseClass$4=mix(GroupingController).with(HeaderItemMixin);class CuratorController$1 extends BaseClass$4{constructor({storePlatformDictionary:e={}}={}){super(...arguments);if(!this.url){this.url=e.url}if(!this.id){this.id=e.id}}updateHeaderItem(e={}){const t=get(e,"editorialArtwork.bannerUber")||get(e,"editorialArtwork.subscriptionCover");if(t){this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:t})}this.headerItem.storePlatformDictionary=e;this.headerItem.title=e.name;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}createViewModel(e){const t=get(e,"pageData.id");const r=get(e,`storePlatformData.${t}`);if(r){this.storePlatformDictionary=r;this.updateHeaderItem(r)}return super.createViewModel(e)}}const BaseClass$5=mix(StorePageController).with(HeaderItemMixin);function findContentIds$1(e,t){return get(e,["storePlatformData","product","results",t,"playlistIds"],[])}function createViewModel(e,t={}){let r;const i=[];const n=findContentIds$1(e,t.id);const o=get(e,"storePlatformData.lockup.results",{});const s=get(t,"itunesNotes.standard");const a=createShelfFromLockups(n,o,{options:{title:localize("FUSE.Profile.Playlists")},sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM,height:ShelfSection.HEIGHT.REGULAR}});if(a){i.push(a)}if(s){i.unshift(createParagraph({title:localize("FUSE.Bio.About"),text:s,shouldHideDivider:true}))}if(i.length>0){r=createVerticalStack({childViewModels:i})}return r}class BrandController extends BaseClass$5{constructor({storePlatformDictionary:e={}}={}){super(...arguments);if(!this.url){this.url=e.url}if(!this.id){this.id=e.id}}didLoad(){super.didLoad();this.loadPage()}updateHeaderItem(e){super.updateHeaderItem(e);const t=get(e,"editorialArtwork.brandLogo");this.headerItem.promotionalThumbnailArtwork=createArtwork({dictionary:t,treatment:Artwork.TREATMENT.CIRCLE})}getMissingContentIds(e){const t=get(e,"pageData.id");return findContentIds$1(e,t)}createViewModel(e){const t=get(e,"pageData.id");const r=["storePlatformData","product","results",t];const i=get(e,r);if(i){this.storePlatformDictionary=i;this.updateHeaderItem(i)}return createViewModel(e,i)}}function createSettingsViewModel(e){return Object.assign(new SettingsViewModel,e)}function createSettingsSection(e){return Object.assign(new SettingsSection,e)}function createSettingsItem(e){const t=createDefaultOptions(e);return Object.assign(new SettingsItem,t,e)}function createSettingsAuthenticationSection(e){return Object.assign(new SettingsAuthenticationSection,e)}function createSettingsLink(e){return Object.assign(new SettingsLink,e)}function createSettingsItemToggle(e){return Object.assign(new SettingsItemToggle,e)}function createSettingsItemText(e){return Object.assign(new SettingsItemText,e)}function userNotificationSettings(){return new Promise((e,t)=>{const r=new UserNotificationSettings;r.onResponse=r=>{if(r){e(r)}else{t(new Error("Unable to retrieve UserNotificationSettings."))}};r.request()})}function userNotificationAuthorizationSegue(e){return Object.assign(new UserNotificationAuthorizationSegue,e)}const SHOW_IN_LIBRARY_SYNC_INTERVAL=1e3*60*60*24;function getPushNotificationSettings(){return getBagValue("musicSubscription.getPushNotificationSettings").then(e=>{const t={v:2,serviceId:"com.apple.Music"};return fetchJSON(constructURL(e,{params:t}))})}function setPushNotificationSettings(e){const t={settings:Object.keys(e).map(t=>({settingId:t,data:e[t]}))};const r={method:HTTP.METHOD.POST,body:t};return getBagValue("musicSubscription.setPushNotificationSettings").then(e=>{const t={v:2,serviceId:"com.apple.Music"};return fetch(constructURL(e,{params:t}),r)})}function syncCachedAccountShowInLibraryEnabled(){return getPushNotificationSettings().then((e={})=>{const t=get(e,"sections",[]);let r;t.forEach(e=>{e.settings.forEach(e=>{if(e.settingId==="notifications.music.account.showInLibrary"){r=e.value}})});if(typeof r!=="undefined"){const e=r.dataUpdated?Number.MAX_SAFE_INTEGER:Date.now();Storage.setItem(StorageKeys.User.DATE_CACHED_SHOW_IN_LIBARY_SETTING_LAST_SYNCED,e);if(r.dataUpdated){CapabilitiesController.cachedAccountShowInLibraryEnabled=r.data;logger$5.log("syncCachedAccountShowInLibraryEnabled: set cachedAccountShowInLibraryEnabled to ",JSON.stringify(r))}}})}function checkCachedAccountShowInLibraryEnabledSync(){return getSubscriptionStatus().then((e={})=>{if(!isUserSignedIn()||!e.isSubscribed){return Promise.resolve()}const t=Storage.getItem(StorageKeys.User.DATE_CACHED_SHOW_IN_LIBARY_SETTING_LAST_SYNCED);const r=!t||t+SHOW_IN_LIBRARY_SYNC_INTERVAL{const r=get(t,"sections",[]);const i=r.reduce((t,r)=>Object.assign(t,...r.settings.map(t=>({[t.settingId]:e}))),{});if(Object.entries(i).length===0){logger$5.error(`NotificationPreferencesController: Failed setting push notifications with response: '${t}'`);return}CapabilitiesController.cachedAccountShowInLibraryEnabled=e;return setPushNotificationSettings(i)}).catch(e=>logger$5.error("Failed to set all push notification settings in NotificationPreferencesController",e))}const BaseClass$6=mix(ComponentController).with(MetricsMixin);class NotificationPreferencesController extends BaseClass$6{get metricsId(){return"Notifications-Preferences"}constructor(...e){super(...e);this.responseData=[];this.toggleData={};this.changedSettings={};this.enablingNewArtistContentFromDeepLink=false;this.onNotificationsEnabledChange=()=>{this.reloadData()}}didLoad(){super.didLoad();registerGlobalCallback(CapabilitiesController,"onNotificationsEnabledChange",this.onNotificationsEnabledChange);this.loadPage();this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD;this.title=localize("FUSE.Settings.Notifications")}willUnload(){super.willUnload();removeGlobalCallback(CapabilitiesController,"onNotificationsEnabledChange",this.onNotificationsEnabledChange)}willDisappear(...e){super.willDisappear(...e);this.saveData()}saveData(){if(Object.entries(this.changedSettings).length===0){return}setPushNotificationSettings(this.changedSettings).then((e={})=>{if(e.status===200||e.output.status==="success"){this.changedSettings={}}else{logger$5.error(`Failed to send push notification settings with response: '${e}'`)}}).catch(e=>logger$5.error("Failed to send push notification settings in NotificationPreferencesController",e))}loadPage(){return Promise.all([getPushNotificationSettings(),isSocialOnboarded(),shouldSocial(),getSubscriptionStatus(),userNotificationSettings()]).then((e=[])=>{this.responseData=e;this.considerRecordingPageEvent();this.reloadData();this.enablingNewArtistContentFromDeepLink=false}).catch(e=>logger$5.error("Failed to fetch notification settings in NotificationPreferencesController",e))}createPageMetrics(){this.pageContext="NotificationPreferences";this.pageFields={pageType:"Settings",pageId:"Notifications",page:combineWithSeparator("Settings","Notifications")}}buildSections(){if(this.responseData.length===0){return[]}const[e={},t=false,r=false,i,n]=this.responseData;const o=get(i,"isSubscribed",false);this.toggleData=e;const s=get(e,"sections",[]);const a=o?"FUSE.Settings.Notifications.Disclaimer":"FUSE.LibraryBanner.OptInSheet.Footer";const l=localize(a);const c=[];const u=[];const d=n?.authorizationStatus;const g=d===UserNotificationSettings.AUTHORIZATION_STATUS.NOT_DETERMINED;let h;let f;let p;if(g||d===UserNotificationSettings.AUTHORIZATION_STATUS.DENIED){const e=this.deviceLocalizationSuffix();const t=createSettingsItem({title:localize(`FUSE.Settings.Notifications.HintTitle.${e}`),onSelect:()=>{if(g){logger$5.log(`userNotificationAuthorizationStatus: ${d}`);return userNotificationAuthorizationSegue({userInitiated:true})}return createRedirectSegue({url:"prefs:root=NOTIFICATIONS_ID&path=com.apple.Music"})}});const r=createSettingsSection({footerText:localize(`FUSE.Settings.Notifications.HintDescription.${e}`),items:[t]});c.push(r)}s.forEach((e,i)=>{e.settings.forEach((e,n)=>{if(e.settingId==="notifications.music.account.friends"&&(!t||!r||!o)){return}if(this.enablingNewArtistContentFromDeepLink){this.setToggleData(true,i,n)}const s=createSettingsItem({accessoryItem:createSettingsItemToggle({isToggled:e.value.data,onToggledDidChange:e=>{if(this.setToggleDataIncludingShowInLibraryToggleData(e,i,n,p)){this.reloadData()}}}),title:e.title,detailText:e.description!==""?e.description:null,usesApplicationTintColor:false,name:e.settingId});if(e.settingId==="notifications.music.account.artistsAndShows"){f=s}else if(e.settingId==="notifications.music.account.showInLibrary"){h=s;p={sectionIndex:i,rowIndex:n}}else{u.push(s)}})});if(f){const e=[f];if(h&&f.accessoryItem.isToggled){e.push(h)}c.push(createSettingsSection({items:e}))}u.forEach(e=>{c.push(createSettingsSection({items:[e]}))});c[c.length-1].footerText=l;return c}reloadData(){this.updateViewModel(this.buildSections())}updateViewModel(e){if(!e||e.length===0){this.viewModel=createMessageViewModel({message:localize("FUSE.Error.AnErrorOccurred"),onAccessoryButtonSelect:this.loadPage})}else if(this.viewModel){this.viewModel.sectionsForAuthenticatedState=e}else{this.viewModel=createSettingsViewModel({sectionsForAuthenticatedState:e})}}setToggleDataIncludingShowInLibraryToggleData(e,t,r,i){const n=this.toggleData.sections[t].settings[r];let o=this.setToggleData(e,t,r);if(n.settingId==="notifications.music.account.artistsAndShows"&&i){this.setToggleData(e,i.sectionIndex,i.rowIndex)}else{o=false}return o}setToggleData(e,t,r){const i=this.toggleData.sections[t].settings[r];if(!i||i.value.data===e){return false}if(i.settingId==="notifications.music.account.showInLibrary"){CapabilitiesController.cachedAccountShowInLibraryEnabled=e}this.toggleData.sections[t].settings[r].value.data=e;if(typeof this.changedSettings[i.settingId]!=="undefined"&&this.changedSettings[i.settingId]!==e){delete this.changedSettings[i.settingId]}else{this.changedSettings[i.settingId]=e}return true}deviceLocalizationSuffix(){switch(Device.model){case"iPhone":return"Phone";case"iPad":return"Pad";case"iPod Touch":return"iPod";default:return"Phone"}}}function createAlertViewModel(e){return Object.assign(new AlertViewModel,e)}function createAlertAction(e){return Object.assign(new AlertAction,e)}function createAlertComponentController(e){return new AlertComponentController(e)}const BaseClass$7=mix(StorePageController).with(HeaderItemMixin,SocialProfileBadgingMixin);const OPT_IN_SEEN_KEY="OPT_IN_SEEN_KEY";const artistFavoritesCache={};const FAVORITING_ACTIVITY_TOPIC="FAVORITING_ACTIVITY_TOPIC";class ArtistController extends BaseClass$7{constructor({url:e,id:t,storePlatformDictionary:r={}}={}){super(...arguments);if(!this.url){this.url=r.url??e}if(!this.id){this.id=r.id??t}this.onNotificationsEnabledChange=()=>{this.updateNotificationSettingsIfNeeded()}}updateHeaderItem(e={},t={}){const r=getPhoneArtistPromoArt(e);const i=t.artistContainerUrl;if(Device.model==="iPad"){const i=getPadArtistPromoArt(e,t);if(i&&i.cropStyle==="vc"){this.headerItem.promotionalBackgroundArtwork=createArtwork(i)}else if(i){this.headerItem.promotionalBackgroundArtworkForRegularWidth=createArtwork(i);if(r){this.headerItem.promotionalBackgroundArtwork=createArtwork(r)}}}else if(r){this.headerItem.promotionalBackgroundArtwork=createArtwork(r)}const n=e?.editorialVideo;if(n&&this.containsMotionArtistVideo(n)){if(n.motionArtistFullscreen16x9){delete n.motionArtistFullscreen16x9}this.headerItem.videoDetailArtwork=createVideoArtwork({dictionary:n,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionArtistVideoForUbers(n)})}this.headerItem.storePlatformDictionary=e;this.headerItem.title=e.name;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED;this.headerItem.promotionalLayoutStyle=HeaderItem.PROMOTIONAL_LAYOUT_STYLE.ARTIST;if(i){this.headerItem.contextualPlaybackProvidingURL=i}this.headerItem.onActionPerformed=(e,t,r,i,n)=>{const o=get(n,"target.id");const s=get(n,"targetId");const a=e?.storePlatformDictionary?.kind;const l="artistHeader";const c=metricsFieldsForHeaderItemAction(t,o,l,s,n?.actionUrl,a);if(c){recordClickEvent(...clickMetricsForImpressions(e,i,c))}};this.headerItem.onContentFavoritedChange=(e,t)=>{if(!this.id){logger$5.error("Artist favorites update request not attempted, no artist id available");return}const r=new MusicAPIURL("/v1/me/favorites");r.queryString.shouldIncludeFormatResourcesMap=false;r.queryString.addParameters({"ids[artists]":this.id});r.string().then(e=>requestMusicAPIResource(e,{method:t?HTTP.METHOD.POST:HTTP.METHOD.DELETE,shouldImportResponse:false})).then(e=>{if(e){this.headerItem.isContentFavorited=t;this.cacheArtistFavoriteResult(this.id,t);publish(FAVORITING_ACTIVITY_TOPIC,{});logger$5.info(`User Artist favorites updated for artist with id ${this.id}`)}else{logger$5.error(`Artist inFavorites update request failed with no response for artist with id ${this.id}`);this.headerItem.isContentFavorited=!t}return Promise.resolve()}).catch(e=>{logger$5.error(`Artist inFavorites request to music api failed for artist with id ${this.id}`,e);this.headerItem.isContentFavorited=!t})}}didLoad(){super.didLoad();registerGlobalCallback(CapabilitiesController,"onNotificationsEnabledChange",this.onNotificationsEnabledChange);this.loadPage()}willUnload(){super.willUnload();removeGlobalCallback(CapabilitiesController,"onNotificationsEnabledChange",this.onNotificationsEnabledChange)}willAppear(){super.willAppear();if(this.viewModel){this.badgeViewModel()}getSubscriptionStatus().then(e=>this.getArtistInFavorites(this.id,e)).then(()=>this.updateNotificationSettingsIfNeeded())}loadPage(){super.loadPage().then(()=>this.badgeViewModel(true)).then(()=>{if(this.viewModel){this.viewModel.onNeedsAdditionalChildViewModels=this.onNeedsAdditionalChildViewModels.bind(this)}})}cacheArtistFavoriteResult(e,t){artistFavoritesCache[e]=t}createAlertPresentationSegue(e,t,r,i){const n=createAlertViewModel({title:r,message:i,alertStyle:"alert",alertActions:[e,t]});const o=createAlertComponentController({viewModel:n});return createPresentationSegue({componentController:o})}updateNotificationSettingsIfNeeded(){const e=Persistence.localStorage.getItem(OPT_IN_SEEN_KEY);if(e){return Promise.resolve()}return Promise.all([getPushNotificationSettings(),userNotificationSettings()]).then((e=[])=>{this.notificationSettingsData=e;this.updateArtistFavoritedNotificationOptInSelectHandler()}).catch(e=>logger$5.error("Failed to fetch notification settings in ArtistController",e))}enableArtistPushNotifications(){const e={settings:[{settingId:"notifications.music.account.artistsAndShows",data:true},{settingId:"notifications.music.account.showInLibrary",data:true}]};const t={method:HTTP.METHOD.POST,body:e};return getBagValue("musicSubscription.setPushNotificationSettings").then(e=>{const r={v:2,serviceId:"com.apple.Music"};return fetch(constructURL(e,{params:r}),t)})}updateArtistFavoritedNotificationOptInSelectHandler(){if(this.notificationSettingsData.length===0){return null}const[e={},t]=this.notificationSettingsData;const r=t?.authorizationStatus;let i=false;const n=e?.sections||[];n.forEach(e=>{e.settings.forEach(e=>{if(e.settingId==="notifications.music.account.artistsAndShows"){i=e.value.data}})});if(r===UserNotificationSettings.AUTHORIZATION_STATUS.AUTHORIZED&&i){return null}const onSelect=()=>{Persistence.localStorage.setItem(OPT_IN_SEEN_KEY,true);if(r===UserNotificationSettings.AUTHORIZATION_STATUS.AUTHORIZED&&!i){const e=createAlertAction({title:localize("FUSE.TurnOn"),alertActionStyle:"default",onSelect:()=>{this.enableArtistPushNotifications()}});const t=createAlertAction({title:localize("FUSE.NotNow"),alertActionStyle:"cancel"});const r=localize("FUSE.Notifications.Favorites.Generic.OptIn.Title");const i=localize("FUSE.Notifications.Favorites.Account.OptIn.Message");return this.createAlertPresentationSegue(e,t,r,i)}else if(r===UserNotificationSettings.AUTHORIZATION_STATUS.NOT_DETERMINED){logger$5.log(`deviceNotificationAuthorizationStatus: ${r}`);return userNotificationAuthorizationSegue({userInitiated:false})}else if(r===UserNotificationSettings.AUTHORIZATION_STATUS.DENIED){const e=createAlertAction({title:localize("FUSE.TurnOn"),alertActionStyle:"default",onSelect:()=>{const e=new NotificationPreferencesController;e.enablingNewArtistContentFromDeepLink=true;return createPresentationSegue({componentController:e})}});const t=createAlertAction({title:localize("FUSE.NotNow"),alertActionStyle:"cancel"});const r=localize("FUSE.Notifications.Favorites.Generic.OptIn.Title");const i=localize("FUSE.Notifications.Favorites.Device.OptIn.Message");return this.createAlertPresentationSegue(e,t,r,i)}return createNoopSegue()};Object.assign(this.headerItem,{onSelect:onSelect},MetricsClickHandlers.baseItem)}getArtistInFavorites(e,t){if(!e||!t.isSubscribed||hasVoiceAccount(t)){return Promise.resolve()}const r=artistFavoritesCache[e];if(r!==undefined){this.headerItem.isContentFavorited=r;return Promise.resolve()}return getBagValue("countryCode").then(t=>{const r=new MusicAPIURL(`/v1/catalog/${t}/artists/${e}`);r.queryString.addParameters({fields:"inFavorites","omit[resource]":"autos"});return r.string()}).then(e=>requestMusicAPIResource(e,{shouldImportResponse:false})).then(e=>{const t=e.data?.[0]?.id;if(t===this.id){const r=e.resources?.artists?.[t]?.attributes?.inFavorites??false;this.headerItem.isContentFavorited=r;this.cacheArtistFavoriteResult(t,r)}return Promise.resolve()}).catch(t=>{logger$5.error(`Artist inFavorites request to music api failed for artist with id ${e}`,t)})}getMissingContentIds(e){const t=get(e,"pageData.content",[]);const r=get(e,"pageData.id");const i=["artist","results",r,"artistContemporaries"];const n=get(e,"storePlatformData",{});this.similarArtistIdentifiers=get(n,i,[]);const o=[...this.similarArtistIdentifiers];const s=t.reduce((e,t)=>{const r=t.adamIds||[];e.push(...r);return e},[]);return o.concat(s)}createViewModel(e){const t=get(e,"pageData.id");const r=get(e,"storePlatformData",{});const i=get(e,"pageData",{});const n=["artist","results",t];const o=get(r,n);const s=get(r,"lockup.results");const a=get(r,"product.results");const l=get(e,"pageData.content",[]);const c=shouldUseSplitView(l);const u=c?l.slice(2,l.length):l;const d=[];let g;if(o){g=get(o,"id");if(!this.id){this.id=g}this.updateHeaderItem(o,i)}if(Device.model==="iPhone"&&o&&o.classicalUrl){const e=createMusicBridges(g);if(e){d.push(e)}}if(c){const e=Device.model==="iPad"?12:8;const t=createFeaturedContentGrid(l[0],a||s);const i=createArtistContentShelf(l[1],s,g,e,r);const n=get(l,"[0].dkExternalId");const o=(n==="musicVideo"||n==="movie"||n==="uploadedVideo")&&Device.model==="iPad"?SplitWidgetViewModel.DISPLAY_STYLE.COMPACT_RIGHT:SplitWidgetViewModel.DISPLAY_STYLE.COMPACT_LEFT;const c=createSplitWidgetViewModel({leftViewModel:t,rightViewModel:i,displayStyle:o});d.push(c)}u.forEach(e=>{const t=createArtistContentShelf(e,s,g);if(t){d.push(t)}});if(o&&o.artistBio){d.push(createArtistBio(o))}if(this.similarArtistIdentifiers.length>0){const e={title:localize("FUSE.Bio.ArtistContemporaries"),adamIds:this.similarArtistIdentifiers,sectionName:"similarArtists"};const t=createArtistContentShelf(e,s,g,MAX_SHELF_ITEMS);if(t){d.push(t)}}return createVerticalStack({childViewModels:d})}containsMotionArtistVideo(e){return!!e?.motionArtistWide16x9}}function createBarButtonItem(e){const t=createDefaultOptions(e);return Object.assign(new BarButtonItem,t,e)}const SEE_ALL_CAP=50;const GLOBAL_CHARTS_SEE_ALL_CAP=12;const CITY_CHARTS_SEE_ALL_CAP=12;function isGlobalChart(e){return e?.id==="119"}function isCityChart(e){return e?.id==="135"}function createChart(e={},t,r){const i=t?createTopChartsGridFromLockups:createTopChartsShelfFromLockups;const n=e.shortTitle||e.title;const o=e.adamIds||[];const s=!(isGlobalChart(e)||isCityChart(e));let a=o;if(!t){if(isGlobalChart(e)){a=o.slice(0,GLOBAL_CHARTS_SEE_ALL_CAP)}else if(isCityChart){a=o.slice(0,CITY_CHARTS_SEE_ALL_CAP)}else{a=o.slice(0,SEE_ALL_CAP)}}const l=i(a,r,{options:{title:n},sectionOptions:{isRankedList:s}});const c=get(l,"sections[0].items.length");const u=e.seeAllUrl;if(u&&l&&cthis.badgeViewModel(true))}willAppear(){super.willAppear();if(this.viewModel){this.badgeViewModel()}}getMissingContentIds(e){let t;if(this.singleChart){t=get(e,"pageData.selectedChart.adamIds",[])}else{const r=get(e,"pageData.topCharts",[]);t=r.reduce((e,t)=>{const r=t.adamIds||[];let i;if(isGlobalChart(t)){i=GLOBAL_CHARTS_SEE_ALL_CAP}else if(isCityChart(t)){i=CITY_CHARTS_SEE_ALL_CAP}else{i=SEE_ALL_CAP}e.push(...r.slice(0,i));return e},[])}return t}getButtonName(e){const t=e?.genre;const r=e?.categoryList;let i;if(r){if(t.id===r.genreId){i=r.parentCategoryLabel}else if(r.children){const e=r.children;const n=e.find(e=>e.genreId===t.id);i=n?get(n,"name",""):""}}return i}onGenreChange(e){if(this.headerItem.trailingBarButtonItem.title){this.headerItem.trailingBarButtonItem.title=e?.title}this.url=e?.url;this.pageData=null;this.viewModel=null;this.pendingSelectedItem=e;this.loadPage().then(()=>{this.pendingSelectedItem=null})}getPreSelectedMenuItem(e,t,r){let i;if(r){i=querystringEs3.parse(url.parse(r).query).genreId}if(!i){i=e?.genre?.id}let n;Object.keys(t.items).some(e=>{const r=querystringEs3.parse(url.parse(t.items[e].url).query);const o=i===r.genreId;if(o){n=t.items[e]}return o});return n}createGenreMenu(e){const t=[];const r=e?.categoryList;if(!r){logger$5.warn("No pageData.categoryList set in TopController:createGenreMenu");return}const i=r.url;const n=r.parentCategoryLabel;const o=createMenuItem({title:n,url:i,onSelect:this.onGenreChange.bind(this)});t.push(o);const s=r.children||[];let a=0;for(a;a{if(t){const i=createChart(t,this.singleChart,r);if(i){e.push(i)}}return e},[]);const o=this.singleChart?i[0]?.shortTitle||i[0]?.title:e?.pageData.pageTitle;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE;this.headerItem.title=o;const s=e?.pageData;const a=this.singleChart&&s?.selectedChart.kinds.playlist;if(!a){const e=createBarButtonItem({title:this.getButtonName(s),menu:this.createGenreMenu(s)});this.headerItem.trailingBarButtonItem=e}if(n.length>0){t=createVerticalStack({childViewModels:n})}return t}}function findContentIds$2(e){return get(e,"pageData.adamIds",[])}function createParagraphViewModel(e){const t=createParagraph({text:e.description,title:e.title,shouldHideDivider:true});return t}function createRadioShowContentGrid(e=[],t){const r=get(Grid,"ADAPTIVE_LAYOUT_STYLE.DEFAULT");const itemIteratorCallback=(e,t)=>{const r=get(t,"showHostName");return createGridItem({storePlatformDictionary:t,subtitle:r})};const gridCallback=e=>createGrid(Object.assign(e,{adaptiveLayoutStyle:r}));return createGridWithIterator(e,t,itemIteratorCallback,createGridSection,gridCallback)}function createRadioContentGrid(e=[],t){const r=Grid.ADAPTIVE_LAYOUT_STYLE.DEFAULT;const i=GridSection.UNIFORM_CELL_TYPE.FEATURED_RADIO_SHOW;const n=checkDataForIdenticalNotes(e,t);const itemIteratorCallback=(e,t)=>{let r=null;t=sanitizeItunesNotes(t);if(t?.radioStationTypeId!==4){const e=localizedMonthDayYearStringFromReleaseDate(t?.airTime?.start);r=n&&e?e:t?.itunesNotes?.standard}return createGridItem({storePlatformDictionary:t,headline:r})};const sectionIteratorCallback=e=>createGridSection(Object.assign(e,{uniformCellType:i}));const gridCallback=e=>createGrid(Object.assign(e,{adaptiveLayoutStyle:r}));return createGridWithIterator(e,t,itemIteratorCallback,sectionIteratorCallback,gridCallback)}function createArtistContentGrid(e=[],t){const r=Grid.ADAPTIVE_LAYOUT_STYLE.COMPACT_LIST;const i=GridSection.UNIFORM_CELL_TYPE.ARTIST;const itemIteratorCallback=(e,t)=>createGridItem({storePlatformDictionary:t});const sectionIteratorCallback=e=>createGridSection(Object.assign(e,{uniformCellType:i}));const gridCallback=e=>createGrid(Object.assign(e,{adaptiveLayoutStyle:r}));return createGridWithIterator(e,t,itemIteratorCallback,sectionIteratorCallback,gridCallback)}function createBroadcastRadioShowContentGrid(e=[],t){const r=get(Grid,"ADAPTIVE_LAYOUT_STYLE.DEFAULT");const itemIteratorCallback=(e,t)=>{const r=getBroadcastRadioShowSubtitle(t);if(r){t.itunesNotes={short:r}}return createGridItem({storePlatformDictionary:t})};const gridCallback=e=>createGrid(Object.assign(e,{adaptiveLayoutStyle:r}));return createGridWithIterator(e,t,itemIteratorCallback,createGridSection,gridCallback)}function createMixedKindContentGrid(e=[],t){const r=get(Grid,"ADAPTIVE_LAYOUT_STYLE.DEFAULT");const i=getKindsFromMixedContent(e,t);const n=i.indexOf("brand")!==-1&&i.indexOf("iTunesBrand")!==-1;const o=n?null:GridSection.UNIFORM_CELL_TYPE.ALBUM;const itemIteratorCallback=(e,t)=>createGridItem({storePlatformDictionary:t});const sectionIteratorCallback=e=>createGridSection(Object.assign(e,{uniformCellType:o}));const gridCallback=e=>createGrid(Object.assign(e,{adaptiveLayoutStyle:r}));return createGridWithIterator(e,t,itemIteratorCallback,sectionIteratorCallback,gridCallback)}function getFirstAvailableItemId(e,t){return e.find(e=>t[e]&&t[e].kind)}function createViewModel$1(e){const t=e?.pageData?.pageTitle;const r=findContentIds$2(e);const i=e?.storePlatformData?.lockup?.results||{};const n=getFirstAvailableItemId(r,i);const o=i[n];const s=e?.pageData?.description;const a=[];const l=r.find(e=>isBroadcastRadioShowContent(i[e]));const c=containsMixedContent({ids:r,lockupData:i});let u;let d;if(c){const e=getMixedContentTypes({ids:r,lockupData:i});if(e.get("radioStation")&&e.get("album")&&e.size===2){d=createRadioContentGrid(r,i)}else{d=createMixedKindContentGrid(r,i)}}else if(isBrandShowContent(o)){d=createRadioShowContentGrid(r,i)}else if(l){d=createBroadcastRadioShowContentGrid(r,i)}else if(isRadioContent(o)){d=createRadioContentGrid(r,i)}else if(o.kind==="artist"){d=createArtistContentGrid(r,i)}else{if(!o){logger$5.warn(`Missing first item with ID ${n}`)}const e={title:t};if(o&&(o.kind==="playlist"||o.kind==="activity"||o.kind==="artist")){e.adaptiveLayoutStyle=Grid.ADAPTIVE_LAYOUT_STYLE.COMPACT_LIST}d=createGridFromLockups(r,i,{options:e})}if(s){a.push(createParagraphViewModel({description:sanitizeStringAndEnableTags(s),shouldHideDivider:true}))}if(d){a.push(d)}if(a.length>0){u=createVerticalStack({childViewModels:a})}return u}const BaseClass$9=mix(StorePageController).with(SocialProfileBadgingMixin);class RoomController extends BaseClass$9{didLoad(){super.didLoad();this.loadPage()}loadPage(){return super.loadPage().then(()=>this.badgeViewModel(true))}willAppear(){super.willAppear();if(this.viewModel){this.badgeViewModel()}}getMissingContentIds(e){return findContentIds$2(e).map(e=>String(e))}createViewModel(e){const t=get(e,"pageData.uber");if(t){this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE;this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:get(t,"masterArt")})}else{this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}const r=get(e,"pageData.pageTitle")||get(e,"pageData.title");if(r){this.headerItem.title=r}return createViewModel$1(e)}}function createParagraphViewModel$1(e){const t=createParagraph({text:e.description,textSize:e.displayStyle,title:e.title,shouldHideDivider:true});return t}function getShelfByLockupStyle(e,t){const r=e.title;const i=get(e,"fcMetadata.lockupStyle");const n=e.adamIds||[];const o=get(t[n[0]],"kind");const s=["tvEpisode","showBrand","movie"].indexOf(o)!==-1;let a;let l={};let c=false;let u=false;let d=false;let g;switch(i){case"Spotlight":if(Device.model==="iPhone"){l={uniformCellType:GridSection.UNIFORM_CELL_TYPE.CUSTOM_ROOM_ALBUM,title:r};d=true}else{l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.CUSTOM_ROOM_ALBUM,height:ShelfSection.HEIGHT.COMPACT}}if(s){l={title:r};if(o==="tvEpisode"){d=false;l={title:""}}}break;case"Spotlight+ShortCopy":if(Device.model==="iPhone"){l={uniformCellType:GridSection.UNIFORM_CELL_TYPE.CUSTOM_ROOM_ALBUM,title:r};d=true}else{l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.CUSTOM_ROOM_ALBUM,height:ShelfSection.HEIGHT.COMPACT}}if(s){l={title:r};if(o==="tvEpisode"){d=false;l={title:""}}}c=true;break;case"Grid":if(Device.model!=="iPad"){l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.CUSTOM_ROOM_ALBUM,height:ShelfSection.HEIGHT.DEFAULT}}else if(o==="playlist"){l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM,height:ShelfSection.HEIGHT.DEFAULT}}if(s){l={title:""}}break;case"Grid+ShortCopy":if(Device.model==="iPad"&&o==="artist"){l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM,height:ShelfSection.HEIGHT.DEFAULT};a=true}else if(Device.model!=="iPad"){l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.CUSTOM_ROOM_ALBUM,height:ShelfSection.HEIGHT.DEFAULT}}if(s){l={title:""}}c=true;break;default:if(o==="artist"){l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.CUSTOM_ROOM_ALBUM,height:ShelfSection.HEIGHT.DEFAULT}}else if(o==="radioStation"&&i!=="Default+Copy"){l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM};u=true}else if(o==="musicVideo"){l={uniformCellType:null}}else if(o!=="song"&&!s){l={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}}if(s){l={title:""}}break}const h=n.reduce((e,r)=>{const n=cloneDeep(t[r]);if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){return e}const o=get(n,"itunesNotes");let s;if(c){const e=sanitizeString(get(o,"short"));if(a){n.genreNames[0]=e}else{s=e}}if(u&&o){n.itunesNotes=null}if(n){const t={storePlatformDictionary:n};if(i==="Spotlight+ShortCopy"&&o){t.title=n.name;t.subtitle=o.short}else{t.description=s}if(d){if(e.length0){l=Object.assign(l,{items:h});if(d){const e=createGridSection(l);g=createGrid({sections:[e]})}else{const e=createShelfSection(l);g=createShelf({sections:[e],title:r})}}return g}function createLinkMenu(e=[],t){const r=[];let i=0;for(i;i{const r=createSegment(t,i);if(r){if(Array.isArray(r)){e=e.concat(r)}else{e.push(r)}}return e},[]);const a=o.concat(s);if(a.length>0){t=createVerticalStack({childViewModels:a})}return t}class RoomController$1 extends StorePageController{didLoad(){this.loadPage()}getMissingContentIds(e){const t=get(e,"pageData.segments",[]);return t.reduce((e,t)=>{const r=t.adamIds||[];e.push(...r);return e},[]).map(e=>String(e))}createViewModel(e){const t=get(e,"pageData.uber");if(t){this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED;this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:get(t,"masterArt")})}const r=get(e,"pageData.pageTitle");if(r){this.headerItem.title=r}return createViewModel$2(e)}}function createInlinePopup(e={},t={}){const r=e.onCloseButtonSelectionPerformed;const onCloseButtonSelectionPerformed=(e,i)=>{if(typeof r==="function"){r(e,i)}const n=assignClickMetricsFields({actionType:"dismiss",targetId:"DismissX"},t);recordClickEvent(...clickMetricsForImpressions(e,i,n))};return Object.assign(new InlinePopup,e,{onCloseButtonSelectionPerformed:onCloseButtonSelectionPerformed})}function createInlinePopupButton(e){const t=createDefaultOptions(e);return Object.assign(new InlinePopupButton,t,e)}function createContextAction(e){return Object.assign(new ContextAction,e)}function createOrderedPlaylistSelector(e){return Object.assign(new OrderedPlaylistSelector,e)}function createOrderedPlaylistSelectorItem(e){return Object.assign(new OrderedPlaylistSelectorItem,e)}function createSocialOnboardingVerticalStack(e){return Object.assign(new SocialOnboardingVerticalStack,e)}function createSocialOnboardingFriendsFinder(e){return Object.assign(new SocialOnboardingFriendsFinder,e)}function createSocialOnboardingNetwork(e){return Object.assign(new SocialOnboardingNetwork,e)}function createSocialProfileEditor(e){const t={onTextFieldSelectionPerformed:(e,t,r)=>{const i=upperFirst(t);const n={actionType:"select",actionDetails:{action:`edit${i}Field`}};recordClickEvent(...clickMetricsForImpressions(e,r,n))},onPhotoPickerSelectionPerformed:(e,t)=>{const r={actionType:"select",actionDetails:{action:"editPhoto"}};recordClickEvent(...clickMetricsForImpressions(e,t,r))}};return Object.assign(new SocialProfileEditor,t,e)}function createSocialOnboardingWelcomeViewModel(e){return Object.assign(new SocialOnboardingWelcomeViewModel,e)}function createPrivacyLinkViewModel(){return new PrivacyLinkViewModel}const BaseClass$a=mix(ComponentController).with(MetricsMixin);const createDefaultCancelBarButtonItem=()=>{const e=localize("FUSE.Social.Onboarding.Share.CTA2");const t=createBarButtonItem({title:e});addClickMetricsHandlerToItem(t,()=>({actionDetails:{localizedTitle:e}}));return t};class SetupProfileController extends BaseClass$a{constructor({promiseToFullfillBeforeLoading:e,isDismissable:t}={}){super(...arguments);this.promiseToFullfillBeforeLoading=e;this.isDismissable=t}fetchData(){if(this.promiseToFullfillBeforeLoading){return this.promiseToFullfillBeforeLoading}return Promise.resolve()}updateHeader(){}updateViewModel(){}updateMetricsFields(){}updateModels(){return this.fetchData().then(e=>{this.updateMetricsFields(e);this.updateViewModel(e);this.updateHeader()})}setSocialOnboardingVerticalStack(e){const t=Object.assign({},e);if(this.isDismissable&&!e.cancelBarButtonItem){t.cancelBarButtonItem=createDefaultCancelBarButtonItem()}this.viewModel=createSocialOnboardingVerticalStack(t)}get pageType(){return"Picker"}get metricsId(){throw new Error("Subclasses of SetupProfileController must override metricsId() or pageId()")}get pageId(){return`socialOnboarding${this.metricsId}`}createPageMetrics(){this.pageFields={pageType:this.pageType,pageId:this.pageId,page:combineWithSeparator(this.pageType,this.pageId)}}didAppear(){this.pageContext=currentPageContext();super.didAppear()}didLoad(){super.didLoad();waitForLocInitialization().then(()=>this.updateModels()).then(()=>{this.createPageMetrics();this.considerRecordingPageEvent()}).catch(e=>{logger$5.error(e)})}}function createToggleSelectorViewModel(e){return Object.assign(new ToggleSelectorViewModel,e)}function createToggleSelectorItem(e){return Object.assign(new ToggleSelectorItem,e)}function createMultiChoiceViewModel(e){return Object.assign(new MultiChoiceViewModel,e)}function createMultiChoiceItem(e){return Object.assign(new MultiChoiceItem,e)}class PlaylistsProfileController extends SetupProfileController{constructor(...e){super(...e);const[{privateSocialPlaylists:t}]=e;this.privateSocialPlaylists=t}get metricsId(){return"SharePlaylists"}updateHeader(){this.headerItem.title=localize("FUSE.Social.Onboarding.SharePlaylists.Header");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}fetchData(){return super.fetchData().then(()=>{if(this.privateSocialPlaylists){return this.privateSocialPlaylists}return getSocialBag().then(e=>e.getPrivateSocialPlaylists).then(e=>fetchJSONWithStorePlatformData(e,{isPersonalized:true,getIdsMissingStorePlatformData:e=>get(e,"ids",[])}))}).catch(e=>logger$5.error("Failed to fetchData in PlayalistsProfileController",e))}setPrivateSocialPlaylists(){const e=get(this.playlistsVisibilityEditor,"selectedItems",[]);const t=e.map(e=>e.id);return setPrivateSocialPlaylists(t)}updateViewModel(e={}){const t=[];this.playlistsVisibilityEditor=createPlaylistsVisibilityEditor(e);if(this.playlistsVisibilityEditor){t.push(this.playlistsVisibilityEditor)}else{t.push(createParagraph({text:localize("FUSE.Social.Onboarding.SharePlaylists.NoPlaylists"),shouldHideDivider:true}))}this.setSocialOnboardingVerticalStack({childViewModels:t,nextStepButton:this.nextStepButton()})}nextStepButton(){return createDoneButtonForOnboardingFlow({onSelect:this.setPrivateSocialPlaylists.bind(this),instantiatedFromUpsell:this.instantiatedFromUpsell})}}function createCircleImage(e){return Object.assign(new CircleImage,e)}function createCircleImageForContactsConsent(e){return createCircleImage({fullName:e.name,title:localize("FUSE.Social.ContactsConsent.Title"),artwork:createArtwork({dictionary:{url:get(e,"profileImage.url"),width:get(e,"profileImage.width"),height:get(e,"profileImage.height")}})})}function createTopParagraph(e){const t=SocialContactsConsentController.getAppropriateLinkForAppleID(e);return createParagraph({shouldHideDivider:true,text:`${localize("FUSE.Social.ContactsConsent.HelpOthers.Text",{link:t})}`,textStyle:"light",title:localize("FUSE.Social.ContactsConsent.HelpOthers.Title")})}function createBottomParagraph(){return createParagraph({shouldHideDivider:true,text:`${localize("FUSE.Social.ContactsConsent.FriendRecommendations.Text")}`,textStyle:"light",title:localize("FUSE.Social.ContactsConsent.FriendRecommendations.Title")})}function createChildViewModels$1(e,t){return[createCircleImageForContactsConsent(e),createTopParagraph(t),createBottomParagraph()]}function createContactsConsentBarButtonItem(e){return createBarButtonItem({title:localize("FUSE.NotNow"),onSelect:e})}function createNextStepButton(e){return createGridItemButton({shouldDismissPresentation:true,title:localize("FUSE.Allow"),onSelect:e})}function createContactsConsentVerticalStack(e,t,r={}){return createSocialOnboardingVerticalStack({cancelBarButtonItem:createContactsConsentBarButtonItem(r.onFailureCallback),childViewModels:createChildViewModels$1(e,t),nextStepButton:createNextStepButton(r.onSuccessCallback),pinnedButtonsHeaderText:localize("FUSE.Social.ContactsConsent.Button.PinnedText")})}function decorateWithManager(e,t){e.getManager=()=>t;return e}const updateProfileForConsentCollection=e=>{const t=Object.assign({isContactsCheckAllowed:e},socialRequests.getIsDiscoverableByContactRequestBody(e));return socialRequests.updateProfile({body:t}).then(()=>{Store.account.reloadUserProfileIfNeeded();Object.assign(Store.account.userProfile,t)})};class SocialContactsConsentController extends ComponentController{didLoad(){super.didLoad();Promise.all([waitForLocInitialization(),getUserProfile(),fetchUsingSameAccountForCloudAndStore()]).then(([,e,t])=>{this.viewModel=createContactsConsentVerticalStack(e,t,{onSuccessCallback:()=>{updateProfileForConsentCollection(true).catch(e=>logger$5.error("Failed to updateProfileForConsentCollection in SocialContactsConsentController",e))},onFailureCallback:()=>{updateProfileForConsentCollection(false).catch(e=>logger$5.error("Failed to updateProfileForConsentCollection in SocialContactsConsentController",e))}})}).catch(e=>logger$5.error("Failed to create social contacts consent vertical stack",e))}willAppear(){super.willAppear();SocialContactsConsentController.getManager().opened(this)}willDisappear(){super.willDisappear();SocialContactsConsentController.getManager().closed()}}SocialContactsConsentController.discoverabilityConsentVersion=1;SocialContactsConsentController.hasSatisfiedConsentPrompt=(e={})=>e.discoverabilityConsentVersion===SocialContactsConsentController.discoverabilityConsentVersion;SocialContactsConsentController.getAppropriateLinkForAppleID=e=>e?"prefs:root=APPLE_ACCOUNT&path=APPLE_ACCOUNT_CONTACT":"https://appleid.apple.com/manage/section/account/edit";decorateWithManager(SocialContactsConsentController,{isCurrentlyPresenting:null,opened(e){this.isCurrentlyPresenting=true;this.currentlyPresentingCtrl=e},closed(){this.isCurrentlyPresenting=false;this.currentlyPresentingCtrl=null}});const getIsDiscoverableByContactRequestBody=e=>({discoverabilityConsentVersion:SocialContactsConsentController.discoverabilityConsentVersion,isDiscoverableByContact:e});const getPrivateSocialPlaylists=()=>getSocialBagValue("getPrivateSocialPlaylists").then(e=>fetchJSONWithStorePlatformData(e,{getIdsMissingStorePlatformData:e=>get(e,"ids",[]),isPersonalized:true})).catch(e=>{logger$5.error("Failed to getPrivateSocialPlaylists",e);throw e});const getPushNotificationSettings$1=()=>getSocialBagValue("getPushNotificationSettings").then(e=>fetchJSON(e)).catch(e=>{logger$5.error("Failed to getPushNotificationSettings",e);throw e});const setPushNotificationSettings$1=(e={})=>{const t=Object.assign({method:HTTP.METHOD.POST},e);return getSocialBagValue("setPushNotificationSettings").then(e=>fetch(e,t)).catch(e=>{logger$5.error("Failed to setPushNotificationSettings",e);throw e})};const updateProfile=(e={})=>{const t=Object.assign({owner:{type:"user",id:userDSID()}},e.body);return getBagValue("musicCommon.updateProfile").then(e=>fetch(e,{body:t,method:HTTP.METHOD.POST})).catch(e=>{logger$5.error("Failed to updateProfile",e);throw e})};const updateProfileVisibility=e=>updateProfile({body:{isPrivate:!e}});const musicAPIRecommendedFriendsPOST=(e=[])=>{const t={method:HTTP.METHOD.POST,body:{ids:{socialProfiles:e}}};const r=new MusicAPIURL("/v1/social/recommended-friends");r.queryString.addParameters({"extend[social-profiles]":"topGenreNames",meta:"reason"});return r.string().then(e=>requestMusicAPIResponse(e,t)).catch(e=>{logger$5.error("Failed fetching Music API recommended friends.",e);throw e})};const getFriendsWhoListenedToContainer=e=>{if(!e){return Promise.reject(new Error("Unable to get friends who listened, missing container id"))}if(!SocialProfileBadgingController.isContentBeingListenedToByFriends(e)){return Promise.resolve()}return getSocialBagValue("socialProfileSwoosh").then(t=>fetchJSONWithStorePlatformData(constructURL(t,{params:{v:1,id:e}}),{getIdsMissingStorePlatformData:e=>get(e,"ids",[])})).catch(e=>{logger$5.error("Failed to get friend who listened.",e);throw e})};const getFriendsWhoAddedPlaylist=e=>{if(!e){return Promise.reject(new Error("Unable to get friends who added playlist, missing playlist id"))}return getSocialBagValue("playlistSubscribersSwoosh").then(t=>constructURL(t,{params:{v:1,id:e}})).then(e=>fetchJSONWithStorePlatformData(e,{getIdsMissingStorePlatformData:e=>get(e,"ids",[])})).catch(e=>{logger$5.error("Failed to get friend who added playlist.",e);throw e})};const socialRequests={getIsDiscoverableByContactRequestBody:getIsDiscoverableByContactRequestBody,getFriendsWhoAddedPlaylist:getFriendsWhoAddedPlaylist,getFriendsWhoListenedToContainer:getFriendsWhoListenedToContainer,getPrivateSocialPlaylists:getPrivateSocialPlaylists,getPushNotificationSettings:getPushNotificationSettings$1,musicAPIRecommendedFriendsPOST:musicAPIRecommendedFriendsPOST,setPushNotificationSettings:setPushNotificationSettings$1,updateProfile:updateProfile,updateProfileVisibility:updateProfileVisibility};function createFindingByAppleIdToggle(e){const t=SocialContactsConsentController.getAppropriateLinkForAppleID(e);return createToggleSelectorItem({isToggled:true,name:"contactsConsent",subtitleText:localize("FUSE.Social.ContactsConsent.Onboarding.HowYouShare.Subtitle.NoLink",{link:t}),titleText:localize("FUSE.Social.ContactsConsent.Onboarding.HowYouShare.Title")})}function createContactsUploadItemToggle(){return createToggleSelectorItem({isToggled:true,name:"contactsUpload",subtitleText:localize("FUSE.Social.ContactsConsent.Onboarding.Subtitle"),titleText:localize("FUSE.Social.ContactsConsent.Onboarding.Title")})}function createVisibilityChoiceModel(e={}){const t=[createMultiChoiceItem({titleText:localize("FUSE.Social.Onboarding.HowYouShare.SubHeader1")}),createMultiChoiceItem({titleText:localize("FUSE.Social.Onboarding.HowYouShare.SubHeader2")})];const r=get(e,"isPrivate")?t[1]:t[0];return createMultiChoiceViewModel({items:t,selectedItem:r})}class VisibilityProfileController extends SetupProfileController{get metricsId(){return"Privacy"}fetchData(){return super.fetchData().then(()=>Promise.all([fetchUsingSameAccountForCloudAndStore(),socialRequests.getPrivateSocialPlaylists()])).catch(e=>logger$5.error("Failed to fetchData in VisibilityProfileController",e))}updateHeader(){this.headerItem.title=localize("FUSE.Social.Onboarding.HowYouShare.Header");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}updateViewModel([e,t]=[]){const r=this.nextStepButtonForPrivateSocialPlaylists(t);this.visibilityChoiceModel=createVisibilityChoiceModel();this.findingByAppleIdToggleItem=createFindingByAppleIdToggle(e);this.contactsUploadToggleItem=createContactsUploadItemToggle();this.setSocialOnboardingVerticalStack({childViewModels:[this.visibilityChoiceModel,createParagraph({shouldHideDivider:true,text:localize("FUSE.Social.ContactsConsent.Onboarding.FriendRecommendation.Header"),textSize:ParagraphViewModel.TEXT_SIZE.EXTRA_SMALL,textStyle:ParagraphViewModel.TEXT_STYLE.LIGHT}),createToggleSelectorViewModel({items:[this.contactsUploadToggleItem,this.findingByAppleIdToggleItem]})],nextStepButton:r})}nextStepButtonForPrivateSocialPlaylists(e){const t=get(e,"ids",[]).length>0;const r=CapabilitiesController.isCloudLibraryEnabled&&t;if(r){return this.gridItemButton(e)}return createDoneButtonForOnboardingFlow({onSelect:this.updateProfileVisibility.bind(this),instantiatedFromUpsell:this.instantiatedFromUpsell})}gridItemButton(e){return createNextButtonForOnboardingFlow({ControllerClass:PlaylistsProfileController,onSelectCallbackPromise:()=>this.updateProfileVisibility().catch(e=>logger$5.error("Failed to updateProfileVisibility in VisibilityProfileController",e)),initData:{privateSocialPlaylists:e}})}updateProfileVisibility(){const e=this.findingByAppleIdToggleItem.isToggled;const t=this.contactsUploadToggleItem.isToggled;const r=Object.assign({isContactsCheckAllowed:t},{isPrivate:this.visibilityChoiceModel.selectedItem!==this.visibilityChoiceModel.items[0]},socialRequests.getIsDiscoverableByContactRequestBody(e));return socialRequests.updateProfile({body:r})}}function createNetworks(e={}){const t=e.socialNetworks||[];return t.map(e=>{const t={identifier:e.name,name:e.nameForDisplay,authURL:e.oauth_url,redirectURL:e.redirectUrl,authenticated:e.isAuthenticated,authProtocol:e.oauthProtocol};const r=e.artwork;if(r){t.artwork=createArtwork({dictionary:r})}return createSocialOnboardingNetwork(t)})}class FriendsProfileController extends SetupProfileController{static get titleCTA(){return localize("FUSE.Social.Onboarding.CTA.ContinueToFindContacts")}get metricsId(){return"FollowFriends"}constructor({isEditing:e=false}={}){super(...arguments);this.isEditing=e}updateHeader(){this.headerItem.title=localize("FUSE.Social.FollowMoreFriends.Header");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE}fetchData(){return super.fetchData().then(()=>getSocialBag()).then((e={})=>e.getOAuthSocialNetworks).then(e=>fetchJSON(e)).catch(e=>logger$5.error(e))}updateViewModel(e){const t=createNetworks(e);const r=createSocialOnboardingFriendsFinder({networks:t,onButtonSelectionPerformed:(e,t,r)=>{const i={actionDetails:{action:t}};recordClickEvent(...clickMetricsForImpressions(e,r,i))}});const i={childViewModels:[r]};const onSelect=()=>followProfiles(get(r,"selectedFriendIdentifiers"));let n;if(this.isEditing){n=createGridItemButton({title:localize("Done"),onSelect:onSelect,shouldDismissPresentation:true});addClickMetricsHandlerToItem(n,()=>({actionDetails:{title:"Done"}}))}else{n=createNextButtonForOnboardingFlow({ControllerClass:VisibilityProfileController,onSelectCallbackPromise:onSelect})}i.nextStepButton=n;this.setSocialOnboardingVerticalStack(i)}}class HandleProfileController extends SetupProfileController{get metricsId(){return"SetupId"}fetchData(){return super.fetchData().then(getSuggestedHandles)}updateHeader(){this.headerItem.title=localize("FUSE.Social.Onboarding.FindYou.Header");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}updateViewModel(e={}){const t=e.suggestions&&e.suggestions.length>0?e.suggestions[0]:"";this.setSocialOnboardingVerticalStack({childViewModels:[createSocialProfileEditor({suggestedHandle:t,isNameEditable:true}),createParagraph({shouldHideDivider:true})],pinnedChildViewModel:createPrivacyLinkViewModel(),nextStepButton:createNextButtonForOnboardingFlow({ControllerClass:FriendsProfileController})})}}function createNextButton(e=localize("FUSE.Social.Onboarding.Share.CTA1")){const t=createGridItemButton({title:e,onSelect:()=>createPushSegue({componentController:new HandleProfileController})});addClickMetricsHandlerToItem(t,()=>({actionDetails:{localizedTitle:e}}));return t}function createCancelButton(e){const t=createGridItemButton({title:e,shouldDismissPresentation:true});addClickMetricsHandlerToItem(t,()=>({actionDetails:{localizedTitle:e}}));return t}function createCancelBarButtonItem(e=localize("FUSE.Social.Onboarding.Share.CTA2")){const t=createBarButtonItem({title:e});addClickMetricsHandlerToItem(t,()=>({actionDetails:{localizedTitle:e}}));return t}function legacyViewModelData(){return{welcomeScreen:{title:localize("FUSE.Social.Onboarding.Share.Header"),paragraphs:[{subtitle:localize("FUSE.Social.Onboarding.Share.Subheader1"),description:localize("FUSE.Social.Onboarding.Share.Description1")},{subtitle:localize("FUSE.Social.Onboarding.Share.Subheader2"),description:localize("FUSE.Social.Onboarding.Share.Description2")},{subtitle:localize("FUSE.Social.Onboarding.Share.Subheader3"),description:localize("FUSE.Social.Onboarding.Share.Description3")}],actionTexts:[localize("FUSE.Social.Onboarding.Share.CTA1"),localize("FUSE.Social.Onboarding.Share.CTA2")]}}}function createLegacyWelcomePage(e=legacyViewModelData()){const t={};const{paragraphs:r=[],actionTexts:i=[],title:n}=get(e,"welcomeScreen",{});const[o,s]=i;t.childViewModels=r.map(e=>createParagraph({title:e.subtitle,text:e.description,shouldHideDivider:true}));t.nextStepButton=createNextButton(o);t.cancelStepButton=createCancelButton(s);return{viewModel:t,headerTitle:n}}function createArtworkWelcomePage(e){const{headline:t,title:r,description:i,artwork:n,viewType:o,actionText:s}=get(e,"welcomeScreen",{});let a;let l;switch(o){case"ARTWORK_CENTER_ALIGN":a=SocialOnboardingWelcomeViewModel.TEXT_ALIGNMENT.CENTER;l=SocialOnboardingWelcomeViewModel.ARTWORK_SCALE_MODE.SCALE_ASPECT_FIT_HEIGHT;break;case"ARTWORK_LEFT_ALIGN":a=SocialOnboardingWelcomeViewModel.TEXT_ALIGNMENT.LEADING;l=SocialOnboardingWelcomeViewModel.ARTWORK_SCALE_MODE.SCALE_ASPECT_FIT_HEIGHT;break;default:a=SocialOnboardingWelcomeViewModel.TEXT_ALIGNMENT.LEADING;l=SocialOnboardingWelcomeViewModel.ARTWORK_SCALE_MODE.SCALE_ASPECT_FIT;logger$5.error(`createArtworkWelcomePage() called with unsupported viewType: ${o}`)}const c=createSocialOnboardingWelcomeViewModel({headline:t,title:r,subtitle:i,textAlignment:a,artworkScaleMode:l});if(n){c.artwork=createArtwork({dictionary:n})}return{viewModel:{childViewModels:[c],nextStepButton:createNextButton(s),cancelBarButtonItem:createCancelBarButtonItem()}}}function createWelcomePage(e){const t=get(e,"welcomeScreen.viewType");switch(t){case"ARTWORK_CENTER_ALIGN":case"ARTWORK_LEFT_ALIGN":return createArtworkWelcomePage(e);case"DEFAULT_ONBOARD_V0":return createLegacyWelcomePage(e);default:logger$5.error(`Unknown Welcome Screen viewType: ${t}`);return createLegacyWelcomePage()}}class WelcomeProfileController extends SetupProfileController{get pageId(){return this.metricsPageId}fetchData(){return super.fetchData().then(()=>{if(!SocialOnboardingWelcomeViewModel){return Promise.resolve()}return getSocialBag().then(e=>e.socialOnboardingWelcomeScreen).then(e=>fetchJSON(e))}).catch(e=>{logger$5.error("Error fetching data for Social Onboarding Welcome page",e);return Promise.resolve()})}updateViewModel(e){const t=e?createWelcomePage(e):createLegacyWelcomePage();if(t.headerTitle){this.headerItem.title=t.headerTitle;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}this.setSocialOnboardingVerticalStack(t.viewModel)}updateMetricsFields(e){this.metricsPageId=get(e,"metrics.pageId","socialOnboardingWelcome")}}function createProfileVerticalStack(e){return Object.assign(new SocialProfileVerticalStack,e)}function createPersonalMixes(e){return Object.assign(new PersonalMixesViewModel,e)}function createPersonalMixItem(e){const t=createDefaultOptions(e);return Object.assign(new PersonalMixItem,t,e)}function createPersonalMixesFromLockups(e,t={},{options:r={},itemOptions:i={}}={}){let n;const o=e.reduce((e,r)=>{const n=t[r.contentId];if(n&&CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){e.push(createPersonalMixItem(Object.assign({storePlatformDictionary:n},i)))}return e},[]);if(o.length>0){n=createPersonalMixes(Object.assign({items:o},r))}return n}const BaseClass$b=mix(ComponentController).with(MetricsMixin);class FollowRequestController extends BaseClass$b{constructor({pageMetrics:e,pageFields:t}={}){super(...arguments);this.headerItem.title=localize("FUSE.Social.Profile.FollowRequests");this.pageMetrics=e;this.pageFields=t;this.followRequestCount=0}didLoad(){super.didLoad();this.loadPage()}didAppear(){this.pageContext=currentPageContext();super.didAppear()}createPageMetrics(){if(this.pageFields){const e=combineWithSeparator(this.pageFields.pageType,"FollowRequests");this.pageFields.pageType=e;this.pageFields.page=combineWithSeparator(e,this.pageFields.pageId)}}handleButtonSelectionPerformed(e){this.followRequestCount=Math.max(this.followRequestCount-1,0);updatePendingRequestsCount(this.followRequestCount);e(this.emptyListAction())}emptyListAction(){let e;if(this.followRequestCount===0){e=redirectToProfile()}return e}createViewModel(e){const t=get(e,"followRequests",[]);const r=get(e,"storePlatformData.lockup.results",[]);const i=createSocialProfileCollection({collectionStyle:SocialProfileCollection.COLLECTION_STYLE.FOLLOW_REQUESTS});const n=t.reduce((e,t)=>{const i=overrideSocialProfile(r[t.followerProfileId]);if(i){const t=createSocialProfile({storePlatformDictionary:i,hasRequestedToFollowCurrentUser:true});const onSelect=()=>createPushSegueForStoreContent(i);const r=this.handleButtonSelectionPerformed.bind(this);const n=this.handleButtonSelectionPerformed.bind(this);const o=createSocialProfileCollectionItem({profile:t,onSelect:onSelect,onApproveButtonSelectionPerformed:r,onDeclineButtonSelectionPerformed:n});e.push(o)}return e},[]);let o;this.followRequestCount=t.length;if(n.length>0){i.items=n;const e=[i];o=createVerticalStack({childViewModels:e})}return o}loadPage(){return getFollowRequests().then(e=>this.createViewModel(e)).then(e=>{this.createPageMetrics();this.viewModel=e;const onSelect=()=>approveAllFollowRequests();const t=createBarButtonItem({title:localize("FUSE.Social.Profile.FollowRequests.ApproveAll"),onSelect:onSelect});if(!this.headerItem.title){this.headerItem.title=localize("FUSE.Social.Profile.FollowRequests");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}this.headerItem.trailingBarButtonItem=t}).then(()=>{this.considerRecordingPageEvent()}).catch(e=>{logger$5.error(e);const t=userFacingMessageForError(e);if(t){this.viewModel=createMessageViewModel({message:t})}})}}function createEditorParagraph(){return createParagraph({text:localize("FUSE.Social.Profile.NameField.Disclaimer"),shouldHideDivider:true,textStyle:"light",textSize:get(ParagraphViewModel,"TEXT_SIZE.EXTRA_SMALL")})}function createEmptyParagraph(){return createParagraph({shouldHideDivider:true,title:" "})}function createSegueForOffboardingConfirmation(){const e=createAlertAction({title:localize("FUSE.Social.Profile.TurnOffSharing"),alertActionStyle:"default",onSelect:offboardUser});const t=createAlertAction({title:localize("FUSE.Social.Profile.Cancel"),alertActionStyle:"cancel"});const r=createAlertViewModel({title:localize("FUSE.Social.Profile.TurnOffSharing.Confirm"),alertStyle:"actionSheet",alertActions:[e,t]});const i=createAlertComponentController({viewModel:r});return createPresentationSegue({componentController:i})}const USER_PROFILE_WAS_EDITED="userProfileWasEdited";const BaseClass$c=mix(ComponentController).with(MetricsMixin);class SocialProfileEditController extends BaseClass$c{constructor(){super(...arguments);this.headerItem.title=localize("FUSE.Social.Profile.EditProfile.Header");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}createOffboardingButton(){const e=createGridItemButton({title:localize("FUSE.Social.Profile.TurnOffSharing"),onSelect:createSegueForOffboardingConfirmation});addClickMetricsHandlerToItem(e,()=>({actionDetails:{title:"Delete Profile"}}));return createGridWithButtons([e])}didLoad(){super.didLoad();waitForLocInitialization().then(()=>this.updateModels()).then(()=>{this.createPageMetrics();this.considerRecordingPageEvent()}).catch(e=>logger$5.error("Couldn't load edit profile page",e))}didAppear(){this.pageContext=currentPageContext();super.didAppear()}updateModels(){return this.fetchData().then(([e,t])=>this.updateViewModel(e,t))}get pageType(){return"Profile"}get pageId(){return"EditProfile"}createPageMetrics(){const e=isSocialProfilePrivateSync();const t=isSocialProfileVerifiedSync();this.pageFields={pageType:this.pageType,pageId:this.pageId,page:combineWithSeparator(this.pageType,this.pageId),pageDetails:{followState:"self",isPrivate:e,isVerified:t}}}getHideListeningToFlag(){return getListeningToSettings().then(e=>get(e,"listeningToSettings.hideListeningTo")).catch(e=>logger$5.error(e))}getPrivateSocialPlaylists(){let e;if(CapabilitiesController.isCloudLibraryEnabled){e=getSocialBag().then(e=>e.getPrivateSocialPlaylists).then(e=>fetchJSONWithStorePlatformData(e,{isPersonalized:true,shouldCacheStorePlatformData:false,getIdsMissingStorePlatformData:e=>get(e,"ids",[])})).catch(e=>logger$5.error(e))}else{e=Promise.resolve({})}return e}fetchData(){return Promise.all([this.getHideListeningToFlag(),this.getPrivateSocialPlaylists()]).catch(e=>logger$5.error(e))}setPrivateSocialPlaylists(){const e=get(this.playlistsVisibilityEditor,"selectedItems",[]);const t=e.map(e=>e.id);return setPrivateSocialPlaylists(t)}setListeningTo(){const e=get(this.hideListeningToToggle,"items[0].isToggled");const t={listeningToSettings:{hideListeningTo:!e}};setListeningToSettings(t)}updateProfileVisibility(){if(this.visibilityChoiceModel&&this.visibilityChoiceModel.selectedItem){const e=this.visibilityChoiceModel;const t=e.selectedItem===e.items[0];socialRequests.updateProfileVisibility(t).catch(e=>logger$5.error("Failed to updateProfileVisibility in SocialProfileEditController",e))}}sendData(){return Promise.all([this.updateProfileVisibility(),this.setPrivateSocialPlaylists(),this.setListeningTo()]).then(()=>{reloadUserProfileIfNeeded();publish(USER_PROFILE_WAS_EDITED)})}updateViewModel(e,t={}){const r=createSocialProfileEditor({isNameEditable:true});const i=createEditorParagraph();const n=createEmptyParagraph();const o=createParagraph({text:localize("FUSE.Social.Profile.ShareWith.Header"),shouldHideDivider:true,textStyle:"light",textSize:get(ParagraphViewModel,"TEXT_SIZE.EXTRA_SMALL")});const s=isSocialProfilePrivateSync();this.visibilityChoiceModel=createVisibilityChoiceModel({isPrivate:s});const a=[];const l=!e;a.push(createToggleSelectorItem({isToggled:l,titleText:localize("FUSE.Social.Profile.Edit.ListeningTo.Title"),name:"thetoggle"}));this.hideListeningToToggle=createToggleSelectorViewModel({items:a});const c=createParagraph({text:localize("FUSE.Social.Profile.Edit.ShowOnProfile"),shouldHideDivider:true,textStyle:"light",textSize:get(ParagraphViewModel,"TEXT_SIZE.EXTRA_SMALL")});const u=createParagraph({text:localize("FUSE.Social.Profile.Edit.ListeningTo.Description"),shouldHideDivider:true,textStyle:"light",textSize:get(ParagraphViewModel,"TEXT_SIZE.EXTRA_SMALL")});this.playlistsVisibilityEditor=createPlaylistsVisibilityEditor(t);const d=this.createOffboardingButton();const g=[r,i,o,this.visibilityChoiceModel];if(this.playlistsVisibilityEditor){g.push(createParagraph({text:localize("FUSE.Social.Profile.SharePlaylist.Header"),shouldHideDivider:true,textStyle:"light",textSize:get(ParagraphViewModel,"TEXT_SIZE.EXTRA_SMALL")}),createParagraph({text:localize("FUSE.Social.Profile.SharePlaylist.Subheader"),textStyle:"light",textSize:get(ParagraphViewModel,"TEXT_SIZE.EXTRA_SMALL")}),this.playlistsVisibilityEditor)}g.push(c,this.hideListeningToToggle,u,n,d,n);const h=createSocialOnboardingVerticalStack({isEditing:true,childViewModels:g,onEditProfileFinished:this.sendData.bind(this)});this.viewModel=h}}function decorateShelfWithSeeAll$1(e={},t){const{seeAllUrl:r}=t;let i;if(r){i=createContainerDetailLink({onSelect:()=>createPushSegueForURL(r,t)})}Object.assign(e,{containerDetailLink:i});return e}function createFollowRequestsLink(e){const onSelect=()=>createPushSegue({componentController:new FollowRequestController({owner:e,title:localize("FUSE.Social.Profile.FollowRequests")})});return createContainerDetailLink({onSelect:onSelect})}function createArtistPageLink(e=[],t){const r=e.length;let i;if(r>1){const t=getContentIdList(e)||[];const r=localize("FUSE.Social.ViewArtistsMusic.Title");i=()=>createPushSegue({componentController:new SeeAllController({contentIds:t,title:r})})}else if(r===1){const r=e[0].entityId;const n=get(t,["lockup","results",r],{});i=()=>createPushSegueForStoreContent(n)}return createContainerDetailLink({onSelect:i})}function createProfileButtonGrid(){const e=createGridItemButton({title:localize("FUSE.Social.FollowMoreFriends.Button"),onSelect:()=>createPresentationSegue({componentController:new FriendsProfileController({isEditing:true})})});addClickMetricsHandlerToItem(e,()=>({actionDetails:{title:"Find More Friends"}}));return createGridWithButtons([e])}const REFRESH_TTL$1=5*60*1e3;const BaseClass$d=mix(StorePageController).with(RefreshMixin,SocialProfileBadgingMixin);class SocialProfileController extends BaseClass$d{constructor({storePlatformDictionary:e={},shouldSocialOnboardUser:t=false}={}){super(...arguments);if(!this.url&&e){this.url=e.url}this.refreshTTL=REFRESH_TTL$1;this.shouldSocialOnboardUser=t;this.pendingRequestCount=get(Store,"account.userSocialProfile.pendingRequestsCount");initializeSocial()}createFriendRecommendationPopup(e={}){const t=get(e,"recommendedFriends");let r;if(t.length>0){r=this.createSocialCardsFromRecommendationData(t,e);const i=this.hasFriendUpsell(this.viewModel.childViewModels);const n=get(this.viewModel,"profile.followState");if(this.viewModel&&n===SocialProfile.FOLLOW_STATE.NOT_FOLLOWING&&!i&&r){this.viewModel.childViewModels=[r].concat(this.viewModel.childViewModels)}}}clearFriendRecommendationPopup(e){if(this.viewModel){const t=this.viewModel.childViewModels;if(this.isInlinePopup(t)){this.viewModel.childViewModels=removeItemFromParent(this.viewModel,e)}}}createSocialCardsFromRecommendationData(e=[],t={}){const r=get(t,"storePlatformData.lockup.results");const i=e.reduce((e,t)=>{const i=t.id;if(i&&r[i]){e.push(createSocialShelfItemWithFollowButton({storePlatformDictionary:r[i],onCloseButtonSelectionPerformed:e=>{this.viewModel.childViewModels=removeItemFromParent(this.viewModel,e);removeRecommendedFriend(i)}}))}return e},[]);let n;if(i.length>0){n=createShelf({sections:[createShelfSection({items:i,uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.SOCIAL_PERSON_CARD})],title:localize("FUSE.ForYou.Module.Friends.Recommended"),isFriendShelf:true})}return n}hasFriendUpsell(e=[]){const t=get(e,"[0].constructor.name");if(t==="InlinePopup"){return true}return get(e,"[0].isFriendShelf",false)}onFollowButtonSelectionPerformed(e){const t=get(this,"viewModel.profile.storePlatformDictionary",{});const r=t.id;recordFollowButtonClick(r);checkShouldSocialUpsellOnFollow(e,t);Promise.all([shouldSocial(),isSocialOnboarded()]).then(([e,t])=>{if(e&&t){getRecommendedFriends(r).then(e=>this.createFriendRecommendationPopup(e))}})}getURL(){let e;if(this.shouldSocialOnboardUser){e=onboardUserAndGetProfileURL().then(e=>{this.shouldSocialOnboardUser=false;this.url=e;return e})}else if(this.url){e=super.getURL()}return e}updateHeaderItem(e={}){this.headerItem.promotionalLayoutStyle=HeaderItem.PROMOTIONAL_LAYOUT_STYLE.PROFILE;const t=get(e,"avatarArtwork");const r=get(e,"name")||get(e,"nameForDisplay");const i=get(e,"handle");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD;this.headerItem.storePlatformDictionary=e;this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:t});this.headerItem.promotionalThumbnailArtwork=createArtwork({dictionary:t,treatment:Artwork.TREATMENT.CIRCLE});if(r){this.headerItem.title=r}if(i){this.headerItem.subtitle=`@${i}`}}didLoad(){if(!this.viewModel&&!this.isLoading){this.reloadPage()}}willUnload(){super.willUnload();unsubscribe(USER_PROFILE_WAS_EDITED,this.refreshWithDebounce);unsubscribe(USER_FOLLOWEES_DID_CHANGE,this.refreshWithDebounce);unsubscribe(USER_FOLLOWERS_DID_CHANGE,this.refreshWithDebounce)}loadPage(){return super.loadPage().then(()=>this.badgeViewModel(true))}willAppear(e){super.willAppear(e);this.considerLoadingPage();if(get(this,"viewModel.profile.followState")==="self"){updateFollowRequestCount().then(()=>{this.viewModel.profile.pendingRequestsCount=get(Store,"account.userSocialProfile.pendingRequestsCount",0)})}if(this.viewModel&&!this.isLoading){this.badgeViewModel()}}refreshPageContent(){return this.loadPage()}getMissingContentIds(e){const t=get(e,"socialData",[]);const r=[];const i=get(e,"relationship.socialProfileId");if(i){r.push(i)}t.forEach(e=>{e.children.every(e=>r.push(e.contentId))});return r}updateViewModel(e){return Promise.resolve(this.createViewModel(e)).then(t=>{this.appendPlayActivity(t,e);if(this.viewModel){this.replaceCurrentViewModel(t)}else{this.viewModel=t}})}replaceCurrentViewModel(e={}){const replaceViewModelAtIndex=(e=[],t,r)=>{const i=["playActivityFeatureName","onAccessoryButtonSelect","title","sections"];const n=i.reduce((e,r)=>{if(t[r]){e[r]=t[r]}return e},{});Object.assign(e[r],n)};const t=this.viewModel.childViewModels.length;const r=e.childViewModels.length;if(t!==r){this.viewModel=e}else{this.viewModel.profile=e.profile;this.viewModel.onFollowButtonSelectionPerformed=e.onFollowButtonSelectionPerformed;this.viewModel.followRequestsLink=e.followRequestsLink;this.viewModel.childViewModels.forEach((t,r)=>{const i=e.childViewModels[r]||{};replaceViewModelAtIndex(this.viewModel.childViewModels,i,r)})}}createPageMetrics(e){super.createPageMetrics(e);const{socialProfileId:t,followState:r}=get(e,"relationship",{});const{isPrivate:i=false,isVerified:n=false}=get(e,["storePlatformData","product","results",t],{});this.pageFields.pageType="Profile";this.pageFields.page=combineWithSeparator(this.pageFields.pageType,"0");delete this.pageFields.pageUrl;this.pageFields.pageDetails={followState:r,isPrivate:i,isVerified:n}}removeItemFromListeningTo(e){removeItemFromParent(this.viewModel,e)}createViewModel(e){const t=e.profile||e.relationship||{};const r=get(e,"socialData",[]);const i=get(e,"storePlatformData",{});const n=get(t,"socialProfileId");const o=get(i,["product","results",n])||get(i,["lockup","results",n],{});const s=createSocialProfileFromData(e);const a=get(e,"linkedEntities",[]);this.updateHeaderItem(o);const l=get(t,"followState");const c=get(i,"lockup.results");const u=r.reduce((e,r)=>{const i=r.children||[];const n=i.slice(0,MAX_SHELF_ITEMS)||[];let o;if(r.moduleType==="USER_PERSONAL_MIXES"){const e=get(PersonalMixesViewModel,"LAYOUT_STYLE.SHELF");o=createPersonalMixesFromLockups(n,c,{options:{title:getTitleForModuleType(r.moduleType),layoutStyle:e}})}else{const e=getTitleForModuleType(r.moduleType,l);let s;if(r.moduleType==="USER_PLAYLISTS"){s=true}o=createProfileShelfFromLockups(n,c,{itemOptions:{date:s},options:{title:e}});if(o&&r.moduleType==="USER_ENGAGEMENT"&&t.followState==="self"){addHideFromProfileContextToItem(o,this.removeItemFromListeningTo.bind(this));this.listeningToModule=o}if(o&&i.length>0&&i.length>MAX_SHELF_ITEMS){decorateShelfWithSeeAll$1(o,{seeAllUrl:get(r,"seeAllUrl"),contentIds:getContentIdList(i),title:getTitleForModuleType(r.moduleType)})}}if(o){e.push(o)}return e},[]);if(o.isPrivate&&(t.followState==="requested"||t.followState==="notFollowing")){const e=localize("FUSE.Social.AwaitingApproval.Description",{Name:o.name});u.push(createParagraph({text:e}))}const d={profile:s,childViewModels:u,onFollowButtonSelectionPerformed:this.onFollowButtonSelectionPerformed.bind(this)};if(t.followState==="self"){u.push(createProfileButtonGrid());if(o.isPrivate){d.followRequestsLink=createFollowRequestsLink(o)}subscribe(USER_PROFILE_WAS_EDITED,this.refreshWithDebounce);subscribe(USER_FOLLOWEES_DID_CHANGE,this.refreshWithDebounce);subscribe(USER_FOLLOWERS_DID_CHANGE,this.refreshWithDebounce)}if(a&&a.length>0){d.artistPageLink=createArtistPageLink(a,i);d.artistPageLinkTitle=localize("FUSE.Social.ViewArtistsMusic")}return createProfileVerticalStack(d)}}function getTitleForModuleType(e,t){const r={USER_PLAYLISTS:localize("FUSE.Social.Playlist"),HEAVY_ROTATION:localize("FUSE.Social.HeavyRotation"),USER_ENGAGEMENT:localize("FUSE.Social.ListeningTo"),USER_PERSONAL_MIXES:localize("FUSE.Social.PersonalMixes")};if(t==="self"){r.USER_FOLLOWEES=localize("FUSE.Social.MyProfile.Following");r.USER_FOLLOWERS=localize("FUSE.Social.MyProfile.Followers")}else{r.USER_FOLLOWEES=localize("FUSE.Social.Following");r.USER_FOLLOWERS=localize("FUSE.Social.Followers")}return r[e]}function addHideFromProfileContextToItem(e={},t){const r=get(e,"sections[0].items",[]);r.forEach(e=>{const r=get(e,"storePlatformDictionary.kind");const i=get(e,"storePlatformDictionary.id");const n=createContextAction({title:localize("FUSE.Social.HideFromProfile.Context.Title"),kind:ContextAction.KIND.HIDE_FROM_PROFILE,onSelect:()=>{const n=createAlertViewModel({alertStyle:AlertViewModel.ALERT_STYLE.ACTION_SHEET,message:localize("FUSE.Social.HideFromProfile.Context.Confirm.Message",{Kind:r})});const o=createAlertAction({alertActionStyle:AlertAction.ALERT_ACTION_STYLE.DESTRUCTIVE,title:localize("FUSE.Social.HideFromProfile.Context.Confirm.CTA"),onSelect:()=>{updateListeningToPreferences({ids:[i],actionType:"hide"});t.call(this,e)}});const s=createAlertAction({alertActionStyle:AlertAction.ALERT_ACTION_STYLE.CANCEL,title:localize("FUSE.Social.HideFromProfile.Context.Confirm.Cancel")});n.alertActions=[o,s];const a=createAlertComponentController({viewModel:n});return createPresentationSegue({componentController:a})}});e.contextActions=[n]});return e}function createNextButtonForOnboardingFlow({ControllerClass:e,onSelectCallbackPromise:t=(()=>Promise.resolve()),awaitPromiseBeforeLoadingNextPage:r=false,initData:i={}}){const n=createGridItemButton({title:e.titleCTA||localize("FUSE.Social.Onboarding.CTA.Continue"),subtitle:e.subtitleCTA,onSelect:()=>{const n=t();let o;if(r){o=n}const s=Object.assign({promiseToFullfillBeforeLoading:o},i);return createPushSegue({componentController:new e(s)})}});addClickMetricsHandlerToItem(n,()=>({actionDetails:{title:"Continue"}}));return n}function createSegueToSocialOnboarding(){return createPresentationSegue({componentController:new WelcomeProfileController})}function considerCreatingSocialOnboardingSegue(e=false,t){const r=!!Persistence.localStorage.getItem(StorageKeys.Device.LAST_TIME_SOCIAL_ONBOARDING_PRESENTED);const i=getCookieString().indexOf("disableSocialOnboarding")>-1;if(i||r&&!e){logger$5.log(`disableSocialOnboarding: ${i}\nhasSocialOnboardingBeenPresented: ${r}\nignorePreviousOnboardingPresentation: ${e}`);return Promise.resolve()}const n=t?Promise.resolve(t):getSubscriptionStatus();return Promise.all([n,canSocialOnboard()]).then(([e={},t])=>{if(!e.isSubscribed||!t){return}return createSegueToSocialOnboarding()})}function considerPresentingSocialOnboarding(e){return considerCreatingSocialOnboardingSegue(false,e).then(e=>{if(e){const updateSocialOnboardingPresentedStore=()=>{Persistence.localStorage.setItem(StorageKeys.Device.LAST_TIME_SOCIAL_ONBOARDING_PRESENTED,(new Date).toString())};return[e,updateSocialOnboardingPresentedStore]}return Promise.resolve()})}function createSegueToUserControllerAndSocialOnboardUser(){return createPushSegue({componentController:new SocialProfileController({shouldSocialOnboardUser:true})})}function createDoneButtonForOnboardingFlow({onSelect:e=(()=>{}),instantiatedFromUpsell:t=false}){const r=createGridItemButton({title:localize("FUSE.Social.Onboarding.GetNotifications.CTA"),onSelect:()=>{e();if(!t){return createSegueToUserControllerAndSocialOnboardUser()}return createNoopSegue()},shouldDismissPresentation:true});addClickMetricsHandlerToItem(r,()=>({actionDetails:{title:"Done"}}));return r}function considerPresentingContactsConsent(){const e=SocialContactsConsentController.getManager();if(e.isCurrentlyPresenting){return Promise.resolve([createNoopSegue()])}return Promise.all([isSocialOnboarded(),getUserProfile()]).then(([e,t])=>{if(!e||SocialContactsConsentController.hasSatisfiedConsentPrompt(t)){return Promise.resolve()}return[createPresentationSegue({componentController:new SocialContactsConsentController})]})}function createPlaylistSelectorItems(e={}){const t=[];const r=e.ids||[];const i=get(e,"storePlatformData.lockup.results");r.forEach(e=>{const r=get(i,[e,"sagaId"],"");const n=get(i,[e,"isPublic"],false);const o=new IdentifierSet;o.contentKind=IdentifierSet.CONTENT_KIND.PLAYLIST;o.cloudUniversalLibraryID=e;o.storeCloudID=r.toString();t.push(createOrderedPlaylistSelectorItem({identifierSet:o,isSelected:n,id:e}))});return t}function createPlaylistsVisibilityEditor(e={}){const t=createPlaylistSelectorItems(e);let r;if(t.length){r=createOrderedPlaylistSelector({items:t})}return r}function defaultItemCreator(e,t){return createShelfItem({storePlatformDictionary:t})}function otherVersionsItemCreator(e,t){const r={subtitle:getTrackCountCopy(get(t,"trackCount"))};return createShelfItem(Object.assign({storePlatformDictionary:t},r))}function topAlbumsByArtistItemCreator(e,t){const r={};const i=get(t,"releaseDate");const n=localizedYearStringFromReleaseDate(i);if(n){r.subtitle=n}return createShelfItem(Object.assign({storePlatformDictionary:t},r))}function audioExtrasItemCreator(e,t){const r={};const i=get(t,"kind");if(i==="radioStation"){r.subtitle=get(t,"itunesNotes.standard")}else{r.subtitle=get(t,"uploadingBrandName")}return createShelfItem(Object.assign({storePlatformDictionary:t},r))}function videoExtrasItemCreator(e,t){const r={};const i=get(t,"kind");if(i==="uploadedVideo"){r.subtitle=get(t,"uploadingArtistName")||get(t,"uploadingBrandName")}return createShelfItem(Object.assign({storePlatformDictionary:t},r))}function audioExtrasGridItemCreator({storePlatformDictionary:e}){const t={};const r=get(e,"kind");if(r==="uploadedAudio"){const t=get(e,"artistName");if(!t){e.artistName=get(e,"uploadingBrandName")}}return createGridItem(Object.assign({storePlatformDictionary:e},t))}function videoExtrasGridItemCreator({storePlatformDictionary:e}){const t={};const r=get(e,"kind");const i=get(e,"artistName");if(r==="uploadedVideo"&&!i){e.artistName=get(e,"uploadingArtistName")||get(e,"uploadingBrandName")}return createGridItem(Object.assign({storePlatformDictionary:e},t))}const UPSELL_CLOSED_KEY="UPSELL_CLOSED_KEY";const RELATED_SECTIONS={otherVersions:{title:"FUSE.Album.Headline.OtherVersions",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}},itemCreator:otherVersionsItemCreator},relatedVideos:{title:"FUSE.Album.Headline.RelatedVideos",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.FEATURED_MUSIC_VIDEO}}},audioExtras:{title:"FUSE.Album.Headline.AudioExtras",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}},itemCreator:audioExtrasItemCreator,seeAllGridItemCreator:audioExtrasGridItemCreator},videoExtras:{title:"FUSE.Album.Headline.VideoExtras",itemCreator:videoExtrasItemCreator,seeAllGridItemCreator:videoExtrasGridItemCreator},moreByThisProvider:{title:"FUSE.Product.MoreByProvider.CapitolCase",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}}},topAlbumsByArtist:{title:"FUSE.Product.MoreByArtist.CapitolCase",itemCreator:topAlbumsByArtistItemCreator},appearsOn:{title:"FUSE.Album.Headline.AppearsOn",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}}},featuredArtists:{title:"FUSE.Product.FeaturedArtists.CapitolCase"},listenersAlsoBoughtAlbums:{title:"FUSE.Product.YouMayAlsoLike.CapitolCase"}};function createDetailContentShelf(e=[],t,r,i){const n=get(RELATED_SECTIONS[i],"itemCreator",defaultItemCreator);const sectionIteratorCallback=()=>{const e=get(r,"sectionOptions.uniformCellType");const t={uniformCellType:e};return createShelfSection(t)};const shelfCallback=e=>{const t=get(r,"options.title");return createShelf(Object.assign(e,{title:t}))};return createShelfWithIterator(e,t,n,sectionIteratorCallback,shelfCallback)}function ContainerDetailMixin(e){const t=mix(e).with(RefreshMixin,StorePageMixin);const r=class extends t{constructor(e={}){super(...arguments);const t=get(e,this.storePlatformDictionaryKey,{});const r=this.viewModelStorePlatformDictionary;if(!this.id){this.id=t.id||r.id}if(!this.url){this.url=t.url||r.url}registerOnBagChange(updateUberSupportFlag)}fetchPageData(e,t){return e?super.fetchPageData(e,t):Promise.resolve({})}fetchAdditionalData(e){return e}getMissingContentIds(e){let t=[];const r=e.pageData;if(r){t=Object.keys(RELATED_SECTIONS).reduce((e,t)=>{const i=get(r,t,[]);if(i.length>0){const t=i.slice(0,MAX_SHELF_ITEMS);e.push(...t)}return e},[])}const{artistId:i,curatorId:n,socialProfileId:o}=this.viewModelStorePlatformDictionary;const s=i||n||o;if(s){t.push(s)}return t}updateViewModel(e){const t=get(e,"pageData.id");if(t){const r=this.getProductDataFromPageResponse(e,t);const i=get(r,"editorialArtwork.bannerUber");const n=this.lyricsSnippetData;if(n){this.viewModel.prominentItemIdentifier=n.trackID;this.viewModel.lyricsSnippetData=n}else{const e=this.selectedTrackId;if(e){this.viewModel.prominentItemIdentifier=e}}this.viewModel[this.storePlatformDictionaryKey]=r;this.viewModel.onActionPerformed=this.viewModelActionHandler.bind(this);if(i&&!this.hideUberArt){this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD;this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:i})}const o=r?.editorialVideo;if(o&&containsMotionDetailVideo(o)){this.headerItem.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(o),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(o)})}}this.appendPlayActivity(this.viewModel,e);return Promise.resolve()}loadLater(e){return Promise.all([super.fetchAdditionalData(e),this.fetchFriendsWhoListened(),getSubscriptionStatus()])}updateViewModelLater(e){const[t,r,i]=e;this.updateFooterModels(t,r,i);this.updateByLineLink(t)}refreshPageContent(){return this.loadPage()}get storePlatformDictionaryKey(){throw new Error("Subclasses must override storePlatformDictionaryKey getter")}get productType(){throw new Error("Subclasses must override productType getter")}get detailLinkKey(){throw new Error("Subclasses must override detailLinkKey getter")}get friendsWhoListenedShelfTitle(){throw new Error("Subclasses must override friendsWhoListenedShelfTitle getter")}getProductDataFromPageResponse(e,t){return get(e,["storePlatformData",this.productType,"results",t])}updateFooterModels(e,t,r){if(hasOptedOutOfSubscription()||restrictsMusicSubscription()){return}const i=[this.createFriendsWhoListenedShelf(t,r),...this.createRelatedContentShelves(e)].filter(e=>!!e);this.viewModel.footerViewModels=i}get viewModelStorePlatformDictionary(){return get(this,["viewModel",this.storePlatformDictionaryKey],{})}get selectedTrackId(){return this.getSelectTrackIdFromURL(this.url)}getSelectTrackIdFromURL(e){if(!e){return}return get(url.parse(e,true),"query.i")}get lyricsSnippetData(){return this.getLyricsSnippetData(this.url)}getLyricsSnippetData(e){if(!e){return}const t=url.parse(e,true);const r=t.pathname.match(/\/\w{2}\/lyrics\/([0-9]+)/);if(!r){return}return{trackID:r[1],startTime:get(t,"query.ts"),endTime:get(t,"query.te")}}viewModelActionHandler(e,t,r,i,n){const o=get(n,"target.kind")||this.viewModelStorePlatformDictionary.kind;const s=get(n,"target.id")||this.id;const a=get(n,"targetId");const l=metricsFieldsForContainerDetailAction(t,r,o,s,a);if(l){recordClickEvent(...clickMetricsForImpressions(e,i,l))}}fetchFriendsWhoListened(){return Promise.all([isSocialOnboarded(),shouldSocial()]).then(([e,t])=>{if(!e||!t){return Promise.resolve()}return socialRequests.getFriendsWhoListenedToContainer(this.id).catch(e=>logger$5.error("ContainerDetailMixin failed to fetch friends who listened",e))})}createRelatedContentShelves(e){const{artistName:t,curatorName:r}=this.viewModelStorePlatformDictionary;const i=get(e,"storePlatformData.lockup.results",{});const n=[];Object.keys(RELATED_SECTIONS).forEach(o=>{const s=get(e,["pageData",o],[]);if(s.length>0){const e=localize(get(RELATED_SECTIONS[o],"title"),{artistName:t,curatorName:r});const a=get(RELATED_SECTIONS[o],"shelfOptions");const l=this.createFooterShelf({contentIds:s,sectionKey:o,storePlatformData:i,title:e,shelfOptions:a});if(l){n.push(l)}}});return n}handleCloseButtonCalled(e){const t=new Date;Persistence.localStorage.setItem(UPSELL_CLOSED_KEY,t.toDateString());this.viewModel.footerViewModels=removeItemFromParent(this.viewModel,e)}createSocialUpsellInlinePopup(){const e=Persistence.localStorage.getItem(UPSELL_CLOSED_KEY);if(e){return}const t="FriendsStorePageCTA";const r=createInlinePopupButton({title:localize("FUSE.Social.Upsell.ForYou.CTA"),onSelect:createSegueToSocialOnboarding});addClickMetricsHandlerToItem(r,()=>({actionContext:t,actionDetails:{title:"Get Started"}}));const i={actionContext:t};return createInlinePopup({title:localize("FUSE.Social.Upsell.ForYou.Title"),message:localize("FUSE.Social.Upsell.ForYou.Body"),button:r,onCloseButtonSelectionPerformed:this.handleCloseButtonCalled.bind(this)},i)}createFriendsWhoListenedShelf(e,t){if(!t.isSubscribed){return}const r=e?.ids||[];const i=this.environment?.mediaPickerEnvironment;if(i){return}let n;if(canSocialOnboardSync()){n=this.createSocialUpsellInlinePopup()}else if(r.length){const t=this.friendsWhoListenedShelfTitle;n=this.createPersonShelf({contentIds:r,title:t,sectionKey:"inYourNetwork",storePlatformData:e?.storePlatformData?.lockup?.results||{},nextPageURL:e?.next})}return n}createPersonShelf(e={}){const{title:t,sectionKey:r,storePlatformData:i,nextPageURL:n,contentIds:o,maxShelfItems:s}=e;considerFetchingFollowStateForIds(o);return this.createFooterShelf({contentIds:o,sectionKey:r,storePlatformData:i,title:t,nextPageURL:n,onDidRequestNextPageURL:e=>considerFetchingFollowStateForIds(e),maxShelfItems:s,shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ARTIST}}})}createFooterShelf({contentIds:e,sectionKey:t,storePlatformData:r,title:i,nextPageURL:n,onDidRequestNextPageURL:o,maxShelfItems:s=MAX_SHELF_ITEMS,shelfOptions:a={}}={}){set(a,"options.title",i);const l=s===0?e:e.slice(0,s);const c=createDetailContentShelf(l,r,a,t);if(c){const r=Object.assign({},this.pageFields,{pageDetails:t});const s=Object.assign({},this.pageMetrics);if(l.lengthcreatePushSegue({componentController:new SeeAllController({contentIds:e,title:i,pageFields:r,pageMetrics:s,nextPageURL:n,onDidRequestNextPageURL:o,gridItemCreator:a})});c.containerDetailLink=createContainerDetailLink({onSelect:onSelect})}}return c}updateByLineLink(){const{artistId:e,curatorId:t,socialProfileId:r}=this.viewModelStorePlatformDictionary;const i=e||t||r;return Promise.all([fetchContent({ids:[String(i)]}),shouldSocial()]).then(([e={},t])=>{const n=e[i];if(n&&!n.isCompilation){if(!t&&r){return}this.viewModel[this.detailLinkKey]=createContainerDetailLink({onSelect:()=>createPushSegueForStoreContent(n)})}else{const t=get(e,[i,"url"]);if(t){this.viewModel[this.detailLinkKey]=createContainerDetailLink({onSelect:()=>createPushSegueForURL(t)})}}})}handleLoadingError(e){logger$5.error(e)}};return r}const fetchOffersForStorefront=()=>getBagValue("musicSubscriptionOffersForStorefront").then(fetchJSON).then((e={})=>e.offers).catch(e=>{logger$5.error("Failed to fetch musicSubscriptionOffersForStorefront",e);throw e});const identifierSetPropertiesForResourceIdentifier=e=>{const t=e.type;const r=e.id;switch(t){case MusicAPIResourceType.ALBUMS:return{contentKind:IdentifierSet.CONTENT_KIND.ALBUM,storeAdamID:r};case MusicAPIResourceType.LIBRARY_ALBUMS:return{contentKind:IdentifierSet.CONTENT_KIND.ALBUM,storeCloudAlbumID:r};case MusicAPIResourceType.LIBRARY_PLAYLISTS:return{contentKind:IdentifierSet.CONTENT_KIND.PLAYLIST,cloudUniversalLibraryID:r};case MusicAPIResourceType.MUSIC_MOVIES:return{contentKind:IdentifierSet.CONTENT_KIND.MOVIE,storeAdamID:r};case MusicAPIResourceType.MUSIC_VIDEOS:return{contentKind:IdentifierSet.CONTENT_KIND.SONG,storeAdamID:r};case MusicAPIResourceType.PLAYLISTS:return{contentKind:IdentifierSet.CONTENT_KIND.PLAYLIST,storeAdamID:r};case MusicAPIResourceType.SOCIAL_PROFILES:return{contentKind:IdentifierSet.CONTENT_KIND.SOCIAL_PROFILE,socialProfileID:r};case MusicAPIResourceType.SONGS:return{contentKind:IdentifierSet.CONTENT_KIND.SONG,storeAdamID:r};case MusicAPIResourceType.STATIONS:return{contentKind:IdentifierSet.CONTENT_KIND.RADIO_STATION,storeAdamID:r};case MusicAPIResourceType.TV_EPISODES:return{contentKind:IdentifierSet.CONTENT_KIND.TV_EPISODE,storeAdamID:r};case MusicAPIResourceType.TV_SHOWS:return{contentKind:IdentifierSet.CONTENT_KIND.TV_SHOW,storeAdamID:r};case MusicAPIResourceType.ARTISTS:return{contentKind:IdentifierSet.CONTENT_KIND.ARTIST,storeAdamID:r};case MusicAPIResourceType.UPLOADED_AUDIOS:return{contentKind:IdentifierSet.CONTENT_KIND.ARTIST_UPLOADED_AUDIO,storeAdamID:r};case MusicAPIResourceType.UPLOADED_VIDEOS:return{contentKind:IdentifierSet.CONTENT_KIND.ARTIST_UPLOADED_VIDEO,storeAdamID:r};default:logger$5.warn(`An IdentifierSet could not be created for a resource identifier of type "${t}" with id "${r}".`);return null}};function identifierSetForMusicAPIResourceIdentifier(e){const t=identifierSetPropertiesForResourceIdentifier(e);if(!t){return null}const r=get(e,"meta.catalogIds");if(r){t.catalogIds=r}return Object.assign(new IdentifierSet,t)}function parsePreviewResponse(e){const t=e.results.data?.[0];if(!t){return Promise.reject(new Error("Preview response missing resource identifier"))}const r=t.type;const i=t.id;const n=e.resources[r][i];if(!n){return Promise.reject(new Error(`Preview response missing marketingResource for ${i} and ${r}`))}const o=n.attributes?.offers[0];return o?.buyParams}function requestPreviewMarketingItem(){return getBagValue("countryCode").then(e=>{const t=new MusicAPIURL(`/v1/engagement/${e}/upsell/marketing-items`);t.queryString.addParameters({serviceType:requestPreviewMarketingItem.SERVICE_TYPE,placement:requestPreviewMarketingItem.PREVIEW_PLACEMENT});return t.string()}).then(e=>requestMusicAPIResource(e)).then(e=>parsePreviewResponse(e))}requestPreviewMarketingItem.SERVICE_TYPE="music";requestPreviewMarketingItem.PREVIEW_PLACEMENT="musicVoiceUpsell";function previewPurchaseSegueForPurchaseOptions(e){return getSubscriptionStatus().then(e=>{if(e.isSubscribed||e.rawResponseData?.music?.status==="Glide"||e.rawResponseData?.music?.isInGlidePreview){return Promise.reject(new Error("Unable to purchase a preview, the user is already a subscriber or in a preview."))}}).then(()=>requestPreviewMarketingItem()).then(t=>{if(!t){return Promise.reject(new Error("Missing buyParams for preview purchase."))}const r={buyParameters:t,shouldShowLoadingIndicator:false,shouldSuppressOnboarding:true,options:e};return Object.assign(new SubscriptionPurchaseSegue,r)})}function attemptPreviewPlaybackForOptions(e,t){const r=e.messageIdentifier==="play";if(!r){logger$5.log(`Will not attempt playback. Message identifier: ${e.messageIdentifier} is invalid.`);t(createNoopSegue());return}const i=e.parameterMap;if(!i.id||!i.type){logger$5.log("Will not attempt playback. Required id or type parameters missing.");t(createNoopSegue());return}fetchMediaAPIContentForIdentifier(i.id,i.type).then(e=>{const r=identifierSetForMusicAPIResourceIdentifier(e);const i=playbackIntentForIdentifierSet(r);const n=createNoopSegue({playbackIntent:i});t(n)}).catch(e=>{logger$5.error(`An error occurred attempting to fetch MediaAPI resource: ${e}.`);t(createNoopSegue())})}function siriAceRequestForRequestOptions(e={}){if(!e.shouldReplay){logger$5.log("[siriAceRequestForRequestOptions]: shouldReplay is false. Will not perform SiriAceRequest.");return}const t=new SiriAceRequest;Object.assign(t,e);if(!t.payloadyUserData){t.payloadUserData={appBundleId:"com.apple.Music",isAppleVoiceGdprHandoffRetry:true}}logger$5.log(`Sending SiriAceRequest for options: utterance: ${t.utterance},\n isVoiceTriggeredEnabled: ${t.isVoiceTriggerEnabled},\n isTextToSpeechEnabled: ${t.isTextToSpeechEnabled},\n isEyesFree: ${t.isEyesFree},\n inputOrigin: ${t.inputOrigin},\n interactionType: ${t.interactionType},\n payloadIdentifier: ${t.payloadIdentifier},\n payloadOptions-appBundleId: ${t.payloadUserData.appBundleId},\n payloadOptions-isAppleVoiceGdprHandoffRetry: ${t.payloadUserData.isAppleVoiceGdprHandoffRetry}`);t.send()}const SUBSCRIPTION_PURCHASE_DID_SUCCEED="SUBSCRIBER_PURCHASE_DID_SUCCEED";const SUBSCRIPTION_PURCHASE_DID_FAIL="SUBSCRIBER_PURCHASE_DID_FAIL";const shouldAttemptOnboardingSymbol=Symbol("shouldAttemptOnboarding");class SubscriptionPurchaseManager{constructor(){this.pendingSubscriptionPurchases=new Set;if(typeof SubscriptionPurchaseCoordinator!=="undefined"){SubscriptionPurchaseCoordinator.onSubscriptionPurchaseDidBegin=this.onSubscriptionPurchaseDidBegin.bind(this);SubscriptionPurchaseCoordinator.onSubscriptionPurchaseDidComplete=this.onSubscriptionPurchaseDidComplete.bind(this);this.onSubscriptionChangeBound=this.onSubscriptionChange.bind(this);registerOnSubscriptionChange(this.onSubscriptionChangeBound)}}onSubscriptionPurchaseDidBegin(e={}){this[shouldAttemptOnboardingSymbol]=false;this.pendingSubscriptionPurchases.add(e.identifier);logger$5.log(`${this.constructor.name} Subscription Purchase did begin`,e)}onSubscriptionPurchaseDidComplete(e={},t){logger$5.log(`${this.constructor.name} Purchase did complete`,e,"didCompletePurchase: ",e.didPurchaseSubscription);this.pendingSubscriptionPurchases.delete(e.identifier);if(!e.didPurchaseSubscription){publish(SUBSCRIPTION_PURCHASE_DID_FAIL);if(!e.segue?.shouldSuppressOnboarding){this[shouldAttemptOnboardingSymbol]=true}return}const r=e.segue?.shouldSuppressOnboarding||e.subscriptionStatus?.music?.status==="Glide";logger$5.log(`${this.constructor.name} Should supress onboarding: ${r}`);if(!r){this[shouldAttemptOnboardingSymbol]=false;presentOnboardingControllerIfRequired(t)}const i=e.segue?.options;if(i){siriAceRequestForRequestOptions(i)}const n=e.segue?.options?.marketingMessageIdentifier;if(n){attemptPreviewPlaybackForOptions(n,t)}publish(SUBSCRIPTION_PURCHASE_DID_SUCCEED)}onSubscriptionChange(e,t){logger$5.log(`${this.constructor.name} Subscription status changed.`);if(!this[shouldAttemptOnboardingSymbol]){logger$5.log(`${this.constructor.name} Should attempt onboarding flag is set to false. Will not attempt onboarding on subscription change.`);return}this[shouldAttemptOnboardingSymbol]=false;presentOnboardingControllerIfRequired(t);unregisterOnSubscriptionChange(this.onSubscriptionChangeBound)}get isMusicSubscriptionPurchaseInProgress(){return this.pendingSubscriptionPurchases.size>0}set shouldAttemptOnboarding(e){this[shouldAttemptOnboardingSymbol]=e}get shouldAttemptOnboarding(){return this[shouldAttemptOnboardingSymbol]}}var SubscriptionPurchaseManager$1=new SubscriptionPurchaseManager;function dynamicAMSUIURLForPlacement(e){return getBagValue("marketingItemDynamicUIUrl").then(t=>{if(t&&e){return`${t}&serviceType=music&placement=${e}`}})}dynamicAMSUIURLForPlacement.PLACEMENTS={ALBUM_PAGE_BANNER:"musicAlbumBanner",BROWSE_TAB_BANNER:"musicBrowseBanner",LAUNCH_UPSELL:"musicAppLaunch",MUSIC_LYRICS_SHARING_UPSELL:"musicLyricsSharingUpsell",MUSIC_PRE_BUY:"musicPreBuyFlow",MUSIC_SHARED_LISTEN_UPSELL:"musicSharedListenUpsell",PLAYBACK_UPSELL:"musicPlaybackUpsell",RADIO_TAB_BANNER:"musicRadioBanner",MUSIC_VOICE_UPSELL:"musicVoiceUpsell"};function dynamicAMSUISegueForURL(e,t={},r={}){const i=Object.assign({},t);const n=Object.assign({},r);return createStoreFlowSegue({url:e,userInfo:i,metricsOverlay:n})}dynamicAMSUISegueForURL.OPTION_KEYS={OFFER_HINT:"offerHints",SEED:"seed",MEDIAKIT_KIND:"mediaKitKind"};dynamicAMSUISegueForURL.OFFER_HINTS={CARRIER:"CARRIER",HOME_POD:"HOMEPOD",WIN_BACK:"WINBACK",RETAIL:"RETAIL",OTHER:"OTHER",VOICE:"VOICE"};function precedingMarketingMetricsForMarketingOffer(e){const t=get(e,"metrics");let r=null;if(t){r={[precedingMarketingMetricsForMarketingOffer.METRICS_KEY]:t}}return r}function onSelectHandlerForMarketingOffer(e){let t;const r=e?.url;if(e?.buyParams){if(SubscriptionPurchaseManager$1.isMusicSubscriptionPurchaseInProgress){logger$5.log(`Subscription purchase in progress. Ignoring purchase attempt for offer: "${JSON.stringify(e)}".`);return null}const t={buyParameters:e.buyParams,shouldShowLoadingIndicator:true,metricsOverlay:{app:"com.apple.Music",topic:DEFAULT_TOPIC,dsId:Store.account.uniqueIdentifier,pageContext:currentPageContext()}};return()=>Object.assign(new SubscriptionPurchaseSegue,t)}if(r){t=r}else{t="https://finance-app.itunes.apple.com/subscribe"}if(t){const r=precedingMarketingMetricsForMarketingOffer(e);return()=>dynamicAMSUISegueForURL(t,null,r)}logger$5.warn(`Marketing item offer URL is missing for marketing item with offer: "${JSON.stringify(e)}". Unable to handle commerce segue".`);return null}precedingMarketingMetricsForMarketingOffer.METRICS_KEY="precedingMarketing";const fetchIndividualOffer=()=>fetchOffersForStorefront().then(e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r.type==="Individual"){return r}}});const placementsForLoggedOutMessageTargetIdentifiers={browse_tab:dynamicAMSUIURLForPlacement.PLACEMENTS.BROWSE_TAB_BANNER,radio_tab:dynamicAMSUIURLForPlacement.PLACEMENTS.RADIO_TAB_BANNER,Album_Detail_Controller:dynamicAMSUIURLForPlacement.PLACEMENTS.ALBUM_PAGE_BANNER};const createApplicationMessage=(e,t)=>{const r="logged-out-user-individual-offer-promotion";const i=locWithIntroPricing("FUSE.UpsellBanner.Subscribe.Long",e);const n=locWithIntroPricing("FUSE.UpsellBanner.Subscribe.Short",e);const o="DEFAULT";const s="FINANCE";return new ApplicationMessage({identifier:r,contentPages:[{contentParameters:{text:i,compactText:n,style:o},actions:[{url:t,actionParameters:{actionType:s}}]}]})};const bannerApplicationMessageDescriptorsForLoggedOutUsers=()=>{const e=Promise.all([fetchIndividualOffer(),waitForLocInitialization()]);return e.then(([e])=>{const t=Object.entries(placementsForLoggedOutMessageTargetIdentifiers).map(([t,r])=>{const i=dynamicAMSUIURLForPlacement(r);return i.then(i=>{if(i){return{targetIdentifier:t,applicationMessage:createApplicationMessage(e,i)}}return Promise.reject(new Error(`Couldn't create URL for dynamic AMS UI placement "${r}" for logged out user.`))})});return Promise.all(t)})};let sharedApplicationMessageBannerSourceLoggedOutUser;class ApplicationMessageBannerSourceLoggedOutUser{constructor(){this.priorityMessageForTargetIdentifier={};this.callbacksForTargetIdentifier={};this.hasUpdatedMessageSinceLastSubscriptionStatusChange=false;this.boundDebouncedOnSubscriptionChange=debounce(this.onSubscriptionChange.bind(this),1e3);registerOnSubscriptionChange(this.boundDebouncedOnSubscriptionChange)}static get shared(){if(!sharedApplicationMessageBannerSourceLoggedOutUser){sharedApplicationMessageBannerSourceLoggedOutUser=new ApplicationMessageBannerSourceLoggedOutUser}return sharedApplicationMessageBannerSourceLoggedOutUser}registerTargetForCallback(e,t){if(typeof t!=="function"){return}if(!this.hasRegisteredCallbacks){this.updateMessagesIfNeeded()}let r=this.callbacksForTargetIdentifier[e];if(!r){r=new Set;this.callbacksForTargetIdentifier[e]=r}r.add(t);const i=this.priorityMessageForTargetIdentifier[e];if(i){t(i,e)}}unregisterTargetForCallback(e,t){const r=this.callbacksForTargetIdentifier[e];if(!r){return}r.delete(t);if(r.size===0){delete this.callbacksForTargetIdentifier[e]}}updateMessagesIfNeeded(){if(!this.hasUpdatedMessageSinceLastSubscriptionStatusChange){this.updateMessages()}}get hasRegisteredCallbacks(){return Object.keys(this.callbacksForTargetIdentifier)>0}updatePriorityMessageForTargetIdentifier(e,t){this.priorityMessageForTargetIdentifier[t]=e;this.notifyTargetsWithIdentifier(t,e)}onSubscriptionChange(){this.hasUpdatedMessageSinceLastSubscriptionStatusChange=false;if(this.hasRegisteredCallbacks){logger$5.log("Subscription status changed, updating banner messages for logged out user.");this.updateMessages()}}notifyTargetsWithIdentifier(e,t){const r=this.callbacksForTargetIdentifier[e];if(!r){return}r.forEach(r=>{r(t,e)})}updateMessages(){this.hasUpdatedMessageSinceLastSubscriptionStatusChange=true;getSubscriptionStatus().then(e=>{if(e.carrierBundlingStatus===SubscriptionStatusResponse.CARRIER_BUNDLING_STATUS.UNLINKED){logger$5.log('Carrier bundling status "unlinked", no banner application messages will be shown.');return Promise.resolve(null)}return bannerApplicationMessageDescriptorsForLoggedOutUsers()}).catch(e=>{logger$5.error("Failed to create banner application message for the logged out user",e);return null}).then(e=>{if(e){e.forEach(e=>{const t=e.applicationMessage;const r=e.targetIdentifier;this.updatePriorityMessageForTargetIdentifier(t,r)})}})}}let sharedApplicationMessageBannerManager;class ApplicationMessageBannerManager{constructor(){if(!canShowSubscriptionContent()){logger$5.log(`${this.constructor.name}: Cannot show subscription content, no banners will be shown.`)}this.applicationMessageTargetForTargetIndentifier={};this.priorityMessageForTargetIdentifier={};this.callbacksForTargetIdentifier={};this.boundUpdatePriorityMessageForTargetIdentifier=this.updatePriorityMessageForTargetIdentifier.bind(this);this.boundDebouncedOnAccountChanged=debounce(this.onAccountChanged.bind(this),1e3);registerOnAccountChange(this.boundDebouncedOnAccountChanged);registerOnCanShowSubscriptionContentChange(this.onCanShowSubscriptionContentChange.bind(this))}static get shared(){if(!sharedApplicationMessageBannerManager){sharedApplicationMessageBannerManager=new ApplicationMessageBannerManager}return sharedApplicationMessageBannerManager}registerTargetForCallback(e,t){if(typeof t!=="function"){return}let r=this.callbacksForTargetIdentifier[e];if(!r){r=new Set;this.callbacksForTargetIdentifier[e]=r}r.add(t);this.registerForMessagesForTargetIdentifier(e)}unregisterTargetForCallback(e,t){const r=this.callbacksForTargetIdentifier[e];if(!r){return}r.delete(t);if(r.size===0){this.unregisterForMessagesForTargetIdentifier(e)}}reportTargetMessageDidAppearWithIdentifier(e,t){const r=this.applicationMessageTargetForTargetIndentifier[e];if(r){r.reportMessageDidAppearWithIdentifier(t)}}reportTargetMessageDidDisappearWithIdentifier(e,t){const r=this.applicationMessageTargetForTargetIndentifier[e];if(r){r.reportMessageDidDisappearWithIdentifier(t)}}reportTargetMessageWithIdentifierActionPerformed(e,t,r){const i=this.applicationMessageTargetForTargetIndentifier[e];if(i){i.reportMessageWithIdentifierActionPerformed(t,r)}}static pageMetricsBannerFieldsForUpsellBanner(e){const t=get(e,"applicationMessage");if(!t){return null}const r=t.identifier;const i=e.style===UpsellBanner.STYLE.DEFAULT?"upsell":"error";return{id:r,copyType:i}}get canShowBanners(){return canShowSubscriptionContent()}registerForMessagesForTargetIdentifier(e){if(!this.canShowBanners){return}if(isUserSignedIn()){const t=this.createApplicationMessageTargetForTargetIdentifierIfNeeded(e);if(t.priorityMessage){this.updatePriorityMessageForTargetIdentifier(t.priorityMessage,e)}}else{ApplicationMessageBannerSourceLoggedOutUser.shared.registerTargetForCallback(e,this.boundUpdatePriorityMessageForTargetIdentifier)}}unregisterForMessagesForTargetIdentifier(e){if(isUserSignedIn()){this.destroyApplicationMessageTargetForTargetIdentifier(e)}else{ApplicationMessageBannerSourceLoggedOutUser.shared.unregisterTargetForCallback(e,this.boundUpdatePriorityMessageForTargetIdentifier)}}createApplicationMessageTargetForTargetIdentifierIfNeeded(e){const t=this.applicationMessageTargetForTargetIndentifier[e];if(t){return t}const r=new ApplicationMessageTarget({identifier:e});r.onPriorityMessageChanged=t=>{this.updatePriorityMessageForTargetIdentifier(t,e)};this.applicationMessageTargetForTargetIndentifier[e]=r;return r}destroyApplicationMessageTargetForTargetIdentifier(e){const t=this.applicationMessageTargetForTargetIndentifier[e];if(!t){return}t.unregister();delete this.applicationMessageTargetForTargetIndentifier[e]}updatePriorityMessageForTargetIdentifier(e,t){this.priorityMessageForTargetIdentifier[t]=e;this.notifyTargetsOfPriorityMessageChangeForTargetIdentifier(e,t)}notifyTargetsOfPriorityMessageChangeForTargetIdentifier(e,t){const r=this.callbacksForTargetIdentifier[t];if(!r){return}r.forEach(r=>{r(e,t)})}updateApplicationMessageSourcesForReason(e){logger$5.log(`${this.constructor.name}: Updating application message sources for reason "${e}".`);Object.keys(this.callbacksForTargetIdentifier).forEach(e=>{if(isUserSignedIn()){ApplicationMessageBannerSourceLoggedOutUser.shared.unregisterTargetForCallback(e,this.boundUpdatePriorityMessageForTargetIdentifier)}else{this.destroyApplicationMessageTargetForTargetIdentifier(e)}this.updatePriorityMessageForTargetIdentifier(null,e);this.registerForMessagesForTargetIdentifier(e)})}onAccountChanged(e,t){if(t===Store.ACCOUNT_CHANGE_REASON.UNIQUE_IDENTIFIER_CHANGED){this.updateApplicationMessageSourcesForReason("Account unique identifier changed")}}onCanShowSubscriptionContentChange(e){this.updateApplicationMessageSourcesForReason(`Can Show Subscription Content changed to '${e}'`)}}function createUpsellBanner(e){const t={onSelectionPerformed(e,t){const{regularText:r,compactText:i}=e;const n={actionDetails:{regularText:r,compactText:i},actionType:"navigate",location:[{locationPosition:0,locationType:"banner"}],targetType:"banner"};recordClickEvent(...clickMetricsForImpressions(e,t,n))}};return Object.assign(new UpsellBanner,t,e)}function onSelectHandlerForFinanceAction(e,t,r,i){if(e){return()=>{ApplicationMessageBannerManager.shared.reportTargetMessageWithIdentifierActionPerformed(r,t,e);return createFinanceSegue(i,{reason:`InAppMessage_${r}_${t}`})}}return()=>{const e={[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.OTHER};return dynamicAMSUISegueForURL(i,e)}}function onSelectHandlerForAction(e,t,r){if(!e){logger$5.error(`Missing action for application message with id: ${t.identifier}`);return null}const{url:i,identifier:n,actionParameters:o={}}=e;if(!o){logger$5.error(`Missing action parameters on action with id: ${n} for application message with id: ${t.identifier}`);return null}const s=o.actionType;switch(s){case"FINANCE":return onSelectHandlerForFinanceAction(n,t.identifier,r,i);default:logger$5.error(`Unsupported banner action type: ${s} for application message with id: ${t.identifier}`);return null}}function clickMetricsHandlerForAction(e,t){const{url:r,identifier:i}=e;if(i){return null}return()=>({url:r,targetId:t})}function createUpsellBannerFromApplicationMessageWithTargetIdentifier(e,t){if(!e){return null}const r=e.identifier;const i=get(e,"contentPages[0]");if(!i){logger$5.error(`Application message with id: ${r} missing message content`);return null}const n=i.contentParameters;if(!n){logger$5.error(`Application message with id: ${r} missing content parameters`);return null}const{compactText:o,text:s,style:a}=n;const l=get(i,"actions[0]");const c=onSelectHandlerForAction(l,e,t);if(!c){return null}let u=UpsellBanner.STYLE[a];if(!u){logger$5.warn(`Unsupported banner style: ${a} for application message with id: ${r}`);u=UpsellBanner.STYLE.DEFAULT}const d=u===UpsellBanner.STYLE.DEFAULT;const g=clickMetricsHandlerForAction(l,t);const h={regularText:s,compactText:o,style:u,showsAppleMusicLogo:d,onSelect:c,applicationMessage:e};if(!g){h.onSelectionPerformed=undefined}const f=createUpsellBanner(h);if(g){addClickMetricsHandlerToItem(f,g)}return f}const ApplicationMessageUpsellBannerControllerMixin=Mixin(e=>{const t=class extends e{get applicationMessageTargetIdentifier(){return this.messageTargetIdentifier}set applicationMessageTargetIdentifier(e){this.messageTargetIdentifier=e}get shouldWaitUntilNextControllerAppearanceToShowBanner(){return this.waitUntilNextControllerAppearanceToShowBanner}set shouldWaitUntilNextControllerAppearanceToShowBanner(e){this.waitUntilNextControllerAppearanceToShowBanner=e}setPageBannerMetrics(e){if(this.pageMetricsController){this.pageMetricsController.pageBannerMetrics=e}else{logger$5.warn(`${this.constructor.name} couldn't set page banner metrics, missing a pageMetricsController.`)}}didLoad(){super.didLoad();if(!this.shouldDisplayBanners){return}this.boundOnPriorityApplicationMessageChanged=this.onPriorityApplicationMessageChanged.bind(this);this.registerApplicationMessageBannerTarget(this.applicationMessageTargetIdentifier)}willAppear(e){super.willAppear(e);if(this.shouldDisplayBanners){this.updateUpsellBannerFromApplicationMessageIfNeeded(this.priorityApplicationMessage)}}didAppear(e){super.didAppear(e);this.isControllerVisible=true;if(!this.shouldDisplayBanners){return}const t=get(this.headerItem,"upsellBanner.applicationMessage.identifier");if(t){this.reportMessageAppearance(t)}}didDisappear(e,t){super.didDisappear(e,t);this.isControllerVisible=false;if(!this.shouldDisplayBanners){return}const r=get(this.headerItem,"upsellBanner.applicationMessage.identifier");if(r){this.reportMessageDisappearance(r)}}willUnload(){super.willUnload();if(this.shouldDisplayBanners){ApplicationMessageBannerManager.shared.unregisterTargetForCallback(this.applicationMessageTargetIdentifier,this.boundOnPriorityApplicationMessageChanged)}}onPriorityApplicationMessageChanged(e){this.priorityApplicationMessage=e;if(!e&&this.headerItem.upsellBanner){this.removeUpsellBanner()}else if(!this.shouldWaitUntilNextControllerAppearanceToShowBanner){this.updateUpsellBannerFromApplicationMessageIfNeeded(e)}}get shouldDisplayBanners(){return this.applicationMessageTargetIdentifier&&!get(this,"environment.mediaPickerEnvironment",false)}reportMessageAppearance(e){if(!this.isControllerVisible){return}ApplicationMessageBannerManager.shared.reportTargetMessageDidAppearWithIdentifier(this.applicationMessageTargetIdentifier,e);this.hasReportedMessageDisapperanceForPresentation=false}reportMessageDisappearance(e){if(this.hasReportedMessageDisapperanceForPresentation){return}ApplicationMessageBannerManager.shared.reportTargetMessageDidDisappearWithIdentifier(this.applicationMessageTargetIdentifier,e);this.hasReportedMessageDisapperanceForPresentation=true}registerApplicationMessageBannerTarget(e){ApplicationMessageBannerManager.shared.registerTargetForCallback(e,this.boundOnPriorityApplicationMessageChanged)}updateUpsellBannerFromApplicationMessageIfNeeded(e){if(!e||get(this.headerItem,"upsellBanner.applicationMessage.identifier")===e.identifier){return}const t=this.applicationMessageTargetIdentifier;const r=createUpsellBannerFromApplicationMessageWithTargetIdentifier(e,t);if(r){this.setUpsellBannerFromApplicationMessage(r,e)}}setUpsellBannerFromApplicationMessage(e,t){const r=get(this.headerItem,"upsellBanner.applicationMessage.identifier");if(r){this.reportMessageDisappearance(r)}this.headerItem.upsellBanner=e;this.setPageBannerMetrics(ApplicationMessageBannerManager.pageMetricsBannerFieldsForUpsellBanner(e));this.reportMessageAppearance(t.identifier);logger$5.log(`${this.constructor.name} set upsell banner from Application Message`,t.identifier)}removeUpsellBanner(){const e=get(this.headerItem,"upsellBanner.applicationMessage.identifier");this.headerItem.upsellBanner=undefined;this.setPageBannerMetrics(undefined);if(e){this.reportMessageDisappearance(e)}logger$5.log(`${this.constructor.name} removed upsell banner`,e)}};return t});const BaseClass$e=mix(AlbumDetailComponentController).with(ContainerDetailMixin,ApplicationMessageUpsellBannerControllerMixin);class AlbumDetailController extends BaseClass$e{constructor(...e){super(...e);if(!this.id&&!this.url){logger$5.error(`${this.constructor.name} did not receive either an id or a URL from the passed storePlatformDictionary. It cannot load tracks in this scenario or any underlying shelves. this.id: ${this.id} this.url ${this.url}`)}this.headerItem.promotionalLayoutStyle=HeaderItem.PROMOTIONAL_LAYOUT_STYLE.DEFAULT;this.applicationMessageTargetIdentifier="Album_Detail_Controller"}didLoad(){super.didLoad();this.reloadPage();subscribe(ONBOARD_COMPLETE,this.refreshWithDebounce)}willAppear(e){super.willAppear(e);this.considerLoadingPage()}willUnload(){super.willUnload();unsubscribe(ONBOARD_COMPLETE,this.refreshWithDebounce)}onShouldSetUpsellBanner(e){this.hideUberArt=true;super.onShouldSetUpsellBanner(e)}onShouldRemoveUpsellBanner(){this.hideUberArt=false;super.onShouldRemoveUpsellBanner()}setUpsellBannerFromApplicationMessage(e,t){this.hideUberArt=true;super.setUpsellBannerFromApplicationMessage(e,t)}removeUpsellBanner(){this.hideUberArt=false;super.removeUpsellBanner()}get storePlatformDictionaryKey(){return"albumStorePlatformDictionary"}get productType(){return"product-dv"}get detailLinkKey(){return"artistDetailLink"}get friendsWhoListenedShelfTitle(){return localize("FUSE.Social.Detail.Header")}}function errorViewModel(e,t){const r=userFacingMessageForError(e);const i=userFacingButtonTitleForError();const onAccessoryButtonSelect=()=>{t();return createNoopSegue()};return createMessageViewModel({message:r,accessoryButtonTitle:i,onAccessoryButtonSelect:onAccessoryButtonSelect})}const responseExpirationDateSymbol=Symbol("responseExpirationDate");const hasCachedPageResourceBeenInvalidatedSymbol=Symbol("hasCachedPageResourceBeenInvalidated");const shouldPrioritizeRequestSymbol=Symbol("shouldPrioritizeRequest");const performanceMetricsSymbol=Symbol("performanceMetrics");const RequestDrivenControllerMixin=Mixin(e=>{const t=class extends e{willDisappear(e){super.willDisappear(e);if(this.shouldAutomaticalyRefreshAfterResponseExpiration&&this.responseExpirationDate&&Date.now()>this.responseExpirationDate){this.refreshForReason("Response expired")}}loadViewModel(){return this.requestPageResourceAndCreateViewModel()}errorViewModel(e){return this.waitForLocalizationIfNeeded().then(()=>this.viewModelForError(e))}refreshViewModel(e){this.invalidateCachedPageResource();return this.requestPageResourceAndRefreshViewModel(e)}invalidateCachedPageResource(){this.hasCachedPageResourceBeenInvalidated=true}willRequestPageResource(){return Promise.resolve()}requestPageResource(){return Promise.reject(new Error(`${this.constructor.name} must override requestPageResource.`))}didReceivePageResourceResponse(e){return Promise.resolve(e)}updatePageMetricsForPageResponse(){throw new Error(`${this.constructor.name} must override updatePageMetricsForPageResponse.`)}viewModelForPageResponse(){throw new Error(`${this.constructor.name} must override viewModelForPageResponse.`)}refreshViewModelForPageResponse(){throw new Error(`${this.constructor.name} must override refreshViewModelForPageResponse.`)}viewModelForError(e){return errorViewModel(e,()=>{this.loadedViewModel=null;this.refreshForReason("Error retry button tapped")})}decorateViewModel(){return Promise.resolve()}get requiresLocalization(){return true}get pageMetricsController(){throw new Error(`${this.constructor.name} must override get pageMetricsController.`)}get shouldAutomaticalyRefreshAfterResponseExpiration(){return false}get responseExpirationDate(){return this[responseExpirationDateSymbol]}get performanceMetrics(){return this[performanceMetricsSymbol]}requestPageResourceAndCreateViewModel(){return this.performPageRequestSequence().then(e=>{const t=this.waitForLocalizationIfNeeded().then(()=>this.viewModelForPageResponse(e));t.then(e=>this.decorateViewModel(e));return t})}requestPageResourceAndRefreshViewModel(e){return this.performPageRequestSequence().then(t=>{const r=this.refreshViewModelForPageResponse(e,t);r.then(()=>{this.loadedViewModel.then(e=>{if(e){this.decorateViewModel(e)}})});return r})}performPageRequestSequence(){return this.willRequestPageResource().then(e=>this.requestPageResource(e,this.hasCachedPageResourceBeenInvalidated,this.shouldPrioritizeRequest).then(e=>{this.hasCachedPageResourceBeenInvalidated=false;this[responseExpirationDateSymbol]=e.expirationDate;this[performanceMetricsSymbol]=e.performanceMetrics;return this.didReceivePageResourceResponse(e?.body)}).then(t=>{this.updatePageMetricsForPageResponse(t,e,this.performanceMetrics);return t}))}waitForLocalizationIfNeeded(){return this.requiresLocalization?waitForLocInitialization():Promise.resolve()}get hasCachedPageResourceBeenInvalidated(){return this[hasCachedPageResourceBeenInvalidatedSymbol]}set hasCachedPageResourceBeenInvalidated(e){this[hasCachedPageResourceBeenInvalidatedSymbol]=e}get shouldPrioritizeRequest(){return this[shouldPrioritizeRequestSymbol]}set shouldPrioritizeRequest(e){this[shouldPrioritizeRequestSymbol]=e}};return t});const resourcesSymbol=Symbol("resources");const environmentSymbol=Symbol("environment");class MusicAPIResourceManager{get resources(){return this[resourcesSymbol]}addResources(e){if(!e){return}if(!this[resourcesSymbol]){this[resourcesSymbol]=e;return}Object.entries(e).forEach(([e,t])=>{if(!this[resourcesSymbol][e]){this[resourcesSymbol][e]=t;return}Object.assign(this[resourcesSymbol][e],t)})}resourceForResourceIdentifier(e){return get(this.resources,[e.type,e.id])}resourcesForResourceIdentifiers(e){return e.map(this.resourceForResourceIdentifier.bind(this))}itemsForResourceIdentifiers(e,t,r){const i=get(this,"environment.mediaPickerEnvironment");const n=[];if(!e){logger$5.warn(`${this.constructor.name} missing resourceIdentifiers from server response.`);return n}e.forEach(e=>{const o=MusicAPIResourceManager.isResourceRequiredForType(e.type);let s;if(o){s=this.resourceForResourceIdentifier(e);if(!s){logger$5.warn(`${this.constructor.name} missing resource ${e.type} ${e.id} for item.`);return}}if(!o&&typeof r!=="function"){logger$5.warn(`${this.constructor.name} missing creation function for item created without a resource, dropping "${e.type}" with id "${e.id}".`);return}if(i){const e=get(s,"attributes.playParams.kind");const t=MediaPicker.typeIdentifiersFromMediaPickerEnvironment(i);if(t&&!MediaPicker.shouldShowItemWithKind(e,t)){return}}if(!CapabilitiesController.shouldShowItemWithMediaAPIResource(s,e)){return}const a=o?t(e,s):r(e);if(!a){return}n.push(a)});return n}onEnvironmentChanged(e){this[environmentSymbol]=e}get environment(){return this[environmentSymbol]}static isResourceRequiredForType(e){switch(e){case MusicAPIResourceType.LIBRARY_ALBUMS:case MusicAPIResourceType.LIBRARY_PLAYLISTS:return false;default:return true}}}const resourceManagerSymbol=Symbol("resourceManager");const MusicAPIRequestDrivenControllerMixin=Mixin(e=>{const t=class extends e{URL(){return Promise.reject(new Error(`${this.constructor.name} must override URL.`))}get resourceManager(){let e=this[resourceManagerSymbol];if(!e){e=new MusicAPIResourceManager;this[resourceManagerSymbol]=e}return e}onEnvironmentChanged(e){super.onEnvironmentChanged(e);this.resourceManager.onEnvironmentChanged(e)}willRequestPageResource(){return this.URL()}requestPageResource(e,t,r=false){if(!e){return Promise.reject(new Error(`${this.constructor.name} couldn't request page resource, missing URL.`))}return requestMusicAPIResponse(e,{shouldIgnoreCache:t,shouldPrioritizeRequest:r})}didReceivePageResourceResponse(e){this.resourceManager.addResources(e?.resources);return Promise.resolve(e)}updatePageMetricsForPageResponse(e,t,r){this.pageMetricsController.xhrMetrics=r;const i=get(e,"meta.metrics");if(i){i["data.reco.dataSetId"]=i.reco_id;delete i.reco_id;this.pageMetricsController.pageMetrics=i}}};return t});class ContainerDetailURL extends MusicAPIURL{constructor(e,t=false){super(e);this.queryString.shouldIncludeFormatResourcesMap=true;this.queryString.shouldIncludeLanguage=true;if(t){this.queryString.addParameters({"omit[resource]":"autos","relate[songs]":"artists,albums","relate[music-videos]":"artists","art[url]":"f,c"})}else{this.queryString.addParameters({"omit[resource]":"autos",views:"appears-on,more-by-artist,related-videos,other-versions,you-might-also-like,audio-extras,video-extras","art[url]":"f,c"})}}}function createDirectPlaySegue(e){const t=e?.identifierSet;let r;if(t){r=playbackIntentForIdentifierSet(t)}return createNoopSegue({playbackIntent:r})}function createTVShowEpisodeDetailViewModel(e){return Object.assign(new TVShowEpisodeDetail,e)}function createTVShowEpisodeDetailItem(e){return Object.assign(new TVShowEpisodeDetailItem,e)}function createTVShowEpisodeDetailHeader(e,t){const r=createTVShowEpisodeDetailItem(e);t.item=r;return createTVShowEpisodeDetailViewModel(t)}function createMovieClipItem(e){const t=createDefaultOptions(e);return Object.assign(new MovieClipItem,t,e)}function getSongsForEpisode(e={},t){const r=get(e,"playlistIds",[]);let i;const n=e.kind;if(t&&r.length>0){const e=[];const o={};r.forEach(r=>{const i=t[r]||{};const{children:n,childrenIds:s=[]}=i;e.push(...s);Object.assign(o,n)});if(e.length>0){const t=n==="movie"?localize("FUSE.Music.Show.SongsInTitle"):localize("ATV.Music.Show.SongsInThisEpisode");i=createShelfFromLockups(e,o,{options:{title:t}})}}return i}function getAlbumsForMovie(e,t){const r=get(t,"xmerchAdamIds",[]);const i=localize("FUSE.Music.Show.FeaturedAlbums");const n=createShelfFromLockups(r,e,{options:{title:i}});return n}function getEpisodeHeader(e,t,r){let i;let n;const{showBrandId:o,description:s,name:a,artistName:l,episodeSeasonNumber:c,trackNumber:u,videoSubType:d}=e;const g=get(s,"standard")||get(s,"short");const h=t[o];if(h){const onSelect=()=>createPushSegueForURL(get(h,"url"));i=createContainerDetailLink({onSelect:onSelect})}if(get(e,"kind")!=="movie"){if(d==="episode"&&u){n=localize("FUSE.Music.Show.EpisodeHeadline",{seasonNum:convertNumberToLocaleString(c),trackNum:convertNumberToLocaleString(u)})}else{n=getHeadlineForEpisodeSubType(d)}}const f=createTVShowEpisodeDetailHeader({storePlatformDictionary:e,title:a,showName:l,episodeInformationItems:createBadgingItemsFromDictionary(e,r),description:g,headline:n},{showDetailLink:i});if(e.kind==="movie"){if(f&&f.item){f.item.showName=""}const t=get(e,"editorialArtwork.subscriptionCover");if(t){f.item.backgroundArtwork=createArtwork({cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,dictionary:t})}}return f}function getRelatedContent(e,t,r){let i;const n=get(e,"kind");if(n==="movie"){const t=get(e,"movieClips");const r=t.reduce((t,r)=>{const i=createMovieClipItem({movieClipDictionary:r,movieStorePlatformDictionary:e});if(i){const e=createShelfItem({movieClipItem:i});t.push(e)}return t},[]);if(r.length>0){i=createShelf({sections:[createShelfSection({items:r})],title:localize("FUSE.OC.Trailer.Subheader")})}}else{const e=get(t,"pageData.otherEpisodes")||[];const n=e.reduce((e,t)=>{const i=r[t];if(i){const t=get(i,"trackNumber");const r=get(i,"videoSubType");let n;if(r==="episode"&&t){n=localize("FUSE.Music.Show.Episode",{count:t})}else{n=getHeadlineForEpisodeSubType(r)}const o={storePlatformDictionary:i,headline:n,subtitle:""};const s=createShelfItem(o);e.push(s)}return e},[]);if(n.length>0){i=createShelf({sections:[createShelfSection({items:n})],title:"More from This Show"})}}return i}class EpisodeDetailController extends StorePageController{constructor({storePlatformDictionary:e={}}={}){super(...arguments);if(!this.url){this.url=e.url}if(!this.id){this.id=e.id}}didLoad(){super.didLoad();this.loadPage()}getMissingContentIds(e){const t=get(e,"pageData",{});const r=t.componentName==="movie_page"?"product-dv":"product";const i=[r,"results",t.id];const n=get(e,"storePlatformData",{});const o=get(n,i);const s=get(t,"musicArtists")||[];const a=get(t,"otherEpisodes")||[];const l=get(t,"xmerchAdamIds")||[];const c=t.id;const{collectionId:u,artistId:d}=o;return[u,d,...s,...a,...l,c]}createViewModel(e){this.headerItem.title="";const t=[];const r=get(e,"pageData",{});const i=r.componentName==="movie_page";const n=i?"product-dv":"product";const o=[n,"results",r.id];const s=get(e,"storePlatformData",{});const a=get(s,o);const l=get(s,["playlist-product","results"]);const c=get(s,"lockup.results",{});const u=createLanguageItemsFromDictionary(r);const d=i?createAccessibilityItemsFromDictionary(r):createAccessibilityItemsFromDictionary(a);const g=getEpisodeHeader(a,c,r);const h=getRelatedContent(a,e,c);const f=getSongsForEpisode(a,l);const p=getAlbumsForMovie(c,r);const m=createArtistsInEpisode(r,c);const S=createInformationItemsFromDictionary(a);const I=createCastItemsFromDictionary(a);if(g){t.push(g)}if(h){t.push(h)}if(f){t.push(f)}if(p){t.push(p)}if(I){t.push(I)}if(m){t.push(m)}if(S){t.push(S)}if(u){t.push(u)}if(d){t.push(d)}return createVerticalStack({childViewModels:t})}}function createTVShowPlayBarViewModel(e){return Object.assign(new TVShowPlayBarViewModel,e)}function createTVShowPlayBarItem(e){return Object.assign(new TVShowPlayBarItem,e)}const BaseClass$f=mix(StorePageController).with(HeaderItemMixin);class ShowDetailController extends BaseClass$f{constructor({storePlatformDictionary:e={}}={}){super(...arguments);if(!this.url){this.url=e.url}if(!this.id){this.id=e.id}}didLoad(){super.didLoad();this.loadPage()}updateHeaderItem(e={}){super.updateHeaderItem(e);if(!this.headerItem.promotionalBackgroundArtwork){let t=get(e,"editorialArtwork.subscriptionCover");if(!t){t=get(e,"editorialArtwork.bannerUber")}if(t){this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:t})}}this.headerItem.title="";this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}getMissingContentIds(e){const t=get(e,"pageData",{});const r=["product","results",t.id];const i=get(e,"storePlatformData",{});const n=get(i,r,{});const o=get(t,"musicArtists",[]);const{playlistIds:s=[],childrenIds:a=[],soundtracks:l=[]}=n;const c=findAvailableContentIds(e);return[...a,...s,...l,...c,...o]}createEpisodeItems(e,t,r){return e.reduce((e,i)=>{const n=getHeadlineForEpisodeSubType(i.videoSubType);const o=get(t,i.collectionId);const s=get(o,"seasonNumber");const a=get(i,"releaseDate");let l;let c;let u;if(a){l=new Date(a).toLocaleString(undefined,{month:"long",day:"numeric",year:"numeric",timeZone:"UTC"}).toUpperCase()}if(s){u=localize("FUSE.Music.Show.SeasonCount",{seasonNum:s})}switch(r){case TV_SHOW_BRAND_TYPE_LINEAR:if(i.videoSubType==="episode"){c=localize("FUSE.Music.Show.EpisodeHeadline",{seasonNum:s,trackNum:i.trackNumber})}else{c=`${u} · ${n}`}break;case TV_SHOW_BRAND_TYPE_NON_LINEAR:c=l;break;case TV_SHOW_BRAND_TYPE_STANDALONE:c=n;break;default:c=localize("FUSE.Music.Show.Video");break}if(i.videoSubType==="seasonbonus"){c=l}if(i.videoSubType!=="episodebonus"){e.push(createGridItem({storePlatformDictionary:i,headline:c,onSelect:()=>createPushSegueForStoreContent(i)}))}return e},[])}createTrailerShelfItems(e=[]){let t;const r=e.map(e=>{const t=getHeadlineForEpisodeSubType(e.videoSubType);const r=cloneDeep(e)||{};r.artistName=null;return createShelfItem({headline:t,storePlatformDictionary:r})});if(r.length>0){const e=[createShelfSection({items:r})];t=createShelf({sections:e,title:localize("FUSE.Music.Shows.TrailersShelf")})}return t}createPlayBarItem(e,t,r,i){let n;let o;let s;const getPlaybarTitle=e=>{const t=get(r,e.collectionId);const n=get(t,"seasonNumber");const o=get(e,"trackNumber");let s;if(i===TV_SHOW_BRAND_TYPE_NON_LINEAR){s=localize("FUSE.OC.Show.PlayNewestEpisode")}else if(o){s=localize("FUSE.Music.Show.PlaybarTitle",{seasonNum:n,trackNum:e.trackNumber})}return s};if(e&&t&&t.length>0){const r=t.findIndex(t=>{const r=e[t.id];return!r.hasBeenPlayed&&t.videoSubType==="episode"});if(r>0){o=t[r];n=getPlaybarTitle(o)}}if(t&&t.length>0&&!o){o=t[0];n=getPlaybarTitle(o)}if(o){s=createTVShowPlayBarViewModel({item:createTVShowPlayBarItem({storePlatformDictionary:o,title:n})})}return s}createViewModel(e){const t=[];const r=get(e,"pageData",{});const i=get(e,"storePlatformData",{});const n=get(i,"product.results");const o=get(i,"lockup.results");const s=get(n,r.id);const a=get(s,"itunesNotes.standard");const l=[];const c=[];const u=[];const d=get(s,"iTunesBrandType");const{childrenIds:g=[]}=s;if(s){this.updateHeaderItem(s)}g.forEach(e=>{const t=n[e];if(t){const e=t.childrenIds;u.push(...e);e.forEach(e=>{const r=t.children[e];if(r){if(r.videoSubType==="tvtrailer"||r.videoSubType==="seasonbonus"){c.push(r)}else{l.push(r)}}})}});return getBookKeeperForIds(u).then(i=>{let n;const u=this.createPlayBarItem(i,l,o,d);let g=this.createEpisodeItems(l,o,d);const h=this.createTrailerShelfItems(c,o);const f=createBadgingItemsFromDictionary(s);const p=createCastItemsFromDictionary(s);const m=createInformationItemsFromDictionary(s);const S=createLanguageItemsFromDictionary(s);const I=createArtistsInEpisode(r,o);const C=createAccessibilityItemsFromDictionary(s);const y=Object.assign({},e);y.storePlatformData=o;const P=get(r,"fcStructure.model");if(d===TV_SHOW_BRAND_TYPE_NON_LINEAR){g=g.reverse()}if(P){n=processFeaturedNode(P,y)}if(a){t.push(createParagraph({text:a,shouldHideDivider:true}))}if(f&&f.length>0){t.push(createBadgingViewModel({items:f}))}if(u){t.push(u)}if(g.length>0){const e=createGrid({sections:[createGridSection({items:g,title:localize("FUSE.Music.Show.ShelfLinearTitle")})]});t.push(e)}if(h){t.push(h)}if(n){t.push(...n.childViewModels)}if(I){t.push(I)}if(m){t.push(m)}if(p){t.push(p)}if(S){t.push(S)}if(C){t.push(C)}return createVerticalStack({childViewModels:t})})}}const VIEW_MODEL_LOADING_STATE={UNLOADED:"unloaded",LOADING:"loading",LOADED:"loaded",REFRESHING:"refreshing",ERROR:"error"};const viewModelLoaderErrorOriginalErrorSymbol=Symbol("viewModelLoaderErrorOriginalError");const viewModelLoaderErrorViewModelSymbol=Symbol("viewModelLoaderErrorViewModel");class ViewModelLoaderError extends Error{constructor(e,t){super(e.message);this[viewModelLoaderErrorOriginalErrorSymbol]=e;this[viewModelLoaderErrorViewModelSymbol]=t}static get name(){return"ViewModelLoaderError"}get originalError(){return this[viewModelLoaderErrorOriginalErrorSymbol]}get viewModel(){return this[viewModelLoaderErrorViewModelSymbol]}}const ViewModelLoaderMixin=Mixin(e=>{const t=Symbol("loadedViewModel");const r=Symbol("viewModelLoadingState");const i=class extends e{set loadedViewModel(e){this[t]=e;this.onLoadedViewModelChanged(e)}get loadedViewModel(){if(this.viewModelLoadingState===VIEW_MODEL_LOADING_STATE.LOADED||this.viewModelLoadingState===VIEW_MODEL_LOADING_STATE.REFRESHING){return Promise.resolve(this[t])}if(this.viewModelLoadingState===VIEW_MODEL_LOADING_STATE.LOADING){return this.loadViewModelPromise}this.viewModelLoadingState=VIEW_MODEL_LOADING_STATE.LOADING;this.loadViewModelPromise=Promise.resolve(this.loadViewModel()).then(e=>{this[t]=e;this.viewModelLoadingState=VIEW_MODEL_LOADING_STATE.LOADED;this.onViewModelLoaded(e);return e}).catch(e=>{logger$5.error(`${this.constructor.name} error loading view model`,e);return Promise.resolve(this.errorViewModel(e)).catch(e=>logger$5.error(`${this.constructor.name} error creating error view model`,e)).then(t=>{this.viewModelLoadingState=VIEW_MODEL_LOADING_STATE.ERROR;return Promise.reject(new ViewModelLoaderError(e,t))})});return this.loadViewModelPromise}loadViewModel(){return Promise.reject(new Error(`${this.constructor.name} must override loadViewModel`))}onViewModelLoaded(){}errorViewModel(){return Promise.reject(new Error(`${this.constructor.name} must override errorViewModel`))}onLoadedViewModelChanged(){logger$5.warn(`${this.constructor.name} onLoadedViewModelChanged called but not overriden by class.`)}onLoadedViewModelErrored(){logger$5.warn(`${this.constructor.name} onLoadedViewModelErrored called but not overriden by class.`)}refreshForReason(e){if(this.viewModelLoadingState===VIEW_MODEL_LOADING_STATE.LOADING||this.viewModelLoadingState===VIEW_MODEL_LOADING_STATE.REFRESHING){return}if(this.viewModelLoadingState===VIEW_MODEL_LOADING_STATE.UNLOADED){logger$5.warn(`${this.constructor.name} attempted to refresh for reason "${e}" before view model loaded.`);return}logger$5.log(`${this.constructor.name} refreshing view model with loading state "${this.viewModelLoadingState}" for reason "${e}".`);if(this.viewModelLoadingState===VIEW_MODEL_LOADING_STATE.ERROR){this.loadedViewModel.then(e=>{this.loadedViewModel=e}).catch(e=>this.onLoadedViewModelErrored(e)).catch(e=>logger$5.error(`${this.constructor.name} error onLoadedViewModelErrored`,e));return}this.viewModelLoadingState=VIEW_MODEL_LOADING_STATE.REFRESHING;const r=this[t];Promise.resolve(this.refreshViewModel(r)).then(()=>{this.viewModelLoadingState=VIEW_MODEL_LOADING_STATE.LOADED}).catch(e=>{this.viewModelLoadingState=VIEW_MODEL_LOADING_STATE.ERROR;logger$5.error(`${this.constructor.name} error refreshing view model`,e)})}refreshViewModel(){logger$5.warn(`${this.constructor.name} refreshViewModel must be implemented if the view model can be refreshed."`)}set viewModelLoadingState(e){this[r]=e}get viewModelLoadingState(){return this[r]}};return i});ViewModelLoaderMixin.VIEW_MODEL_LOADING_STATE=VIEW_MODEL_LOADING_STATE;const pageMetricsControllerSymbol=Symbol("pageMetricsController");const RequestDrivenComponentControllerMixin=Mixin(e=>{const t=mix(e).with(ViewModelLoaderMixin,RequestDrivenControllerMixin);const r=class extends t{constructor(...e){super(...e);this.pageMetricsController.onPageRequest()}didAppear(...e){super.didAppear(...e);this.pageMetricsController.didAppear()}willDisappear(...e){super.willDisappear(...e);this.pageMetricsController.willDisappear()}didDisappear(e,t){super.didDisappear(e,t);this.pageMetricsController.didDisappear(t)}reportImpressionsForApplicationWillResignActiveEvent(e){super.reportImpressionsForApplicationWillResignActiveEvent(e);this.pageMetricsController.reportImpressionsForApplicationWillResignActiveEvent(e)}get pageMetricsController(){let e=this[pageMetricsControllerSymbol];if(!e){e=new PageMetricsController;e.shouldRecordPerformanceMetrics=true;if(this.notifyWhenCurrentlyVisibleContentLoadingCompletes){e.notifyWhenOnScreenResourcesLoaded=this.notifyWhenCurrentlyVisibleContentLoadingCompletes.bind(this)}this[pageMetricsControllerSymbol]=e}return e}loadPage(){return this.loadedViewModel.then(e=>{this.viewModel=e;this.pageMetricsController.onPageViewModelSet();this.pageMetricsController.considerRecordingPageEvent()}).catch(e=>{if(e.viewModel){this.viewModel=e.viewModel}this.pageMetricsController.onPageError()})}set viewModel(e){super.viewModel=e}get viewModel(){return super.viewModel}onLoadedViewModelChanged(e){this.viewModel=e}onLoadedViewModelErrored(e){if(e.viewModel){this.viewModel=e.viewModel}}};return r});function sharingPropertiesForMusicAPIResource(e,t){let r;let i;const n=get(e,"attributes.offers");const o=get(e,"attributes.previews");const s=get(e,"attributes.url");if(n&&Array.isArray(n)){r=n.map(e=>e.type)}if(o&&Array.isArray(o)){const e=o.find(e=>e.url!==undefined);if(e){i=e.url}}return Object.assign({offerTypes:r,previewURL:i,url:s},t)}function constructPartialStorePlatformShareResult(e,t,r,i){const n=get(e,"offers",[]);const o={};const s=[];if(n&&Array.isArray(n)){n.forEach(e=>{const t=get(e,"type");if(t){s.push(t)}if(!o.previewURL){const t=get(e,"assets",[]);const r=t.find(e=>get(e,"preview.url"));o.previewURL=get(r,"preview.url")}})}o.url=e.postUrl||e.shortUrl||e.url||r;o.offerTypes=s||t;o.previewURL=o.previewURL||i;return o}function constructStorePlatformShareResult(e,t){const r=get(e,"kind");const i={};if(r==="socialProfile"){const r=get(e,"name");const n=localize("FUSE.UserSharing.Content.SocialProfile.Mail",{name:r});i.message=t.url;i.subject=n}else{i.url=t.url;i.previewURL=t.previewURL;if(t.offerTypes.length>0){i.offers=t.offerTypes}}return i}function shouldFetchContentForShareResult(e,t){if(!t.url||!t.offerTypes){return true}const r=get(e,"kind");if(r==="song"&&!t.previewURL){return true}return false}function fetchStorePlatformShareResult(e,t,r){const i=get(e,"id");const n=r?peekContent:fetchContent;return n({ids:[i]}).then(e=>{const r=get(e,[i],{});const n=constructPartialStorePlatformShareResult(r);if(!n.url){logger$5.log(`Unable to find URL for Share Result ${JSON.stringify(r)}, ${JSON.stringify(t)}.`);return null}return constructStorePlatformShareResult(r,n)})}function getMusicAPIResourceTypeFromSPKind(e){switch(e){case"album":return MusicAPIResourceType.ALBUMS;case"song":return MusicAPIResourceType.SONGS;case"musicVideo":return MusicAPIResourceType.MUSIC_VIDEOS;default:return null}}function fetchMediaAPIShareResult(e){const t=get(e,"id");const r=get(e,"kind");const i=getMusicAPIResourceTypeFromSPKind(r);if(!i){return Promise$1.resolve(null)}return getBagValue("countryCode").then(e=>{const r=new MusicAPIURL(`/v1/catalog/${e}/${i}`);r.queryString.addParameters({fields:"url,offers,previews",includeOnly:"attributes","filter[equivalents]":t});return r.string()}).then(e=>requestMusicAPIResource(e,{shouldImportResponse:false})).then(r=>{const n=get(r,`meta.filters.equivalents.${t}[0].id`)||t;const o=get(r,`resources.${i}.${n}`);const s=sharingPropertiesForMusicAPIResource(o,{});if(!s.url){logger$5.log(`Unable to find URL from Media API Share Result ${JSON.stringify(r)}, ${JSON.stringify(e)}, ${i}.`);return null}s.offers=s.offerTypes;return s})}function getStorePlatformShareResult(e,t,r,i){const n=constructPartialStorePlatformShareResult(e,t,r,i);if(!shouldFetchContentForShareResult(e,n)){const t=constructStorePlatformShareResult(e,n);return Promise$1.resolve(t)}logger$5.log(`Insufficient metadata from share request. Fetching content for additional metadata. ${JSON.stringify(e)}, ${t}, ${i}`);return fetchStorePlatformShareResult(e,n,true).then(t=>{if(!t){return fetchMediaAPIShareResult(e).then(t=>{if(!t){logger$5.log("Fetching using SP lookup request");return fetchStorePlatformShareResult(e,n,false)}return t})}return t})}function getSocialInvitationShareResult(){return waitForLocInitialization().then(()=>{const e=get(Store,"account.userSocialProfile.storePlatformDictionary.shortUrl")||localize("FUSE.UserSharing.SocialInvitation");return{subject:localize("FUSE.UserSharing.SocialInvitation.Subject"),message:e}})}function getClientGeneratedURLShareResult(e){const{identifier:t,type:r,containerId:i}=e;return getBagValue("countryCode").then((e="us")=>{const n="https://music.apple.com/";let o;if(r==="song"&&i){const r="album";o=`${n}${e}/${r}/${i}?i=${t}`}else{o=`${n}${e}/${r}/${t}`}return{url:o}})}function getShareResult(e,t,r,i,n,o){let s;switch(e){case ShareRequest.CONTENT_TYPES.STORE_PLATFORM:s=getStorePlatformShareResult(t,r,i,n);break;case ShareRequest.CONTENT_TYPES.SOCIAL_INVITATION:s=getSocialInvitationShareResult();break;case ShareRequest.CONTENT_TYPES.SHARE_URL_COMPONENTS:s=getClientGeneratedURLShareResult(o);break;default:s=Promise$1.reject(new Error(`Unknown content type ${e}`));break}return s}class ShareRequestHandler extends ShareRequest{perform(){const{contentType:e,contentDictionary:t={},offerTypes:r,url:i,previewURL:n,shareURLComponents:o}=this;return getShareResult(e,t,r,i,n,o).then(e=>{const r=JSON.stringify(e);const i=JSON.stringify(t);logger$5.log(`share response ${r} for content ${i}`);const n=Object.assign(new ShareResult,e);this.handleResponse(n)}).catch(e=>{logger$5.error("Unable to share content.",e);this.handleResponse(undefined,e)})}}const BaseClass$g=mix(ComponentController).with(MusicAPIRequestDrivenControllerMixin,MetricsMixin);function defaultGridStoreItemCreator(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping related content item with id "${e.id}".`);return null}const i={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),backgroundArtwork:createArtwork({dictionary:r.artwork,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP}),name:r.name,title:r.name};switch(e.type){case MusicAPIResourceType.ALBUMS:i.subtitle=r.artistName||r.title;i.headline=localizedMonthDayYearStringFromReleaseDate(r.releaseDate);break;case MusicAPIResourceType.PLAYLISTS:i.subtitle=r.curatorName||r.title;break;case MusicAPIResourceType.MUSIC_VIDEOS:i.subtitle=r.artistName||r.title;i.onSelect=null;break;case MusicAPIResourceType.SOCIAL_PROFILES:i.subtitle=`@${r.handle}`;break;case MusicAPIResourceType.ARTISTS:break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new GridItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}class MusicKitSeeAllController extends BaseClass$g{constructor({contentIds:e,nextPageURL:t,title:r,pageMetrics:i,pageFields:n,onDidRequestNextPageURL:o,gridItemCreator:s,pageResources:a,seeAllUniformCellType:l}={}){super(...arguments);this.contentIds=e;if(a){this.resourceManager.addResources(a)}if(r){this.headerItem.title=r;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}this.pageMetrics=i;this.pageFields=n;this.nextPageURL=t;this.gridItemCreator=s;this.uniformCellType=l===ShelfSection.UNIFORM_CELL_TYPE.RADIO_STATION?GridSection.UNIFORM_CELL_TYPE.FEATURED_RADIO_SHOW:null;if(o){this.onDidRequestNextPageURL=o}this.pageMetricsController.onPageRequest()}didLoad(){super.didLoad();if(this.nextPageURL){this.loadPage()}else if(this.contentIds){const e=this.createViewModel(this.contentIds);this.createPageFieldMetrics();this.viewModel=e}else{throw new Error("MusicKitSeeAllController: No nextPageURL or contentIds data provided")}}didAppear(){this.pageContext=currentPageContext();super.didAppear();this.pageMetricsController.didAppear()}willDisappear(...e){super.willDisappear(...e);this.pageMetricsController.willDisappear()}didDisappear(e,t){super.didDisappear(e,t);this.pageMetricsController.didDisappear(t)}createPageFieldMetrics(){if(this.pageFields){const e=combineWithSeparator(this.pageFields.pageType,"SeeAll");this.pageFields.pageType=e;this.pageFields.page=combineWithSeparator(e,this.pageFields.pageId);this.pageFields.pageUrl=this.nextPageURL}}createPageMetrics(e){this.createPageFieldMetrics();this.pageMetricsController.xhrMetrics=e.performanceMetrics}onDidRequestNextPageURL(){}onNeedsAdditionalChildViewModels(e){if(!e){return}this.viewModel.onNeedsAdditionalChildViewModels=null;this.requestPageResource(e,this.hasCachedPageResourceBeenInvalidated,this.shouldPrioritizeRequest).then(e=>{const t=e.body;this.resourceManager.addResources(t?.resources);const r=t?.data;const i=t?.next;let n;if(i){n=new MusicAPIURL(i);n.queryString.addParameters({limit:"25"})}this.onDidRequestNextPageURL(r);const o=this.gridItemCreator?this.gridItemCreator:defaultGridStoreItemCreator;const s=this.resourceManager.itemsForResourceIdentifiers(r,o.bind(this),null);const a=this.seeAllGrid?.sections[0];if(a&&s.length>0){a.appendItems(s);this.seeAllGrid.sections=[a]}if(n){return n.string()}}).then(e=>{if(e){this.viewModel.onNeedsAdditionalChildViewModels=this.onNeedsAdditionalChildViewModels.bind(this,e)}})}createViewModel(e,t){const r=this.gridItemCreator?this.gridItemCreator:defaultGridStoreItemCreator;let i;const n=this.resourceManager.itemsForResourceIdentifiers(e,r.bind(this),null);if(n.length>0){const e=[createGridSection({items:n,uniformCellType:this.uniformCellType})];this.seeAllGrid=createGrid({sections:e});const r=[this.seeAllGrid];i=createVerticalStack({childViewModels:r});if(t){i.onNeedsAdditionalChildViewModels=this.onNeedsAdditionalChildViewModels.bind(this,t)}}return i}loadPage(){const e=this.nextPageURL;return e.string().then(e=>this.requestPageResource(e,this.hasCachedPageResourceBeenInvalidated,this.shouldPrioritizeRequest)).then(e=>{const t=e.body;this.resourceManager.addResources(t?.resources);this.createPageMetrics(e);return t}).then(e=>{const t=e.next;const r=e.data;let i;if(this.contentIds){i=this.contentIds.concat(r)}else{i=r}if(t){const e=new MusicAPIURL(t);e.queryString.addParameters({limit:"25"});return e.string().then(e=>this.createViewModel(i,e))}return this.createViewModel(i)}).then(e=>{this.viewModel=e;this.pageMetricsController.onPageViewModelSet()}).then(()=>{this.considerRecordingPageEvent()}).catch(e=>{logger$5.error(e);const t=userFacingMessageForError(e);if(t){this.viewModel=createMessageViewModel({message:t})}})}}const BaseClass$h=mix(ComponentController).with(RequestDrivenComponentControllerMixin,MusicAPIRequestDrivenControllerMixin);class RecordLabelController extends BaseClass$h{constructor({url:e,id:t,mediaAPIDictionary:r={},storePlatformDictionary:i={}}={}){super(...arguments);this.mediaAPIDictionary=r;if(!this.url){this.url=r.attributes?.url??i.url??e}if(!this.id){this.id=r.id??i.id??t}this.loadPage()}didAppear(){this.pageMetricsController.pageContext=currentPageContext();super.didAppear()}updateHeaderItem(e={}){const t=e.attributes;let r;let i;if(t?.editorialArtwork){r=t?.editorialArtwork?.bannerUber||t?.editorialArtwork?.subscriptionCover;i=Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}if(!r){r=t?.artwork;i=Artwork.CROP_STYLE.BOUNDED_BOX}if(r){this.headerItem.promotionalBackgroundArtwork=createArtwork({dictionary:r,cropStyle:i})}this.headerItem.promotionalLayoutStyle=HeaderItem.PROMOTIONAL_LAYOUT_STYLE.DEFAULT;this.headerItem.storeMusicAPIDictionary=e;this.headerItem.title=t?.name;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}URL(){let e;if(this.mediaAPIDictionary?.href){e=this.getURLForHREF(this.mediaAPIDictionary.href)}else if(this.id){e=this.getURLForId(this.id)}else if(this.url){e=Promise.resolve(new MusicAPIURL(this.url))}else{throw new Error("getURL: No page URL or ID specified")}return e}updatePageMetricsForPageResponse(e,t,r){const i=t;const n=this.id;super.updatePageMetricsForPageResponse(e,t,r);this.pageMetricsController.pageFields={pageType:"RecordLabel",pageId:n,pageUrl:i}}viewModelForPageResponse(e){return this.createViewModel(e)}createViewModel(e){const t=e.data?.[0];this.resourceIdentifier=t;const r=this.resourceManager.resourceForResourceIdentifier(t);let i;if(r){this.updateHeaderItem(r);const e=r.attributes;i=e?.description?.standard||e?.description?.short}const n=createVerticalStack();const o=n.childViewModels||[];const s=r.views;const a=r.meta?.views.order;if(s&&a){a.forEach(e=>{const t=s[e];if(t?.data&&t.data.length>0){const r=t.data;const i={title:t.attributes?.title};if(e==="top-releases"){i.title=localize("FUSE.Label.Top.Releases");i.sectionOptions={height:ShelfSection.HEIGHT.REGULAR}}else if(e==="latest-releases"){i.title=localize("FUSE.Label.Latest.Releases");i.sectionOptions={uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.RADIO_STATION}}const n=this.createShelf(r,i,t);o.push(n)}})}else{throw new Error("createViewModel: No views data or views meta ordering data")}if(i){const e=localize("FUSE.Bio.About");o.push(createParagraph({title:e,text:i,shouldHideDivider:true}))}n.childViewModels=o;n.playActivityFeatureName="label_page";return n}createShelfItem(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping related content item with id "${e.id}".`);return null}const i={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),backgroundArtwork:createArtwork({dictionary:r.artwork,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),displayStyle:"small",name:r.name,title:r.name};switch(e.type){case MusicAPIResourceType.ALBUMS:i.subtitle=r.artistName||r.title;break;case MusicAPIResourceType.PLAYLISTS:i.subtitle=r.curatorName||r.title;break;case MusicAPIResourceType.MUSIC_VIDEOS:i.subtitle=r.artistName||r.title;break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new ShelfItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}createShelf(e,t,r){const i=this.resourceManager.itemsForResourceIdentifiers(e,this.createShelfItem.bind(this),null);if(i.length===0){return null}const n=t.sectionOptions?.uniformCellType;const o=t.sectionOptions?.height;const s=createShelfSection({items:i,uniformCellType:n,height:o});const a=t.title;const l={title:a,sections:[s]};const c=createShelf(l);if(c&&r.next){const t=n;this.decorateShelfWithSeeAll(c,{seeAllUrl:r.next,title:a,contentIds:e,seeAllUniformCellType:t})}return c}decorateShelfWithSeeAll(e={},t){const{seeAllUrl:r,title:i,contentIds:n,seeAllUniformCellType:o}=t;const s=this.resourceManager.resources;const a=new MusicAPIURL(r);const onSelect=()=>createPushSegue({componentController:new MusicKitSeeAllController({contentIds:n,nextPageURL:a,title:i,pageResources:s,seeAllUniformCellType:o})});const l=createContainerDetailLink({onSelect:onSelect});Object.assign(l,MetricsClickHandlers.containerDetailLink);Object.assign(e,{containerDetailLink:l});return e}getURLForHREF(e){const t=new MusicAPIURL(e);t.queryString.addParameters({views:"top-releases,latest-releases","limit[record-labels:top-releases]":"10","limit[record-labels:latest-releases]":"15","art[url]":"f,c"});return Promise.resolve(t.string())}getURLForId(){return getBagValue("countryCode").then(e=>new MusicAPIURL(`/v1/catalog/${e}/record-labels/${this.id}`)).then(e=>{e.queryString.addParameters({views:"top-releases,latest-releases","limit[record-labels:top-releases]":"10","limit[record-labels:latest-releases]":"15","art[url]":"f,c"});return Promise.resolve(e.string())})}}function onSelectHandlerForMusicAPIResourceIdentifier(e,t,r,i=false,n,o=false){const s=e.type;const a=get(t,"attributes");const l=get(a,"url");switch(s){case MusicAPIResourceType.ALBUMS:if(i){return()=>createDirectPlaySegue({identifierSet:n})}if(!o){return null}return()=>createPushSegueForURL(l);case MusicAPIResourceType.SONGS:if(i){return()=>createDirectPlaySegue({identifierSet:n})}return null;case MusicAPIResourceType.LIBRARY_ALBUMS:return null;case MusicAPIResourceType.LIBRARY_PLAYLISTS:return null;case MusicAPIResourceType.MUSIC_MOVIES:return()=>createPushSegue({componentController:new EpisodeDetailController({url:l})});case MusicAPIResourceType.PLAYLISTS:if(i){return()=>createDirectPlaySegue({identifierSet:n})}if(!o){return null}return()=>createPushSegueForURL(l);case MusicAPIResourceType.SOCIAL_PROFILES:return()=>createPushSegue({componentController:new SocialProfileController({url:l})});case MusicAPIResourceType.TV_EPISODES:return null;case MusicAPIResourceType.TV_SHOWS:return()=>createPushSegue({componentController:new ShowDetailController({url:l})});case MusicAPIResourceType.STATIONS:return()=>{const e=get(a,"playParams.kind")==="radioStation";if(a.mediaKind==="audio"){if(i){return()=>createDirectPlaySegue({identifierSet:n})}let t=a;if(e){t=Object.assign(a,get(a,"playParams"))}return createNowPlayingSegue({storePlatformDictionary:t})}};case MusicAPIResourceType.EDITORIAL_ITEMS:return()=>{const e=get(a,"link");const t=r||get(a,"name");if(get(e,"target")==="external"){return createRedirectSegue({url:l})}else if(get(e,"target")==="overlay"){return createStoreFlowSegue({url:l})}return createPushSegueForURL(l,{title:t})};case MusicAPIResourceType.APPLE_CURATORS:return()=>createPushSegue({componentController:new CuratorController({storePlatformDictionary:a})});case MusicAPIResourceType.CURATORS:return()=>createPushSegue({componentController:new CuratorController({storePlatformDictionary:a})});case MusicAPIResourceType.ARTISTS:return e=>createPushSegue({componentController:new ArtistController({id:e.mediaAPIDictionary?.id??e.storePlatformDictionary?.id??t.id,storePlatformDictionary:e.storePlatformDictionary??a})});case MusicAPIResourceType.ACTIVITIES:return()=>createPushSegue({componentController:new CuratorController$1({storePlatformDictionary:a})});case MusicAPIResourceType.MUSIC_VIDEOS:return()=>{const e=a.playParams?.kind==="musicVideo";let t=a;if(e){t=Object.assign(a,get(a,"playParams"))}return createNowPlayingSegue({storePlatformDictionary:t})};case MusicAPIResourceType.UPLOADED_AUDIOS:case MusicAPIResourceType.UPLOADED_VIDEOS:return null;case MusicAPIResourceType.RECORD_LABELS:return e=>createPushSegue({componentController:new RecordLabelController({mediaAPIDictionary:e.mediaAPIDictionary??t,storePlatformDictionary:e.storePlatformDictionary})});default:logger$5.warn(`onSelectHandlerForMusicAPIResourceIdentifier: unsupported resource type "${s}" with id "${t.id}".`);return null}}function otherVersionsItemCreator$1(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping related content item with id "${e.id}".`);return null}const i={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),backgroundArtwork:createArtwork({dictionary:r.artwork}),name:r.name,title:r.name,subtitle:getTrackCountCopy(r.trackCount)};return Object.assign(new ShelfItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}function topAlbumsByArtistItemCreator$1(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping related content item with id "${e.id}".`);return null}const i=r.releaseDate;const n=localizedYearStringFromReleaseDate(i);const o={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),backgroundArtwork:createArtwork({dictionary:r.artwork}),name:r.name,title:r.name,subtitle:n};return Object.assign(new ShelfItem,sharingPropertiesForMusicAPIResource(t,o),MetricsClickHandlers.baseItem)}function audioExtrasItemCreator$1(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping related content item with id "${e.id}".`);return null}const i={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),backgroundArtwork:createArtwork({dictionary:r.artwork,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),name:r.name,title:r.name};if(e.type===MusicAPIResourceType.STATIONS){i.subtitle=r.editorialNotes?.standard}else{i.subtitle=r.uploadingBrandName}return Object.assign(new ShelfItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}function videoExtrasItemCreator$1(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping related content item with id "${e.id}".`);return null}const i={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),name:r.name,title:r.name};if(e.type===MusicAPIResourceType.UPLOADED_VIDEOS){i.subtitle=r.uploadingArtistName||r.uploadingBrandName}const n=e.type===MusicAPIResourceType.TV_EPISODES?r.previewArtwork:r.artwork;i.backgroundArtwork=createArtwork({dictionary:n});return Object.assign(new ShelfItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}const UPSELL_CLOSED_KEY$1="UPSELL_CLOSED_KEY";const pageMetricsControllerSymbol$1=Symbol("pageMetricsController");const resourceManagerSymbol$1=Symbol("resourceManager");function MusicKitContainerDetailMixin(e){const t={"other-versions":{title:"FUSE.Album.Headline.OtherVersions",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}},itemCreator:otherVersionsItemCreator$1},"related-videos":{title:"FUSE.Album.Headline.RelatedVideos",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.FEATURED_MUSIC_VIDEO}}},"audio-extras":{title:"FUSE.Album.Headline.AudioExtras",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}},itemCreator:audioExtrasItemCreator$1,seeAllGridItemCreator:audioExtrasGridItemCreator},"video-extras":{title:"FUSE.Album.Headline.VideoExtras",itemCreator:videoExtrasItemCreator$1,seeAllGridItemCreator:videoExtrasGridItemCreator},"more-by-artist":{title:"FUSE.Product.MoreByProvider.CapitolCase",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}}},topAlbumsByArtist:{title:"FUSE.Product.MoreByArtist.CapitolCase",itemCreator:topAlbumsByArtistItemCreator$1},"appears-on":{title:"FUSE.Album.Headline.AppearsOn",shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ALBUM}}},"featured-artists":{title:"FUSE.Product.FeaturedArtists.CapitolCase"},listenersAlsoBoughtAlbums:{title:"FUSE.Product.YouMayAlsoLike.CapitolCase"}};const r=mix(e).with(RequestDrivenControllerMixin,MusicAPIRequestDrivenControllerMixin);const i=class extends r{constructor(e={}){super(...arguments);const t=e?.[this.storePlatformDictionaryKey]??{};const r=this.viewModelStoreMusicAPIDictionary;if(!this.id){this.id=t.id??r.id}if(!this.url){this.url=t.url??r.url}this.artistId=r.artistId;this.pageMetricsController.onPageRequest()}didLoad(...e){super.didLoad(e);this.loadPage()}didAppear(...e){this.pageMetricsController.pageContext=currentPageContext();super.didAppear(...e);this.pageMetricsController.didAppear()}willDisappear(...e){super.willDisappear(...e);this.pageMetricsController.willDisappear()}didDisappear(e,t){super.didDisappear(e,t);this.pageMetricsController.didDisappear(t)}get resourceManager(){let e=this[resourceManagerSymbol$1];if(!e){e=new MusicAPIResourceManager;this[resourceManagerSymbol$1]=e}return e}get storePlatformDictionaryKey(){throw new Error("Subclasses must override storePlatformDictionaryKey getter")}get containerDetailType(){throw new Error("Subclasses must override containerDetailType getter")}get friendsWhoListenedShelfTitle(){throw new Error("Subclasses must override friendsWhoListenedShelfTitle getter")}get pageType(){throw new Error("Subclasses must override pageType getter")}createPageMetrics(e={}){this.pageMetricsController.xhrMetrics=e.performanceMetrics;const t=e.body;const r=t?.data?.[0];const i=this.resourceManager.resourceForResourceIdentifier(r);const n=i?.attributes?.url??this.url;const o=r?.id??this.id;const s=this.pageType;const a={pageType:s,pageId:o,pageUrl:n};if(this.viewModel.hasSharedContent===true){a.sharedContent=true}this.pageMetricsController.pageFields=a}loadPage(){if(!this.loadingPage){this.loadingPage=true}else{return}return waitForLocInitialization().then(()=>this.getURL()).then(e=>{this.url=e;return this.noRetryRequest(e)}).catch(e=>{logger$5.error("Failed first attempt at loading album, will now load artist link before next retry",e);this.updateByLineLink();return this.noRetryRequest(this.url)}).catch(e=>{logger$5.error("Failed second attempt at loading album",e);const noOpFunction=()=>{};this.notifyWhenCurrentlyVisibleContentLoadingCompletes(noOpFunction);this.loadingPage=false}).then(e=>{if(!e){return Promise.reject(new Error(`MusicKitContainerDetailMixin.loadPage: Failed to get responseData. JS context: ${JSON.stringify(this)}`))}this.resourceManager.addResources(e?.body?.resources);this.createPageMetrics(e);return e}).then(e=>Promise.all([e,this.updateViewModel(e)])).then(([e])=>{this.pageMetricsController.onPageViewModelSet();this.pageMetricsController.onSecondaryDataRequest();this.loadLater(e).then((...e)=>{this.pageMetricsController.onSecondaryDataResponse();if(e.length===0){return}this.updateViewModelLater(...e);this.loadingPage=false}).catch(e=>logger$5.error("Failed to loadLater",e))}).then(()=>{this.pageMetricsController.considerRecordingPageEvent()}).catch(e=>this.handleLoadingError(e))}loadLater(e){return getSubscriptionStatus().then(t=>Promise.all([this.parseRelatedContentViews(e),this.fetchPersonalizedAndSocialResponse(e,t),Promise.resolve(t)]))}updateViewModelLater(e){const[t,r,i]=e;this.updateFooterModels(t,r,i)}get pageMetricsController(){let e=this[pageMetricsControllerSymbol$1];if(!e){e=new PageMetricsController;e.shouldRecordPerformanceMetrics=true;e.notifyWhenOnScreenResourcesLoaded=this.notifyWhenCurrentlyVisibleContentLoadingCompletes.bind(this);this[pageMetricsControllerSymbol$1]=e}return e}set pageMetricsController(e){this[pageMetricsControllerSymbol$1]=e}noRetryRequest(e){return requestMusicAPIResponse(e,{shouldIgnoreCache:this.hasCachedPageResourceBeenInvalidated,retryCount:0})}getURL(){let e;if(this.id){e=this.getURLForId().then(e=>{e.queryString.extend.add("offers");e.queryString.extend.add("editorialArtwork");e.queryString.extend.add("editorialVideo");e.queryString.extend.add("extendedAssetUrls");e.queryString.addParameters({include:"record-labels,artists,tracks","relate[songs]":"artists,albums","relate[music-videos]":"artists","fields[record-labels]":"name,url","meta[albums:tracks]":"popularity"});return e.string()})}else if(this.url){e=Promise.resolve(new ContainerDetailURL(this.url))}else{throw new Error("getURL: No page URL or ID specified")}return e}getURLForId(){let e=this.containerDetailType;const t=this.viewModelStoreMusicAPIDictionary;let r=false;if(t.kind==="song"){e=MusicAPIResourceType.SONGS;r=true}else if(t.kind==="musicVideo"){e=MusicAPIResourceType.MUSIC_VIDEOS;r=true}return getBagValue("countryCode").then(t=>new ContainerDetailURL(`/v1/catalog/${t}/${e}/${this.id}`,r))}getURLForPersonalizedAndSocialResponse(){const e=this.getURLForId().then(e=>{e.queryString.addParameters({"omit[resource:albums]":"attributes",views:"friends-who-listened"});return e.string()});return e}fetchPersonalizedAndSocialResponse(e,t){const r=e?.body?.data?.[0];if(!r){return Promise.reject(new Error("MusicKitContainerDetailMixin.fetchPersonalizedAndSocialResponse - Missing resource identifier for container detail pageResponse."))}const i=hasOptedOutOfSubscription()||restrictsMusicSubscription()||!t.isSubscribed;const n=r.type;if(n===MusicAPIResourceType.SONGS||n===MusicAPIResourceType.MUSIC_VIDEOS||i){return Promise.resolve([])}return this.getURLForPersonalizedAndSocialResponse().then(e=>this.requestPageResource(e,this.hasCachedPageResourceBeenInvalidated,this.shouldPrioritizeRequest)).then(e=>{const t=e.body?.data?.[0];const r=e.body?.resources;const i=r?.albums?.[t.id];if(i?.views){this.resourceManager.addResources(r);const e=i.views["friends-who-listened"];return Promise.resolve(e)}return Promise.resolve([])})}updateViewModel(e){const t=e?.body?.data?.[0];this.resourceIdentifier=t;if(!t){return Promise.reject(new Error("MusicKitContainerDetailMixin.updateViewModel: Missing resource identifier for container detail pageResponse."))}const r=t?.type;const i=t?.id;const n=this.resourceManager.resourceForResourceIdentifier(t);if(r&&i&&n){this.id=i;const e=this.selectedTrackId;if(e){this.viewModel.prominentItemIdentifier=e}this.viewModel[this.storePlatformDictionaryKey]=n;this.viewModel.onActionPerformed=this.viewModelActionHandler.bind(this);const t=n.attributes?.editorialVideo;if(t&&this.containsMotionDetailVideo(t)){if(this.headerItem.upsellBanner&&Device.model!=="iPad"){this.headerItem.upsellBanner=null}this.headerItem.videoDetailArtwork=createVideoArtwork({dictionary:t,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(t)})}const r=n.relationships;this.updateByLineLink(r?.artists);const o=r?.["record-labels"];if(o){this.updateRecordLabelDetailLinks(o)}}else{return Promise.reject(new Error("Missing type and id for container detail pageResponse."))}return Promise.resolve()}containsMotionDetailVideo(e){return e?.motionDetailSquare&&e?.motionDetailTall}parseRelatedContentViews(e){const t=e?.body?.data?.[0];if(!t){return Promise.reject(new Error("MusicKitContainerDetailMixin.parseRelatedContentViews: Missing resource identifier for container detail pageResponse."))}const r=t?.id;const i=this.resourceManager.resourceForResourceIdentifier(t);if(this.id===r&&i){const e=i.views;return Promise.resolve(e)}return Promise.reject(new Error("Missing Related Content views for container detail pageResponse"))}get selectedTrackId(){return this.getSelectTrackIdFromURL(this.url)}getSelectTrackIdFromURL(e){if(!e){return}return get(url.parse(e,true),"query.i")}updateFooterModels(e,t,r){if(hasOptedOutOfSubscription()||restrictsMusicSubscription()){return}if(!t&&!e){return}const i=[this.createFriendsWhoListenedShelf(t,r),...this.createRelatedContentShelves(e)].filter(e=>!!e);this.viewModel.footerViewModels=i}get viewModelStoreMusicAPIDictionary(){return this.viewModel?.[this.storePlatformDictionaryKey]??{}}get viewModelDataDictionary(){return this.resourceManager.resourceForResourceIdentifier(this.resourceIdentifier)}viewModelActionHandler(e,t,r,i,n){const o=get(n,"target.kind")??this.viewModelStoreMusicAPIDictionary.kind??this.viewModelStoreMusicAPIDictionary.type;const s=get(n,"target.id")??this.id;const a=get(n,"targetId");const l=metricsFieldsForContainerDetailAction(t,r,o,s,a,n?.actionUrl);if(l){recordClickEvent(...clickMetricsForImpressions(e,i,l))}}createRelatedContentShelves(e){if(!e){return}const r=[];Object.keys(t).forEach(i=>{const n=e[i];const o=n?.data||[];const s=n?.attributes;const a=n?.next;let l;if(a){l=new MusicAPIURL(a)}if(o.length>0){const e=s.title??localize(t[i].title,s.artistName??s.curatorName);const n=t[i].shelfOptions;const a=this.createFooterShelf({contentIds:o,sectionKey:i,attributes:s,title:e,nextPageURL:l,shelfOptions:n});if(a){r.push(a)}}});return r}handleCloseButtonCalled(e){const t=new Date;Persistence.localStorage.setItem(UPSELL_CLOSED_KEY$1,t.toDateString());this.viewModel.footerViewModels=removeItemFromParent(this.viewModel,e)}createSocialUpsellInlinePopup(){const e=Persistence.localStorage.getItem(UPSELL_CLOSED_KEY$1);if(e){return}const t="FriendsStorePageCTA";const r=createInlinePopupButton({title:localize("FUSE.Social.Upsell.ForYou.CTA"),onSelect:createSegueToSocialOnboarding});addClickMetricsHandlerToItem(r,()=>({actionContext:t,actionDetails:{title:"Get Started"}}));const i={actionContext:t};return createInlinePopup({title:localize("FUSE.Social.Upsell.ForYou.Title"),message:localize("FUSE.Social.Upsell.ForYou.Body"),button:r,onCloseButtonSelectionPerformed:this.handleCloseButtonCalled.bind(this)},i)}createFriendsWhoListenedShelf(e,t){if(!t.isSubscribed){return}const r=e?.data??[];const i=this.environment?.mediaPickerEnvironment;if(i){return}let n;if(canSocialOnboardSync()){n=this.createSocialUpsellInlinePopup()}else if(r.length){const t=this.friendsWhoListenedShelfTitle;let i;if(e.next){i=new MusicAPIURL(e.next)}n=this.createPersonShelf({title:t,sectionKey:"inYourNetwork",nextPageURL:i,contentIds:r})}return n}createPersonShelf(e={}){const{title:t,sectionKey:r,nextPageURL:i,contentIds:n,maxShelfItems:o}=e;considerFetchingFollowStateForIds(n.map(e=>e?.id));return this.createFooterShelf({contentIds:n,sectionKey:r,title:t,nextPageURL:i,onDidRequestNextPageURL:e=>considerFetchingFollowStateForIds(e.map(e=>e?.id)),maxShelfItems:o,shelfOptions:{sectionOptions:{uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.ARTIST}}})}createFooterShelf({contentIds:e,sectionKey:r,title:i,nextPageURL:n,onDidRequestNextPageURL:o,maxShelfItems:s=MAX_SHELF_ITEMS,shelfOptions:a={}}={}){set(a,"options.title",i);const l=s===0?e:e.slice(0,s);const c=this.createShelf(l,r,a);if(c){const s=Object.assign({},this.pageFields,{pageDetails:r});const a=Object.assign({},this.pageMetrics);if(l.lengthcreatePushSegue({componentController:new MusicKitSeeAllController({contentIds:e,nextPageURL:n,title:i,pageMetrics:a,pageFields:s,onDidRequestNextPageURL:o,gridItemCreator:l,pageResources:u})});c.containerDetailLink=createContainerDetailLink({onSelect:onSelect})}}return c}createShelf(e,r,i){const n=t[r]?.itemCreator||this.defaultShelfStoreItemCreator;const o=this.resourceManager.itemsForResourceIdentifiers(e,n.bind(this),this.defaultShelfLibraryItem.bind(this));if(o.length===0){return null}const s=i.sectionOptions?.uniformCellType;const a=createShelfSection({items:o,uniformCellType:s});const l=i.options?.title;const c={title:l,sections:[a]};return createShelf(c)}defaultShelfStoreItemCreator(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping related content item with id "${e.id}".`);return null}const i={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),backgroundArtwork:createArtwork({dictionary:r.artwork,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),name:r.name,title:r.name};switch(e.type){case MusicAPIResourceType.ALBUMS:i.subtitle=r.artistName??r.title;break;case MusicAPIResourceType.PLAYLISTS:i.subtitle=r.curatorName??r.title;break;case MusicAPIResourceType.MUSIC_VIDEOS:i.subtitle=r.artistName??r.title;i.onSelect=null;break;case MusicAPIResourceType.SOCIAL_PROFILES:break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new ShelfItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}defaultShelfLibraryItem(e){const t={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e)};switch(e.type){case MusicAPIResourceType.LIBRARY_ALBUMS:break;case MusicAPIResourceType.LIBRARY_PLAYLISTS:break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new ShelfItem,t,MetricsClickHandlers.baseItem)}updateByLineLink(e={}){const t=e?.data?.[0]??this.viewModelStoreMusicAPIDictionary.relationships?.artists;const r=t?.id??this.viewModelStoreMusicAPIDictionary.artistId??this.artistId;if(!r){return}if(restrictsMusicSubscription()){logger$5.log("Restricted music subscription. Skipping updateByLineLink for Library.");return}return fetchContent({ids:[String(r)]}).then((e={})=>{const t=e[r];if(t&&!t.isCompilation){this.viewModel[this.detailLinkKey]=createContainerDetailLink({onSelect:()=>createPushSegueForStoreContent(t)})}else{const t=get(e,[r,"url"]);if(t){this.viewModel[this.detailLinkKey]=createContainerDetailLink({onSelect:()=>createPushSegueForURL(t)})}}})}updateRecordLabelDetailLinks(e){const t=e.data;if(t?.length>0){const e=[];t.forEach(t=>{const r=new ContainerDetailLink;const i=this.resourceManager.resourceForResourceIdentifier(t);r.onSelect=onSelectHandlerForMusicAPIResourceIdentifier(t,i);r.identifier=t.id;e.push(r)});if(e.length>0){this.viewModel.recordLabelDetailLinks=e}}}handleLoadingError(e){logger$5.error(e);if(e.viewModel){this.viewModel=e.viewModel}this.pageMetricsController.onPageError()}};return i}const BaseClass$i=mix(AlbumDetailComponentController).with(MusicKitContainerDetailMixin,ApplicationMessageUpsellBannerControllerMixin);class MusicKitAlbumDetailController extends BaseClass$i{constructor(...e){super(...e);if(!this.id&&!this.url){logger$5.error(`${this.constructor.name} did not receive either an id or a URL from the passed storePlatformDictionary. It cannot load tracks in this scenario or any underlying shelves. this.id: ${this.id} this.url ${this.url}`)}else{this.headerItem.promotionalLayoutStyle=HeaderItem.PROMOTIONAL_LAYOUT_STYLE.DEFAULT;this.applicationMessageTargetIdentifier="Album_Detail_Controller"}}didLoad(){super.didLoad();subscribe(ONBOARD_COMPLETE,this.refreshWithDebounce)}willUnload(){super.willUnload();unsubscribe(ONBOARD_COMPLETE,this.refreshWithDebounce)}get storePlatformDictionaryKey(){return"albumStorePlatformDictionary"}get containerDetailType(){return"albums"}get detailLinkKey(){return"artistDetailLink"}get friendsWhoListenedShelfTitle(){return localize("FUSE.Social.Detail.Header")}get pageType(){return"Album"}onShouldSetUpsellBanner(e){this.hideUberArt=true;super.onShouldSetUpsellBanner(e)}onShouldRemoveUpsellBanner(){this.hideUberArt=false;super.onShouldRemoveUpsellBanner()}setUpsellBannerFromApplicationMessage(e,t){this.hideUberArt=true;super.setUpsellBannerFromApplicationMessage(e,t)}removeUpsellBanner(){this.hideUberArt=false;super.removeUpsellBanner()}}function createPlaylistDetailEntry(e){return Object.assign(new PlaylistDetailEntry,e)}const BaseClass$j=mix(PlaylistDetailComponentController).with(ContainerDetailMixin,ApplicationMessageUpsellBannerControllerMixin);class PlaylistDetailController extends BaseClass$j{constructor(...e){super(...e);if(!this.isPlaylistCreationFlow){const e=get(this.viewModelStorePlatformDictionary,"decorations[0]")==="trackBadges";if(e||!this.url){const e=this.getViewPlaylistURLForId(this.id);if(e){this.url=e}}if(!this.id&&!this.url){logger$5.error(`${this.constructor.name} did not receive either an id or a URL from the passed storePlatformDictionary. It cannot load tracks in this scenario or any underlying shelves. this.id: ${this.id} this.url ${this.url}`)}}this.applicationMessageTargetIdentifier="Playlist_Detail_Controller"}didLoad(){super.didLoad();if(!this.isPlaylistCreationFlow){this.reloadPage();subscribe(ONBOARD_COMPLETE,this.refreshWithDebounce)}else{this.pageFields={pageType:"Playlist",pageId:"NewPlaylist"};this.viewModel.onActionPerformed=this.viewModelActionHandler.bind(this)}}willAppear(e){super.willAppear(e);if(!this.isPlaylistCreationFlow){this.considerLoadingPage()}}willUnload(){super.willUnload();if(!this.isPlaylistCreationFlow){unsubscribe(ONBOARD_COMPLETE,this.refreshWithDebounce)}}get storePlatformDictionaryKey(){return"playlistStorePlatformDictionary"}get productType(){return"playlist-product"}get detailLinkKey(){return"curatorDetailLink"}get friendsWhoListenedShelfTitle(){return localize("FUSE.Social.Detail.Playlist.Header")}getProductDataFromPageResponse(e,t){const r=get(e,"storePlatformData");return get(r,["chart-playlist-product","results",t])||get(r,[this.productType,"results",t])}updateFooterModels(e,t,r,i){if(hasOptedOutOfSubscription()||restrictsMusicSubscription()){return}const n=[this.createFriendsMixShelf(e,i),this.createFriendsWhoListenedShelf(t,i),this.createAddedThisPlaylistShelf(r,i),...this.createRelatedContentShelves(e)].filter(e=>!!e);this.viewModel.footerViewModels=n}viewModelActionHandler(e,t,r,i,n){const o=this.isPlaylistCreationFlow;let s=get(n,"target.kind")||this.viewModelStorePlatformDictionary.kind;if(o){s="playlist"}const a=get(n,"targetId")||get(n,"target.id")||this.id;const l=metricsFieldsForPlaylistDetailAction(t,r,s,a,o);recordClickEvent(...clickMetricsForImpressions(e,i,l))}updateViewModel(e){return super.updateViewModel(e).then(()=>this.updateEntries(e))}loadLater(e){return Promise.all([super.loadLater(e),this.fetchFriendsWhoAddedPlaylist(e),this.fetchFriendsMixDataForDeepLink(e)])}updateViewModelLater(e){const[t,r,i]=e;const[n,o,s]=t;const a=get(i,"pageData.friendsSwoosh")?i:n;this.updateFooterModels(a,o,r,s);this.updateByLineLink();this.updateEntries(i)}get isPlaylistCreationFlow(){return get(this,"viewModel.isPlaylistCreationFlow")}getViewPlaylistURLForId(e){if(!e){return}const t=getSocialBagSync();const r=get(t,"viewPlaylist");if(!r){return}return constructURL(r,{params:{v:1,id:e}})}fetchFriendsWhoAddedPlaylist(e={}){const t=get(e,"pageData.id");const r=get(e,"storePlatformData.playlist-product.results",{});const i=r[t]||{};return Promise.all([isSocialOnboarded(),shouldSocial(),getUserProfile()]).then(([e,t,r])=>{if(!e||!t||i.socialProfileId!==r.socialProfileId){return Promise.resolve()}return socialRequests.getFriendsWhoAddedPlaylist(this.id).catch(e=>logger$5.error("PlaylistDetailController failed to fetch friends who added playlist.",e))})}fetchFriendsMixDataForDeepLink(e={}){const t=get(e,"pageData.id");const r=get(e,"storePlatformData.playlist-product.results",{});const i=r[t]||{};const n=get(i,"decorations[0]");if(n!=="trackBadges"){return Promise.resolve()}const o=get(e,"pageData.badgingMap");if(o){return Promise.resolve(e)}return Promise.all([isSocialOnboarded(),shouldSocial()]).then(([e,r])=>{const i=this.getViewPlaylistURLForId(t);if(!e||!r||!i){return Promise.resolve()}return fetchJSONWithStorePlatformData(i,{getIdsMissingStorePlatformData:e=>Object.keys(get(e,"pageData.badgingMap",{}))}).catch(e=>logger$5.error("PlaylistDetailController failed to fetch friends-playist badging content data.",e))})}createFriendsMixShelf(e,t){if(!t.isSubscribed){return}const r=get(e,"pageData.friendsSwoosh",[]);if(r.length===0){return}const i=get(e,"storePlatformData.lockup.results",{});return this.createPersonShelf({contentIds:r,storePlatformData:i,title:localize("FUSE.Social.Detail.FriendsWhoContributed.Header"),sectionKey:"FriendsWhoContributed",maxShelfItems:0})}createAddedThisPlaylistShelf(e,t){if(!t.isSubscribed){return}const r=get(e,"ids",[]);if(r.length===0){return}return this.createPersonShelf({contentIds:r,title:localize("FUSE.Social.Detail.AddedThisPlaylist.Header"),sectionKey:"addedThisPlaylist",storePlatformData:get(e,"storePlatformData.lockup.results",{}),nextPageURL:get(e,"next")})}updateEntries(e){if(!e){return}const t=this.viewModelStorePlatformDictionary;const r=get(t,"decorations[0]")==="trackBadges";if(!r){return}const i=get(t,"children",{});const n=get(t,"childrenIds",[]);const o=get(e,"pageData.badgingMap",{});const s=get(e,"storePlatformData.lockup.results",{});const a=[];n.forEach(e=>{const t=o[e]||[];if(t.length>0){const r=s[t[0]];const n=createSocialProfile({storePlatformDictionary:r});const o=createPlaylistDetailEntry({storePlatformDictionary:i[e],accessorySocialProfiles:[n]});a.push(o)}});this.viewModel.entries=a}}function createMusicViewModel(e){return Object.assign(new MusicVideoViewModel,e)}function createMusicVideoItem(e){return Object.assign(new MusicVideoItem,e)}function createMusicVideoHeader(e,t){const r=createMusicVideoItem(e);t.item=r;return createMusicViewModel(t)}class MusicVideoController extends StorePageController{constructor({storePlatformDictionary:e={}}={}){super(...arguments);if(!this.url){this.url=e.url}if(!this.id){this.id=e.id}this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}didLoad(){super.didLoad();this.loadPage()}getMissingContentIds(e){const t=get(e,"pageData",{});const r=["product-dv","results",t.id];const i=get(e,"storePlatformData",{});const n=get(i,r);const o=n.artistId;const{moreMusicVideosByArtist:s=[],moreMusicVideosInGenre:a=[]}=t;const l=[...s,...a,o];return l}createViewModel(e){const t=[];const r=get(e,"pageData",{});const i=["product-dv","results",r.id];const n=get(e,"storePlatformData",{});const o=get(n,i);const s=get(o,"itunesNotes.standard");const a=o.artistName;const l=o.artistId;const{moreMusicVideosByArtist:c=[],moreMusicVideosInGenre:u=[]}=r;const d=[localize("FUSE.Product.MoreByArtist",{artistName:a}),localize("FUSE.Product.YouMayAlsoLike")];const g=get(n,"lockup.results");const h=[c,u];let f;if(g[l]){const onSelect=()=>createPushSegueForStoreContent(g[l]);f=createContainerDetailLink({onSelect:onSelect})}const p=createMusicVideoHeader({storePlatformDictionary:o},{artistDetailLink:f});const m=h.reduce((e,t,r)=>{const i=t.slice(0,MAX_SHELF_ITEMS);const n=createShelfFromLockups(i||[],g,{options:{title:d[r]}});if(n){if(i.lengthcreatePushSegue({componentController:new SeeAllController({contentIds:t})});n.containerDetailLink=createContainerDetailLink({onSelect:onSelect})}e.push(n)}return e},[]);if(p){t.push(p)}if(s){t.push(createParagraph({text:s,shouldHideDivider:true}))}if(m.length>0){t.push(...m)}return createVerticalStack({childViewModels:t})}}function findContentIds$3(e){let t=get(e,"pageData.adamIds");if(!t){const r=get(e,"socialData.[0].children");t=getContentIdList(r)||[]}return t}const BaseClass$k=mix(StorePageController).with(SocialProfileBadgingMixin);class SocialProfileSeeAllController extends BaseClass$k{didLoad(){super.didLoad();this.loadPage()}loadPage(){return super.loadPage().then(()=>this.badgeViewModel(true))}willAppear(){super.willAppear();if(this.viewModel){this.badgeViewModel()}}getMissingContentIds(e){return findContentIds$3(e).map(e=>String(e))}createPageMetrics(e){super.createPageMetrics(e);const{socialProfileId:t,followState:r}=get(e,"relationship",{});const{isPrivate:i=false,isVerified:n=false}=get(e,["storePlatformData","product","results",t],{});const o=get(e,"socialData.[0].moduleType");delete this.pageFields.pageUrl;this.pageFields.pageType="Profile";this.pageFields.pageId=o;this.pageFields.page=combineWithSeparator(this.pageFields.pageType,"0",this.pageFields.pageId);this.pageFields.pageDetails={followState:r,isPrivate:i,isVerified:n}}onNeedsAdditionalChildViewModels(e){if(e){this.viewModel.onNeedsAdditionalChildViewModels=null;fetchJSONWithStorePlatformData(e,{getIdsMissingStorePlatformData:this.getMissingContentIds}).then(e=>{const t=this.createChildViewModel(e);if(t){const e=this.viewModel&&this.viewModel.childViewModels&&this.viewModel.childViewModels[this.viewModel.childViewModels.length-1];if(e instanceof SocialProfileCollection&&t instanceof SocialProfileCollection){e.appendItems(t.items)}else{this.viewModel.appendChildViewModels([t])}}const r=get(e,"next");if(r){this.viewModel.onNeedsAdditionalChildViewModels=this.onNeedsAdditionalChildViewModels.bind(this,r)}})}}createViewModel(e){const t=get(e,"socialData[0].moduleType");const r=get(e,"relationship.followState");const i=getTitleForModuleType(t,r);let n;if(i){this.headerItem.title=i;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}const o=this.createChildViewModel(e);if(o){n=createVerticalStack({childViewModels:[o]});const t=get(e,"next");if(t){n.onNeedsAdditionalChildViewModels=this.onNeedsAdditionalChildViewModels.bind(this,t)}}return n}createChildViewModel(e){const t=findContentIds$3(e);const r=get(e,"storePlatformData.lockup.results");const i=get(t,"[0]");const n=get(r,i);const o={};const s={};const a=containsMixedContent({ids:t,lockupData:r});const l=get(e,"socialData.[0].moduleType");const c=get(e,"relationship.followState");let u;if(n&&!a&&n.kind==="playlist"){o.adaptiveLayoutStyle=get(Grid,"ADAPTIVE_LAYOUT_STYLE.COMPACT_LIST")}if(n&&n.kind==="socialProfile"){const i=c==="self"&&l==="USER_FOLLOWERS"&&isSocialProfilePrivateSync();const n=getStatesFromSocialData(get(e,"socialData"));const o=i&&get(SocialProfileCollection,"COLLECTION_STYLE.EDIT")?SocialProfileCollection.COLLECTION_STYLE.EDIT:SocialProfileCollection.COLLECTION_STYLE.DEFAULT;u=createSocialProfileCollectionFromLockups({ids:t,lockupData:r,followStates:n,collectionStyle:o})}else{if(l==="USER_ENGAGEMENT"){s.uniformCellType=GridSection.UNIFORM_CELL_TYPE.ALBUM}u=createGridFromLockups(t,r,{options:o,sectionOptions:s});if(l==="USER_ENGAGEMENT"&&c==="self"){addHideFromProfileContextToItem(u,this.removeItemFromListeningTo.bind(this))}}return u}removeItemFromListeningTo(e){removeItemFromParent(this.viewModel,e)}}function findContentIds$4(e){return get(e,"pageData.adamIds",[])}const BaseClass$l=mix(StorePageController).with(SocialProfileBadgingMixin);function createArtistContentGrid$1(e=[],t){const r=get(e,"[0]");const i=get(t,r);const n=get(i,"kind");const o=containsMixedContent({contentIds:e,lockupData:t})||n==="uploadedVideo"||n==="uploadedAudio"||n==="radioStation"?GridSection.UNIFORM_CELL_TYPE.SHOWCASE:null;const s=n==="playlist"||n==="activity"?get(Grid,"ADAPTIVE_LAYOUT_STYLE.COMPACT_LIST"):get(Grid,"ADAPTIVE_LAYOUT_STYLE.DEFAULT");const itemIteratorCallback=(e,t={})=>{const r=get(t,"kind");let i;if(r==="radioStation"){const e=sanitizeItunesNotes(t);const r=e.itunesNotes?.standard;if(r){i=r}}if(r==="album"||r==="musicVideo"){const e=localizedYearStringFromReleaseDate(t.releaseDate);if(e){i=e}}if(r==="song"){const e=localizedYearStringFromReleaseDate(t.releaseDate);if(e&&t.collectionName&&Device.model!=="iPad"){i=`${t.collectionName} · ${e}`}else{i=t.artistName}}return createGridItem(Object.assign({storePlatformDictionary:t},{subtitle:i}))};const sectionIteratorCallback=e=>createGridSection(Object.assign(e,{uniformCellType:o}));const gridCallback=e=>createGrid(Object.assign(e,{adaptiveLayoutStyle:s}));return createGridWithIterator(e,t,itemIteratorCallback,sectionIteratorCallback,gridCallback)}class ArtistSeeAllController extends BaseClass$l{didLoad(){super.didLoad();this.loadPage()}loadPage(){return super.loadPage().then(()=>this.badgeViewModel(true))}willAppear(e){super.willAppear(e);if(this.viewModel){this.badgeViewModel()}}getMissingContentIds(e){return findContentIds$4(e).map(e=>String(e))}createViewModel(e){const t=get(e,"pageData.pageTitle")||get(e,"pageData.title");const r=findContentIds$4(e);const i=get(e,"storePlatformData.lockup.results");const n=[];let o;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD;if(t){this.headerItem.title=t}const s=createArtistContentGrid$1(r,i);if(s){n.push(s);o=createVerticalStack({childViewModels:n})}return o}}function isLyricsURL(e){if(typeof e==="string"){const t=new RegExp(/\/\w{2}\/lyrics\/.*\?.*(ts=|te=).*/,"i");return t.test(e)}}function getLyricsUpsellSegueCheckingForSubscriber(e){return hasSubscription().then(t=>{if(t){return Promise.resolve(null)}const r={};r[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]=dynamicAMSUISegueForURL.OFFER_HINTS.OTHER;return dynamicAMSUIURLForPlacement(dynamicAMSUIURLForPlacement.PLACEMENTS.MUSIC_LYRICS_SHARING_UPSELL).then(t=>dynamicAMSUISegueForURL(t,Object.assign(e,r)))})}function constructLyricsUpsellSegue(e,t){if(isLyricsURL(e)){return getLyricsUpsellSegueCheckingForSubscriber(t)}return Promise.resolve(null)}const BaseClass$m=mix(ComponentController).with(MetricsMixin);class UnknownController extends BaseClass$m{constructor(e,...t){super(e,...t);this.options=e}isSongURL(e){if(typeof e==="string"){const t=new RegExp(/\/\w{2}\/album\/.*\?.*i=.*/,"i");return t.test(e)}}shouldRouteToMusicAPIController(){const e=isLyricsURL(this.options?.url);const t=this.isSongURL(this.options?.url);return!e&&!t}get componentTypeMap(){return{grouping_page:GroupingController,room_page:RoomController,multi_room_page:RoomController$1,top_charts_page:TopController,album_page:this.shouldRouteToMusicAPIController()?MusicKitAlbumDetailController:AlbumDetailController,playlist_page:PlaylistDetailController,music_video_page:MusicVideoController,artist_page:ArtistController,artist_see_all_page:ArtistSeeAllController,brand_page:BrandController,itunes_brand_page:CuratorController,activity_page:CuratorController$1,show_brand_page:ShowDetailController,episode_page:EpisodeDetailController,movie_page:EpisodeDetailController,user_page:SocialProfileController,user_see_all_page:SocialProfileSeeAllController,follow_requests:FollowRequestController}}getPageData(e={}){const{pageData:t}=e;return t?Promise.resolve(t):this.getURL(e).then(e=>fetchJSON(e))}getURL(e){const{url:t,id:r}=e;let i;if(r){i=fetchContent({ids:[r]}).then((e={})=>get(e[r],"url"))}else{i=Promise.resolve(t)}return i}didLoad(){super.didLoad();this.loadPage()}didAppear(){this.pageContext=currentPageContext();super.didAppear()}loadPage(e){const t=e||this.options||{};return this.getPageData(t).then(e=>{let r=get(e,"pageData.componentName")||get(e,"componentName");if(!r&&get(e,"activity")){r="post_page"}if(r==="social_profile"&&get(e,"relationship.socialProfileId")&&shouldSocialSync()){const e=url.parse(t.url);if(e.query&&e.query.indexOf("actionType=seeAll")!==-1){r="user_see_all_page"}else{r="user_page"}}if(r==="grouping_page"&&get(e,"pageData.iTunesBrandAdamId")){r="itunes_brand_page"}const i=this.componentTypeMap[r];let n;if(i){const o=Object.assign({pageData:e},t);if(r==="album_page"){const t=get(e,"pageData.id");const r=["storePlatformData","product-dv","results",t];const i=get(e,r);o.albumStorePlatformDictionary=i}else if(r==="playlist_page"){const t=get(e,"pageData.id");const r=get(e,"storePlatformData.playlist-product");const i=r?["storePlatformData","playlist-product","results",t]:["storePlatformData","chart-playlist-product","results",t];const n=get(e,i);if(n){o.playlistStorePlatformDictionary=n}else{logger$5.error("No playlistProduct available",e,i)}}else if(r==="itunes_brand_page"||r==="brand_page"){const t=get(e,"pageData.id");const r=["storePlatformData","product","results",t];const i=get(e,r);o.storePlatformDictionary=i}else if(r==="artist_page"){const t=e?.pageData?.id;const r=e?.storePlatformData?.artist?.results?.[t];o.storePlatformDictionary=r}const s=new i(o);if(r==="album_page"||r==="playlist_page"){this.viewModel=s.viewModel}delete this.options;Object.keys(s).forEach(e=>{if(e!=="_state"){this[e]=s[e]}});Object.setPrototypeOf(this,i.prototype);if(s instanceof MetricsMixin){this.shouldRecordPerformanceMetrics=false}n=s.didLoad.call(this);s.willAppear.call(this);s.didAppear.call(this)}else{const t=get(e,"action.kind");const i=get(e,"action.url");const o=t===ActionError.TYPES.GOTO||t===ActionError.TYPES.RESET;if(o&&i){const e=url.parse(i);if(e.query.indexOf("app=itunes")!==-1){const e={url:i};throw new ActionError("",e)}n=this.loadPage({url:i})}else{logger$5.log("unsupported component",r);throw new Error}}return n}).catch(e=>{let t;if(e instanceof ActionError){t=()=>{const t=get(e,"url");return createRedirectSegue({url:t})}}else{t=createRetryHandler(this)}logger$5.error(e);const r=userFacingMessageForError(e);if(r){this.viewModel=createMessageViewModel({message:r,onAccessoryButtonSelect:t})}})}}const BaseClass$n=mix(ComponentController).with(HeaderItemMixin);class RadioScheduleController extends BaseClass$n{updateHeaderItem(){this.headerItem.title="Beats 1";this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE}didLoad(){super.didLoad();const e="http://uic.itunes.apple.com/live-stations/beats1/feed.json";this.fetchSchedule(e).then(([e,t])=>this.processBBData(e,t)).then(e=>{this.viewModel=e;this.viewModel.playActivityFeatureName="explore_beats_1"}).catch(e=>{logger$5.error(e);const t=userFacingMessageForError(e);if(t){this.viewModel=createMessageViewModel({message:t})}})}willUnload(...e){clearLiveRadioTimers(this);super.willUnload(...e)}processBBData(e,t){const r=this.processCurrentShow(e,t);const i=this.processUpcomingShows(e,t,r);const n=this.processAnchorShows(e,t);const o=this.processFeaturedShows(e,t);const s=[r,i,n,o];const a=createVerticalStack({childViewModels:s});return a}processCurrentShow(e,t){let r;const i=t[get(e,"stationId")];const n=getCurrentShow(e);if(n){r=createFlowcase();addLiveRadioTimer.call(this,r,t=>{const r=getCurrentShow(e);const n=getLiveURLHeroData(r,i);const o=createFlowcaseItem(n);const s=constructDateRangeDescriptor(get(r,"startTime"),get(r,"endTime"));const a=constructLiveRadioCaseDateFormatter(`${localize("FUSE.Radio.Beats1Live")} • %@`);const l=constructValueTransformerOptions(a,"headline",s);o.applyValueTransformer(l);t.items=[o]},()=>getRemainingTime(getCurrentShow(e)));r.playActivityFeatureName="beats_1_live"}return r}processUpcomingShows(e,t){const r=localize("FUSE.Radio.UpcomingShows");const i=get(e,"upcomingShows",[]);const n=getCurrentShow(e);const o=get(n,"showIndex",0)+1;const s=i.slice(o,i.length);const a=this.processRadioShelf(s,t,r);a.playActivityFeatureName="upcoming_shows";return a}processAnchorShows(e,t){const r=localize("FUSE.Radio.Beats1.Anchors");const i=this.processAnchorsShelf(e.anchorShows,t,r);i.playActivityFeatureName="anchors";return i}processFeaturedShows(e,t){const r=localize("FUSE.Radio.Beats1.AllShows");const i=this.processGrid(e.featuredShows,t,r);i.playActivityFeatureName="all_shows";return i}processRadioShelf(e,t,r){const i=ShelfSection.UNIFORM_CELL_TYPE.FEATURED_RADIO_SHOW;const n=e.reduce((e,r)=>{let i;const n=t[r.curatorId]||{};if(!CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){return e}const o=get(r,"startTime");const s=get(r,"endTime");const a=constructLiveRadioCaseDateFormatter();const l=get(r,"description");if(Object.keys(n).length>0){i=createShelfItem({storePlatformDictionary:n,subtitle:l})}else{const e=get(r,"title");const t={url:get(r,"artworkUrl"),height:1080,width:1080};const o=createArtwork({dictionary:t,cropStyle:Artwork.CROP_STYLE.SQUARE_CENTER_CROP});n.kind="radioStation";n.id="ra.978194965";i=createShelfItem({title:e,subtitle:l,backgroundArtwork:o,storePlatformDictionary:n,onSelect:()=>createNoopSegue()})}const c=constructDateRangeDescriptor(o,s);const u=constructValueTransformerOptions(a,"headline",c);i.applyValueTransformer(u);if(i){e.push(i)}return e},[]);let o;if(n.length>0){const e=createShelfSection({items:n,uniformCellType:i});o=createShelf({title:r,sections:[e]})}return o}processAnchorsShelf(e,t,r){const i=e.reduce((e,r)=>{let i;const n=t[r.curatorId]||{};if(Object.keys(n).length>0&&CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){const e=localize(`FUSE.Radio.BroadcastFrom.${r.location}`);i=createShelfItem({storePlatformDictionary:n,subtitle:e})}if(i){e.push(i)}return e},[]);let n;if(i.length>0){n=createShelf({title:r,sections:[createShelfSection({items:i})]})}return n}processGrid(e,t,r){const i=e.reduce((e,r)=>{let i;const n=t[r.curatorId]||{};const o=get(r,"showHost"," ");const s=getFormattedDayString(get(r,"nextStartTime"));if(Object.keys(n).length>0&&CapabilitiesController.shouldShowItemWithStorePlatformDictionary(n)){i=createGridItem({storePlatformDictionary:n,subtitle:o,overlayTitle:s})}if(i){e.push(i)}return e},[]);let n;const o=createGridSection({title:r,items:i});if(i.length>0){n=createGrid({sections:[o]})}return n}fetchSchedule(e){return fetchJSON(e).then(e=>{const t=e.curatorIds;const r=t.map(e=>e.toString());r.push(e.stationId);return Promise.all([e,fetchContent({ids:r})])})}}const SUPPORTED_STORE_KINDS={album:false,playlist:false,iTunesBrand:true,activity:true,brand:true,artist:true,musicVideo:true,tvEpisode:true,movie:true,showBrand:true,tvShow:true,socialProfile:true,recordLabel:true};function createPushSegue(e){return Object.assign(new PushSegue,e)}function createPushSegueForID(e,t){const r=Object.assign({id:e},t);const i=new UnknownController(r);return createPushSegue({componentController:i})}function createPushSegueForURL(e,t){const r=Object.assign({url:e},t);const i=url.parse(e);let n=UnknownController;let o=r.showsLargeTitleHeader;const s=i.pathname;const a=s.match(/\/\w{2}\/lyrics\/([0-9]+)/);const l=s.match(/\/\w{2}\/label\//);if(a){r.id=a[1]}else if(i.pathname==="/beats1"){o=true;n=RadioScheduleController}else if(l){const e=s.split("/");r.id=e[e.length-1];n=RecordLabelController}if(!r.controllerTitle&&r.title){r.controllerTitle=r.title}delete r.title;const c=new n(r);if(o!==undefined){c.title=r.controllerTitle;c.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}return createPushSegue({componentController:c})}function createPushSegueForStoreContent(e={}){const t=e.kind;let r;let i;if(t==="iTunesBrand"){r=new CuratorController({storePlatformDictionary:e})}else if(t==="showBrand"||t==="tvShow"){r=new ShowDetailController({storePlatformDictionary:e})}else if(t==="activity"){r=new CuratorController$1({storePlatformDictionary:e})}else if(t==="brand"){r=new BrandController({storePlatformDictionary:e})}else if(t==="artist"){r=new ArtistController({storePlatformDictionary:e})}else if(t==="musicVideo"){r=new MusicVideoController({storePlatformDictionary:e})}else if(t==="tvEpisode"||t==="movie"){r=new EpisodeDetailController({storePlatformDictionary:e})}else if(t==="socialProfile"){r=new SocialProfileController({storePlatformDictionary:e})}else if(t==="recordLabel"){r=new RecordLabelController({mediaAPIDictionary:e})}if(r){const n=["musicVideo","iTunesBrand","movie","tvEpisode","showBrand","tvShow","socialProfile"];if(n.indexOf(t)===-1){const t=e.shortName||e.name;r.title=t;r.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED}i=createPushSegue({componentController:r})}return i}function createPushSegueHandler(e){const t=get(e,"storePlatformDictionary.kind");let r;if(t){if(SUPPORTED_STORE_KINDS[t]){r=e=>{const{storePlatformDictionary:t}=e;return createPushSegueForStoreContent(t)}}}else if(e.url){r=()=>createPushSegueForURL(e.url,e)}return r}function createAppReviewSegue(e){return Object.assign(new AppReviewSegue,e)}function segueForApplicationMessage(e){const t=e.identifier;const r=e.contentPages[0]?.contentParameters?.segue;if(r==="JSAppReview"){logger$5.log("Attempting to present AppReviewSegue");return createAppReviewSegue({applicationMessageIdentifier:t})}const i=e.contentPages[0]?.contentParameters?.url;if(!i){Application.reportMessagePresentationDidFailWithIdentifier(t);logger$5.error("Unable to present application message with identifier:",t);return createNoopSegue()}return dynamicAMSUISegueForURL(i,{applicationMessageIdentifier:t})}function reportApplicationMessageDidDisappearFromStoreFlowSegueOptions(e){const t=e.storeFlowSegue?.userInfo?.applicationMessageIdentifier;if(t){Application.reportMessageDidDisappearWithIdentifier(t)}}class StoreFlowPresentationManager{constructor(){this.presentedViewControllerIdentifiers=new Set;if(StoreFlowPresentationCoordinator){StoreFlowPresentationCoordinator.onViewControllerPresented=this.onViewControllerPresented.bind(this);StoreFlowPresentationCoordinator.onViewControllerReloaded=this.onViewControllerReloaded.bind(this);StoreFlowPresentationCoordinator.onViewControllerDismissed=this.onViewControllerDismissed.bind(this)}}onViewControllerPresented(e){this.presentedViewControllerIdentifiers.add(e.viewControllerIdentifier);logger$5.log(`${this.constructor.name} view controller presented`,e.viewControllerIdentifier,get(e.storeFlowSegue,"url"));isFamilySubscription().then(e=>{this.isCurrentlyFamilySubscriber=e})}onViewControllerReloaded(e){logger$5.log(`${this.constructor.name} view controller reloaded`,e.viewControllerIdentifier,get(e.storeFlowSegue,"url"))}onViewControllerDismissed(e,t){logger$5.log(`${this.constructor.name} view controller dismissed`,e.viewControllerIdentifier,get(e.storeFlowSegue,"url"),"didCompletePurchase: ",e.didCompleteSubscriptionPurchase,"didFinishLinkingWithCarrier:",e.didFinishLinkingWithCarrier);this.presentedViewControllerIdentifiers.delete(e.viewControllerIdentifier);reportApplicationMessageDidDisappearFromStoreFlowSegueOptions(e);const r=e?.storeFlowSegue?.userInfo?.originalUrl;if(isLyricsURL(r)){t(createPushSegueForURL(r));logger$5.log(`${this.constructor.name} view controller dismissed for lyrics deeplink upsell`,e.viewControllerIdentifier,get(e.storeFlowSegue,"url"),"didCompletePurchase: ",e.didCompleteSubscriptionPurchase);return}if(e.didFinishLinkingWithCarrier){presentOnboardingControllerIfRequired(t);logger$5.log(`${this.constructor.name} Did finish linking with carrier: ${e.didFinishLinkingWithCarrier}`)}const i=e.subscriptionStatus;logger$5.log(`${this.constructor.name} Subscription status: ${JSON.stringify(i)}`);let n=e?.storeFlowSegue?.userInfo?.shouldSuppressOnboarding||e.subscriptionStatus?.music?.status==="Glide";logger$5.log(`${this.constructor.name} Should suppress onboarding: ${n}`);isFamilySubscription().then(r=>{logger$5.log(`showFamilyCircle: ${r}, was previously a Family subscriber: ${this.isCurrentlyFamilySubscriber}`);if(r&&!this.isCurrentlyFamilySubscriber){presentFamilyCircleSheet(e,n,t);n=true;this.isCurrentlyFamilySubscriber=true}});if(e.didCompleteSubscriptionPurchase){reportBuyConfirmedEventFromCarplayUpsellIfNecessary(e);const attemptToPresentOnboarding=()=>{if(!n){presentOnboardingControllerIfRequired(t)}};attemptToPresentOnboarding()}}get isStoreFlowViewControllerPresented(){return this.presentedViewControllerIdentifiers.size>0}}var StoreFlowPresentationManager$1=new StoreFlowPresentationManager;function createLegacyFinanceURL(e,t,r,i){return getBagValue("financeApp").then(n=>createFinanceURLForPathName(n,i,e,t,r))}function isCommerceAppCompatiblePath(e,t,r){const i=get(e,"urlPath");if(!i){return false}const n=r.indexOf("/")===0?r.slice(1).toLowerCase():r.toLowerCase();for(const e of t){const t=i[e]||{};const r=Object.keys(t).find(e=>e.toLowerCase()===n);if(r){return true}}return false}function createSegueToFinanceSync(e,t,r,i,n,o=createFinanceURLForPathName.DEFAULT_URL_PATH_KEYS){const s=getBagValueSync("commerceApp");const a=isCommerceAppCompatiblePath(s,o,e);let l;if(a){l=s}else{l=n||getBagValueSync("financeApp")}if(!l){return false}const c=createFinanceURLForPathName(l,o,e,t,i);if(c){return createFinanceSegue(c,r)}return false}function createFinanceURL(e,t,r,i=createFinanceURLForPathName.DEFAULT_URL_PATH_KEYS){return getBagValue("commerceApp").catch(e=>{logger$5.warn("Couldn't create a finance URL from the commerceApp bag, will fall back to legacy financeApp bag.",e)}).then(n=>{const o=isCommerceAppCompatiblePath(n,i,e);if(o){return createFinanceURLForPathName(n,i,e,t,r)}return createLegacyFinanceURL(e,t,r,i)})}function createSegueToFinance(e,t,r,i){return createFinanceURL(e,t,i).then(e=>{if(e){return createFinanceSegue(e,r)}})}function isEligibleForWinbackOffer(e={}){const t="rawResponseData.music.isNotEligibleForFreeTrial";const r=get(e,t,false);const i=get(e,"rawResponseData.music.eligibleOffer");const n=/WIN_BACK_+/;return n.test(i)&&r}function isEligibleForHomePodOffer(e={}){const t=get(e,"rawResponseData.music.eligibleOffer");const r=/HOME_POD/;return get(e,"rawResponseData.music.isSetUpForHomePod")||r.test(t)}function isFamilySubscription$1(e={}){return get(e,"rawResponseData.music.reason")==="Member"||e.isFamilySubscription}function hasSeenRetailOffer(){const e=Storage.getRawItem(StorageKeys.Device.HAS_SEEN_RETAIL_DEVICE_OFFER);return get(e,"value",false)}function setHasSeenRetailDeviceOffer(){Storage.setWrappedItem(StorageKeys.Device.HAS_SEEN_RETAIL_DEVICE_OFFER,true)}function shouldPresentRetailDeviceOffer(){const e=get(Store,"account.hasRetailOffer");const t=hasSeenRetailOffer();return e&&!t}function updateWelcomePresentationStore(){Storage.setItem(StorageKeys.User.LAST_MAJOR_VERSION_WELCOME_SHEET_PRESENTED,Device.majorVersion())}function shouldTriggerWelcomePresentation(){const e=Storage.getItem(StorageKeys.User.LAST_MAJOR_VERSION_WELCOME_SHEET_PRESENTED);return!e||Device.majorVersion()>e}function checkWelcomeTrigger(e){if(isGreaterThanOrEqualToVersion("16.2")){return Promise.resolve()}const t=hasSeenRetailOffer();if(t){return Promise.resolve()}if(hasOptedOutOfSubscription()||restrictsMusicSubscription()){logger$5.log(`Welcome upsell suppressed. hasOptedOutOfSubscription: '${hasOptedOutOfSubscription()}' restrictsMusicSubscription: '${restrictsMusicSubscription()}'`);return Promise.resolve()}const r=shouldTriggerWelcomePresentation();if(e.isSubscribed||!r||isEligibleForWinbackOffer(e)||isEligibleForHomePodOffer(e)){return Promise.resolve()}const i={[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.OTHER,reason:"Music2"};return dynamicAMSUIURLForPlacement(dynamicAMSUIURLForPlacement.PLACEMENTS.LAUNCH_UPSELL).then(e=>dynamicAMSUISegueForURL(e,i)).then(e=>[e,updateWelcomePresentationStore])}function checkCarrierBundling(e){const{eligibilityStatus:t,carrierBundlingStatus:r}=e;let i;if(t===SubscriptionStatusResponse.ELIGIBILITY_STATUS.ELIGIBLE&&r===SubscriptionStatusResponse.CARRIER_BUNDLING_STATUS.UNLINKED){i=createSegueToFinance("carrierAccountLinking")}else if(r===SubscriptionStatusResponse.CARRIER_BUNDLING_STATUS.NEEDS_MANUAL_VERIFICATION){i=createSegueToFinance("carrierSMSVerification")}if(i){return i.then(e=>[e]).catch(e=>{logger$5.error("Checking carrier bundling failed",e);return Promise.resolve()})}return Promise.resolve()}function checkFamilyWelcome(e){if(e.isSubscribed&&isFamilySubscription$1(e)&&!e.isFamilyOrganizer){const e=Persistence.localStorage.getItem(StorageKeys.User.FAMILY_WELCOME_SHOWN);if(!e){return createSegueToFinance("familyWelcome").then(e=>{const updateFamilyWelcomeShownStore=()=>{Persistence.localStorage.setItem(StorageKeys.User.FAMILY_WELCOME_SHOWN,userDSID())};return[e,updateFamilyWelcomeShownStore]}).catch(e=>{logger$5.error("Checking family welcome failed",e);return Promise.resolve()})}}return Promise.resolve()}function checkStudentReverification(e){const t=get(e,"rawResponseData.account.studentExpirationDate");if(t){const e=new Date(t);const r=e.getTime()-Date.now();if(r>0){let e;if(r<6048e5){e=1}else if(r<12096e5){e=2}else if(r<18144e5){e=3}else if(r<24192e5){e=4}if(e){const t=Persistence.localStorage.getItem(StorageKeys.Device.LAST_STUDENT_PROMPT)||"{}";const r=JSON.parse(t);let i=false;let n;if(e===1){const t=(new Date).getDay();i=!r.day||r.day!==t;if(i){n={window:e,day:t}}}else{i=!r.window||r.window!==e;if(i){n={window:e}}}if(i){return createSegueToFinance("studentreverification").then(e=>{const updateLastStudentPromptStore=()=>{Persistence.localStorage.setItem(StorageKeys.Device.LAST_STUDENT_PROMPT,JSON.stringify(n))};return[e,updateLastStudentPromptStore]})}}}}return Promise.resolve()}function getCurrentDeviceState(){return{date:Date.now(),systemVersion:Device.systemVersion}}function hasPresentedHomePodOffer(){const e=Persistence.localStorage.getItem(StorageKeys.Device.HOME_POD_OFFER_LAST_PRESENTED_V2);if(!e){return false}return!!e[userDSID()]}function updateHomePodOfferStore(){const e=getCurrentDeviceState();const t=Persistence.localStorage.getItem(StorageKeys.Device.HOME_POD_OFFER_LAST_PRESENTED_V2)||{};t[userDSID()]=e;Persistence.localStorage.setItem(StorageKeys.Device.HOME_POD_OFFER_LAST_PRESENTED_V2,t)}function checkHomePodOffer(e){if(!e.isSubscribed&&isEligibleForHomePodOffer(e)&&!hasPresentedHomePodOffer()&&!hasOptedOutOfSubscription()){const e={[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.HOME_POD,reason:"AppLaunchOffer"};return dynamicAMSUIURLForPlacement(dynamicAMSUIURLForPlacement.PLACEMENTS.LAUNCH_UPSELL).then(t=>dynamicAMSUISegueForURL(t,e)).then(e=>[e,updateHomePodOfferStore])}return Promise.resolve()}function shouldRetriggerTimeBasedWinback(e){return isDateOnOrAfter(e,{val:1,unit:"month"})}function shouldPresentWinbackOffer(){const e=Storage.getWrappedItem(StorageKeys.User.HAS_SEEN_WINBACK_OFFER);if(hasOptedOutOfSubscription()||restrictsMusicSubscription()){logger$5.log(`Winback offer suppressed. hasOptedOutOfSubscription: '${hasOptedOutOfSubscription()}' restrictsMusicSubscription: '${restrictsMusicSubscription()}'`);return false}if(!e||!e.date){return true}return shouldRetriggerTimeBasedWinback(e.date)}function updateWinbackOfferStore(){Storage.setItem(StorageKeys.User.HAS_SEEN_WINBACK_OFFER,true)}function checkWinbackOffer(e){if(isGreaterThanOrEqualToVersion("16.2")){return Promise.resolve()}if(isEligibleForWinbackOffer(e)&&shouldPresentWinbackOffer()){const e={[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.WIN_BACK,reason:"AppLaunchOffer"};return dynamicAMSUIURLForPlacement(dynamicAMSUIURLForPlacement.PLACEMENTS.LAUNCH_UPSELL).then(t=>dynamicAMSUISegueForURL(t,e)).then(e=>[e,updateWinbackOfferStore])}return Promise.resolve()}function considerPresentingRetailDeviceOffer(){if(shouldPresentRetailDeviceOffer()){const e={[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.RETAIL,reason:"RetailDeviceOfferResumption"};return dynamicAMSUIURLForPlacement(dynamicAMSUIURLForPlacement.PLACEMENTS.LAUNCH_UPSELL).then(t=>dynamicAMSUISegueForURL(t,e)).then(e=>[e,setHasSeenRetailDeviceOffer])}return Promise.resolve()}function checkFinanceOnBecomingActive(e,t){const performSegue=(e,r)=>{if(r){r()}t(e);return Promise.resolve()};if(StoreFlowPresentationManager$1.isStoreFlowViewControllerPresented){logger$5.log("Don't perform a segue, there's a store flow view controller already presented that we don't want to overlap.");t(createNoopSegue());return Promise.resolve()}if(SubscriptionPurchaseManager$1.isMusicSubscriptionPurchaseInProgress){logger$5.log("Don't perform a segue, there's a music subscription purchase in progress.");t(createNoopSegue());return Promise.resolve()}if(restrictsMusicSubscription()){t();return Promise.resolve()}const r=[checkCarrierBundling,considerPresentingRetailDeviceOffer,checkWinbackOffer,checkWelcomeTrigger,checkFamilyWelcome,checkStudentReverification,checkHomePodOffer,considerPresentingSocialOnboarding,considerPresentingContactsConsent];const nextSeguePromise=i=>{const n=r.shift();if(!n){t();return Promise.resolve()}return n(i,e).then(([e,t]=[])=>{if(e){if(e instanceof NoopSegue){logger$5.log("No-op segue provided by:",n.name)}else{logger$5.log("Perform segue:",n.name,e.constructor.name,e.url)}return performSegue(e,t)}return nextSeguePromise(i)})};return getSubscriptionStatus().then(e=>{if(hasVoiceAccount(e)){t();return Promise.resolve()}return nextSeguePromise(e)})}function initializeFinance(){initializeFinanceDeeplinks()}function onSubscriptionRequired(e={},t,r){if(StoreFlowPresentationManager$1.isStoreFlowViewControllerPresented){logger$5.log("onSubscriptionRequired: Already presenting a storeFlowSegue");return r(createNoopSegue())}if(Application.isPrivacyDisclaimerPresented){logger$5.log("onSubscriptionRequired: privacy Dislaimer is presenting. Will show upsell.");r(createNoopSegue());return}const{id:i}=e;let n;if(i){n=peekContent([i]).then(t=>t[i]||e)}else{n=Promise.resolve(e)}n.then(e=>{const t={[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.OTHER};const r=e?.id;const i=e?.mediaKitKind;const n=e?.placement;if(n===dynamicAMSUIURLForPlacement.PLACEMENTS.PLAYBACK_UPSELL){if(r){t[dynamicAMSUISegueForURL.OPTION_KEYS.SEED]=r}if(i){t[dynamicAMSUISegueForURL.OPTION_KEYS.MEDIAKIT_KIND]=i}}if(n===dynamicAMSUIURLForPlacement.PLACEMENTS.MUSIC_SHARED_LISTEN_UPSELL){t.shouldSuppressOnboarding=true}if(n===dynamicAMSUIURLForPlacement.PLACEMENTS.MUSIC_VOICE_UPSELL){const t=e?.configurationOptions;logger$5.log("Beginning preview purchase with options");return previewPurchaseSegueForPurchaseOptions(t)}return dynamicAMSUIURLForPlacement(n).then(e=>dynamicAMSUISegueForURL(e,t))}).then(e=>{r(e)}).catch(e=>{publish(SUBSCRIPTION_PURCHASE_DID_FAIL);logger$5.error("onSubscriptionRequired flow failed",e);r(createNoopSegue())})}let subscriptionStatusState={};const USER_SOCIAL_ONBOARDING_STATUS_CHANGED="userSocialOnboardingStatusChanged";const USER_SOCIAL_PROFILE_DID_CHANGE="userSocialProfileDidChange";const USER_FOLLOWEES_DID_CHANGE="userFolloweesDidChange";const USER_FOLLOWERS_DID_CHANGE="userFollowersDidChange";const USER_REMOVED_RECOMMENDED_FRIEND="userRemovedRecommendedFriend";const followeeStates={};function synchronizeFolloweeStates(){if(Store.account&&Store.account.userSocialProfile){Store.account.userSocialProfile.followeeStates=followeeStates}}function addFolloweeStates(e,t=true){Object.keys(e).forEach(t=>{const r=get(followeeStates,t);if(r&&r!==e[t]||!r){createSocialProfile({followState:e[t],storePlatformDictionary:{id:t,socialProfileId:t}})}});Object.assign(followeeStates,e);if(t){synchronizeFolloweeStates()}}function changeFolloweeStates(e,t=true){addFolloweeStates(e,t);publish(USER_FOLLOWEES_DID_CHANGE)}function getStatesFromSocialData(e=[]){const t={};e.forEach(e=>{const r=get(e,"children",[]);const i=r[0]||{};if(i.contentType==="user"){r.forEach(e=>{if(e.contentId&&e.followState){t[e.contentId]=e.followState}})}});addFolloweeStates(t);return t}function getSocialBagSync(){return getBagValueSync("musicFriends")}function getSocialBag(){return getBagValue("musicFriends")}function getSocialBagValue(e){return getSocialBag().then(t=>{const r=get(t,e);if(r===undefined){throw new BagError(`Provided ${e} was not found in the social bag (musicFriends)`)}return r})}function shouldSocialSync(){return!!getSocialBagSync()&&!get(subscriptionStatusState,"rawResponseData.account.isMinor",false)&&CapabilitiesController.canShowSocial&&isUserSignedIn()}function shouldSocial(){return getSubscriptionStatus().then(e=>{subscriptionStatusState=e;const t=get(e,"rawResponseData.account.isMinor",false);const r=hasVoiceAccount(e);if(!t&&!r&&CapabilitiesController.canShowSocial&&isUserSignedIn()){return getSocialBag()}return false}).then(e=>!!e).catch(()=>false)}function createSocialProfileFromData(e={}){const{socialProfileId:t,followRequestCount:r,followState:i,hasOwnerRequestedToFollowUser:n}=get(e,"relationship",{});const o=get(e,"storePlatformData",{});const s=get(o,["product","results",t])||get(o,["lockup","results",t],{});const a=overrideSocialProfile(s);if(i==="self"){getStatesFromSocialData(get(e,"socialData"))}return createSocialProfile({storePlatformDictionary:a,pendingRequestsCount:r,followState:i,hasRequestedToFollowCurrentUser:n,onSelect:()=>createPushSegue({componentController:new SocialProfileController({storePlatformDictionary:a})})})}function isSocialOnboarded(){return getUserProfile().then((e={})=>e.isOnBoarded)}function isSocialOnboardedSync(){return get(Store,"account.userProfile.isOnBoarded",false)}function isSocialProfilePrivate(){return getUserProfile().then((e={})=>e.isOnBoarded&&e.isPrivate)}function isSocialProfilePrivateSync(){return isSocialOnboardedSync()&&get(Store,"account.userProfile.isPrivate",false)}function isSocialProfileVerifiedSync(){return isSocialOnboardedSync()&&get(Store,"account.userProfile.isVerified",false)}function isBlockedFromSocialOnboarding(){return getUserProfile().then((e={})=>e.isOnboardingBlocked)}function isBlockedFromSocialOnboardingSync(){return get(Store,"account.userProfile.isOnboardingBlocked",false)}function canSocialOnboard(){return Promise$1.all([shouldSocial(),isSocialOnboarded(),isBlockedFromSocialOnboarding()]).then(([e,t,r])=>e&&!t&&!r)}function canSocialOnboardSync(){return shouldSocialSync()&&!isSocialOnboardedSync()&&!isBlockedFromSocialOnboardingSync()}function updatePendingRequestsCount(e){const t=Store.account.userSocialProfile;if(t){t.pendingRequestsCount=e}}function updateFollowRequestCount(){return isSocialProfilePrivate().then(e=>{if(!e){return Promise$1.resolve()}return getSocialBag().then(e=>e.followRequestCount).then(e=>fetchJSON(e)).then((e={})=>{const t=e.count||0;updatePendingRequestsCount(t)}).catch(e=>{logger$5.error("Could not update follow request count.",e)})})}function considerFetchingFollowStateForIds(e=[]){return Promise$1.all([shouldSocial(),isSocialOnboarded()]).then(([t,r])=>{if(!t||!r){return Promise$1.resolve()}const i=e.filter(e=>!followeeStates[e]);if(i.length===0){return Promise$1.resolve()}return getSocialBag().then((e={})=>e.getFollowStates).then(e=>{const t={ids:i.join(",")};const r=constructURL(e,{params:t});return fetchJSON(r)}).then((e={})=>{const t=e.followStates.reduce((e,t={})=>{const r=t.id;e[r]=t.followState;return e},{});addFolloweeStates(t)})})}function setUserSocialProfile(e){if(Store.account){Store.account.userSocialProfile=e;publish(USER_SOCIAL_PROFILE_DID_CHANGE)}else{throw new Error("Could not set userSocialProfile, Store.account isn't present.")}}function fetchUserSocialProfileStorePlatformDictionary(e){const t=get(Store,"account.userProfile.socialProfileId")||e;return fetchContent({ids:[t],forceRefresh:true,isPersonalized:true}).then(e=>{const r=e[t];if(!r){throw new Error("Could not fetch store platform data for social profile.")}return r})}function fetchUserSocialProfile(e){return fetchUserSocialProfileStorePlatformDictionary(e).then(e=>{const t=createSocialProfile({storePlatformDictionary:e,backgroundArtwork:createArtwork({dictionary:e.avatarArtwork}),onSelect:()=>createPushSegue({componentController:new SocialProfileController({storePlatformDictionary:e})}),editProfileLink:createContainerDetailLink({onSelect:()=>createPresentationSegue({componentController:new SocialProfileEditController({title:localize("FUSE.Social.Profile.Editbutton")})})})});return t})}function reloadUserProfileIfNeeded(){return new Promise$1((e,t)=>{const r=new Timer;const onUserProfileChange=()=>{unregisterOnUserProfileChange(onUserProfileChange);r.cancel();e()};r.delay=30*1e3;r.onTimeout=()=>{unregisterOnUserProfileChange(onUserProfileChange);t(new Error("Waiting for onUserProfileChange timed out."))};r.schedule();if(Store.account){registerOnUserProfileChange(onUserProfileChange);Store.account.reloadUserProfileIfNeeded()}else{r.cancel();t(new Error("User not signed-in."))}})}function reloadUserProfileAndWaitForNewSocialProfile(){return new Promise$1((e,t)=>{const r=new Timer;const onUserSocialProfileChange=()=>{unsubscribe(USER_SOCIAL_PROFILE_DID_CHANGE,onUserSocialProfileChange);r.cancel();e(Store.account.userSocialProfile)};r.delay=60*1e3;r.onTimeout=()=>{unsubscribe(USER_SOCIAL_PROFILE_DID_CHANGE,onUserSocialProfileChange);t(new Error("Waiting for onUserSocialProfileChange timed out."))};r.schedule();subscribe(USER_SOCIAL_PROFILE_DID_CHANGE,onUserSocialProfileChange);reloadUserProfileIfNeeded().catch(e=>logger$5.error(e))})}function offboardUser(){getSocialBag().then((e={})=>e.offboard).then(e=>fetchJSON(e,{method:HTTP.METHOD.POST})).then(()=>reloadUserProfileIfNeeded()).then(()=>publish(USER_SOCIAL_ONBOARDING_STATUS_CHANGED,false)).catch(e=>{logger$5.error("Could not offboard user.",e);throw e});return createRedirectSegue({url:"https://itunes.apple.com/foryou"})}function updateListeningToPreferences({ids:e=[],actionType:t="unhide"}){return getSocialBag().then((e={})=>e.updateListeningToPreferences).then(r=>fetchJSON(r,{method:HTTP.METHOD.POST,body:{ids:e,actionType:t}})).catch(e=>{logger$5.error("Could not update listening to preferences.",e);throw e})}function getRecommendedFriends(e){return getSocialBag().then((e={})=>e.recommendedFriends).then(t=>{const r={id:e};const i=`${t}?${querystringEs3.encode(r)}`;return fetchJSON(i)}).catch(e=>{logger$5.error("Could not get recommended friends.",e);throw e})}function getListeningToSettings(){return getSocialBag().then((e={})=>e.getListeningToSettings).then(e=>fetchJSON(e)).catch(e=>{logger$5.error("Could not get listening to settings.",e);throw e})}function setListeningToSettings(e={}){return getSocialBag().then((e={})=>e.setListeningToSettings).then(t=>fetchJSON(t,{method:HTTP.METHOD.POST,body:e})).catch(e=>{logger$5.error("Could not set listening to settings.",e);throw e})}function getSuggestedHandles(){return getUserProfile().then(e=>{const t=get(e,"handle");if(t){const e={suggestions:[t]};return Promise$1.resolve(e)}return getBagValue("musicSubscription.suggestedHandles").then(e=>fetchJSON(e)).catch(e=>{logger$5.warn("Could not get suggested handle.",e)})})}function followProfiles(e=[]){if(!e.length){return Promise$1.resolve()}return getSocialBag().then((e={})=>e.followProfiles).then(t=>fetchJSON(t,{method:HTTP.METHOD.POST,body:{ids:e}})).then(e=>{const t=get(e,"followResults",[]);const r={};t.forEach(e=>{r[e.id]=e.followState});changeFolloweeStates(r)}).catch(e=>{logger$5.error("Could not follow profiles.",e)})}function getFollowRequests(){return getSocialBag().then(e=>e.followRequests).then(e=>fetchJSON(e)).catch(e=>{logger$5.error("Could not get follow requests",e)})}function redirectToProfile(){const e=get(Store,"account.userSocialProfile.storePlatformDictionary.shortUrl");return createRedirectSegue({url:e})}function approveAllFollowRequests(){getSocialBag().then((e={})=>e.followRequest).then(e=>fetchJSON(e,{method:HTTP.METHOD.POST,body:{actionType:"approveAll"}})).then(updatePendingRequestsCount(0)).catch(e=>{logger$5.error("Could not approve follow requests",e)});return redirectToProfile()}function setPrivateSocialPlaylists(e=[]){return getSocialBag().then(t=>fetchJSON(t.setPrivateSocialPlaylists,{method:HTTP.METHOD.POST,body:{ids:e}})).catch(e=>{logger$5.error("Could not set private social playlists.",e)})}function onFollowStateDidChange(e,t){if(t){const r={[e]:t};changeFolloweeStates(r,false)}}function onFollowersDidChange(){publish(USER_FOLLOWERS_DID_CHANGE)}function registerListenersForSocialGraphChanges(){registerOnFollowStateDidChange(onFollowStateDidChange);registerOnFollowApprovalDidChange(onFollowersDidChange);registerOnDidApproveAll(onFollowersDidChange);registerOnRemovedFollower(onFollowersDidChange)}function unregisterListenersForSocialGraphChanges(){unregisterOnFollowStateDidChange(onFollowStateDidChange);unregisterOnFollowApprovalDidChange(onFollowersDidChange);unregisterOnDidApproveAll(onFollowersDidChange);unregisterOnRemovedFollower(onFollowersDidChange)}function updateUserSocialProfile(e){if(e&&e.isOnBoarded){return fetchUserSocialProfile(e.socialProfileId).then(e=>{setUserSocialProfile(e);registerListenersForSocialGraphChanges();synchronizeFolloweeStates();updateFollowRequestCount()})}if(get(Store,"account.userSocialProfile")){unregisterListenersForSocialGraphChanges();setUserSocialProfile(null)}return Promise$1.resolve()}function userProfileDidChange(){return getUserProfile().then(e=>{if(!e){throw new Error("User profile could not be retrieved.")}return updateUserSocialProfile(e)}).catch(e=>{logger$5.error("Could not update user and social profile.",e)})}function initializeUserSocialProfile(){const onAccountChangeCallback=(...e)=>{const t=get(e,"[1]");if(t===Store.ACCOUNT_CHANGE_REASON.UNIQUE_IDENTIFIER_CHANGED){initializeUserSocialProfile()}};return Promise$1.all([shouldSocial(),getSubscriptionStatus()]).then(([e,t])=>{registerOnAccountChange(onAccountChangeCallback);if(!e){return Promise$1.resolve()}if(!t.isSubscribed){registerOnSubscriptionChange(initializeUserSocialProfile)}else{unregisterOnSubscriptionChange(initializeUserSocialProfile)}return userProfileDidChange().then(()=>{registerOnUserProfileChange(userProfileDidChange)})}).catch(e=>{logger$5.error("Could not initialize the user social profile.",e)})}function onboardUserAndGetProfileURL(){const e=getSocialBag().then((e={})=>e.onboard).then(e=>fetchJSON(e,{method:HTTP.METHOD.POST})).then(e=>{cacheStorePlatformData(get(e,"storePlatformData",{}))});return e.then(()=>initializeUserSocialProfile()).then(()=>reloadUserProfileAndWaitForNewSocialProfile()).then(e=>{publish(USER_SOCIAL_ONBOARDING_STATUS_CHANGED,true);return e.storePlatformDictionary.url}).catch(e=>{logger$5.error("Could not social onboard user.",e);throw e})}function initializeSocial(){initializeUserSocialProfile();SocialProfileBadgingController.initializeBadging()}function checkShouldSocialUpsellOnFollow(e,t){return Promise$1.all([getSubscriptionStatus(),canSocialOnboard()]).then(([r,i])=>{let n;if(!r.isSubscribed){n=onSubscriptionRequired(t,"",e)}else{const t=i?createSegueToSocialOnboarding():createNoopSegue();n=Promise$1.resolve(t).then(e)}return n})}function removeRecommendedFriend(e){const t=getSocialBagSync();const r=t.removeRecommendedFriend;if(r&&e){const t={method:HTTP.METHOD.POST,body:{id:e}};fetch(r,t).catch(e=>logger$5.error("Failed to removeRecommendedFriend",e));publish(USER_REMOVED_RECOMMENDED_FRIEND)}}const APPEARANCE_STATE={UNLOADED:0,DID_LOAD:1,WILL_APPEAR:2,DID_APPEAR:3,WILL_DISAPPEAR:4,DID_DISAPPEAR:5,WILL_UNLOAD:6};const AbstractContainerControllerMixin=Mixin(e=>{const t=Symbol("childControllers");const r=Symbol("appearanceState");const i=mix(e).with(ViewModelLoaderMixin);const n=class extends i{constructor(...e){super(...e);this.appearanceState=APPEARANCE_STATE.UNLOADED}set childControllers(e){this[t]=e}get childControllers(){if(!this[t]){this[t]=[]}return this[t]}addChildController(e){if(!(e instanceof ContainerChildController)){throw new Error(`Child controllers added to ${this.constructor.name} must be a subclass of ContainerChildController.`)}e.removeFromParentController();this.childControllers.push(e);e.parentController=this;this.callApperanceMethodsOnParentedChildController(e)}removeChildController(e){const t=this.childControllers.indexOf(e);if(t>-1){this.callAppearanceMethodsOnUnparentedChildController(e);this.childControllers.splice(t,1);e.parentController=undefined}}removeChildControllers(){const e=this[t];if(!e){return null}const r=[...e];r.forEach(this.removeChildController.bind(this));return r}onChildLoadedViewModelChanged(){logger$5.warn(`${this.constructor.name} onChildLoadedViewModelChanged called but not overriden by class.`)}onChildLoadedViewModelErrored(){logger$5.warn(`${this.constructor.name} onChildLoadedViewModelErrored called but not overriden by class.`)}set appearanceState(e){this[r]=e}get appearanceState(){return this[r]}callApperanceMethodsOnParentedChildController(e){if(this.environment){e.onEnvironmentChanged(this.environment)}if(this.appearanceState>=APPEARANCE_STATE.DID_LOAD&&this.appearanceState=APPEARANCE_STATE.WILL_APPEAR&&this.appearanceState=APPEARANCE_STATE.WILL_APPEAR&&e.appearanceState=APPEARANCE_STATE.DID_LOAD&&e.appearanceState{if(typeof t[e]==="function"){t[e](...r)}else{logger$5.warn(`Couldn't call on child, "${e}" is not a function on ${t.constructor.name}`)}})}};return n});AbstractContainerControllerMixin.APPEARANCE_STATE=APPEARANCE_STATE;const AbstractContainerController=mix(Object).with(AbstractContainerControllerMixin);AbstractContainerController.APPEARANCE_STATE=AbstractContainerControllerMixin.APPEARANCE_STATE;const parentControllerSymbol=Symbol("parentController");const environmentSymbol$1=Symbol("environment");class ContainerChildController extends AbstractContainerController{set parentController(e){this[parentControllerSymbol]=e}get parentController(){return this[parentControllerSymbol]}removeFromParentController(){if(this.parentController){this.parentController.removeChildController(this)}}onLoadedViewModelChanged(e){if(this.parentController){this.parentController.onChildLoadedViewModelChanged(this,e)}}onLoadedViewModelErrored(e){if(this.parentController){this.parentController.onChildLoadedViewModelErrored(this,e)}}didLoad(...e){this.appearanceState=AbstractContainerController.APPEARANCE_STATE.DID_LOAD;this.callOnChildControllers("didLoad",e)}willAppear(...e){this.appearanceState=AbstractContainerController.APPEARANCE_STATE.WILL_APPEAR;this.callOnChildControllers("willAppear",e)}didAppear(...e){this.appearanceState=AbstractContainerController.APPEARANCE_STATE.DID_APPEAR;this.callOnChildControllers("didAppear",e)}willDisappear(...e){this.appearanceState=AbstractContainerController.APPEARANCE_STATE.WILL_DISAPPEAR;this.callOnChildControllers("willDisappear",e)}didDisappear(...e){this.appearanceState=AbstractContainerController.APPEARANCE_STATE.DID_DISAPPEAR;this.callOnChildControllers("didDisappear",e)}willUnload(...e){this.appearanceState=AbstractContainerController.APPEARANCE_STATE.WILL_UNLOAD;this.callOnChildControllers("willUnload",e)}onEnvironmentChanged(e){this[environmentSymbol$1]=e;this.callOnChildControllers("onEnvironmentChanged",[e])}reportImpressionsForApplicationWillResignActiveEvent(...e){this.callOnChildControllers("reportImpressionsForApplicationWillResignActiveEvent",e)}get environment(){return this[environmentSymbol$1]}}const resourceManagerSymbol$2=Symbol("resourceManager");const personalRecommendationSymbol=Symbol("personalRecommendation");class PersonalRecommendationController extends ContainerChildController{constructor(e,t){super();this.personalRecommendation=t;this.resourceManager.addResources(e)}get resourceManager(){let e=this[resourceManagerSymbol$2];if(!e){e=new MusicAPIResourceManager;this[resourceManagerSymbol$2]=e}return e}get personalRecommendation(){return this[personalRecommendationSymbol]}set personalRecommendation(e){this[personalRecommendationSymbol]=e}get recommendationMetrics(){return get(this,"personalRecommendation.meta.metrics")}get uniqueIdentifier(){return get(this,"personalRecommendation.meta.metrics.reco_id")}onEnvironmentChanged(e){super.onEnvironmentChanged(e);this.resourceManager.onEnvironmentChanged(e)}}function metricsPropertiesForPersonalRecommendation(e={}){const t=get(e,"meta.metrics.reco_id");if(!t){return null}return{reco_id:t,playActivityRecommendationID:t}}const MusicAPIRecommendationDisplayKind={MUSIC_CARD_SHELF:"MusicCardShelf",MUSIC_CIRCLE_COVER_SHELF:"MusicCircleCoverShelf",MUSIC_CIRCLE_COVER_GRID:"MusicCircleCoverGrid",MUSIC_COVER_SHELF:"MusicCoverShelf",MUSIC_COVER_GRID:"MusicCoverGrid",MUSIC_HORIZONTAL_LOCKUP_GRID:"MusicHorizontalLockupGrid",MUSIC_NAMED_BRICK_SHELF:"MusicNamedBrickShelf",MUSIC_NOTES_HERO_SHELF:"MusicNotesHeroShelf",MUSIC_SOCIAL_CARD_SHELF:"MusicSocialCardShelf",MUSIC_SUPER_HERO_SHELF:"MusicSuperHeroShelf",MUSIC_UPSELL_SHELF:"MusicUpsellShelf"};class MusicCoverGridController extends PersonalRecommendationController{loadViewModel(){const e=get(this.personalRecommendation,"attributes.isGroupRecommendation");let t=[];if(e){const e=get(this.personalRecommendation,"relationships.contents.data");const sectionCreationFunction=(e,t)=>this.gridSectionForPersonalRecommendation(t,true);t=this.resourceManager.itemsForResourceIdentifiers(e,sectionCreationFunction)}else{const e=this.gridSectionForPersonalRecommendation(this.personalRecommendation,false);if(e){t=[e]}}if(t.length===0){return null}const r=t[0]?.uniformCellType==="artist";const i=r?Grid.ADAPTIVE_LAYOUT_STYLE.COMPACT_LIST:Grid.ADAPTIVE_LAYOUT_STYLE.DEFAULT;const n={sections:t,adaptiveLayoutStyle:i};Object.assign(n,metricsPropertiesForPersonalRecommendation(this.personalRecommendation));return createGrid(n)}gridSectionForPersonalRecommendation(e,t){const r=e?.relationships?.contents.data;const i=this.resourceManager.itemsForResourceIdentifiers(r,this.musicCoverGridStoreItem.bind(this),this.musicCoverGridLibraryItem.bind(this));if(i.length===0){return null}const n=e?.attributes?.display?.kind;const o=n===MusicAPIRecommendationDisplayKind.MUSIC_CIRCLE_COVER_GRID?GridSection.UNIFORM_CELL_TYPE.ARTIST:GridSection.UNIFORM_CELL_TYPE.ALBUM;const s={items:i,uniformCellType:o};const a=e?.attributes;if(t){let e=a?.title?.stringForDisplay;if(!e&&a?.nextUpdateDate){e=localizedMonthDayStringFromReleaseDate(a?.nextUpdateDate)}s.title=e}return createGridSection(s)}musicCoverGridStoreItem(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping personal recommendation item with id "${e.id}".`);return null}const i={onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),identifierSet:identifierSetForMusicAPIResourceIdentifier(e),backgroundArtwork:createArtwork({dictionary:r.artwork}),name:get(r,"name")};const n=r?.editorialVideo;if(n&&containsMotionDetailVideo(n)){i.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(n),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(n)})}switch(e.type){case MusicAPIResourceType.ALBUMS:Object.assign(i,{title:r.name,subtitle:r.artistName});break;case MusicAPIResourceType.MUSIC_MOVIES:Object.assign(i,{title:r.name,subtitle:r.artistName});break;case MusicAPIResourceType.PLAYLISTS:Object.assign(i,{title:r.name,subtitle:r.curatorName});break;case MusicAPIResourceType.STATIONS:{const e=true;Object.assign(i,{title:getWordMarkString(r.name),subtitle:getBroadcastRadioShowSubtitleForMusicAPIAttributes(r,e)});break}case MusicAPIResourceType.TV_SHOWS:Object.assign(i,{title:r.name,subtitle:""});break;case MusicAPIResourceType.ARTISTS:Object.assign(i,{title:r.name});break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new GridItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}musicCoverGridLibraryItem(e){const t={onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e),identifierSet:identifierSetForMusicAPIResourceIdentifier(e),reco_id:get(this,"recommendationMetrics.reco_id"),displayStyle:"small"};switch(e.type){case MusicAPIResourceType.LIBRARY_ALBUMS:break;case MusicAPIResourceType.LIBRARY_PLAYLISTS:break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new GridItem,t,MetricsClickHandlers.baseItem)}}const ContainerComponentControllerMixin=Mixin(e=>{const t=mix(e).with(AbstractContainerControllerMixin);const r=class extends t{constructor(...e){super(...e);this.pageMetricsController=new PageMetricsController(...e);this.pageMetricsController.shouldRecordPerformanceMetrics=true;this.pageMetricsController.notifyWhenOnScreenResourcesLoaded=this.notifyWhenCurrentlyVisibleContentLoadingCompletes.bind(this);this.pageMetricsController.onPageRequest()}loadPage(){return this.loadedViewModel.then(e=>{this.viewModel=e;this.pageMetricsController.onPageViewModelSet();this.pageMetricsController.considerRecordingPageEvent()}).catch(e=>{if(e.viewModel){this.viewModel=e.viewModel}this.pageMetricsController.onPageError()})}set viewModel(e){super.viewModel=e}get viewModel(){return super.viewModel}viewModelForError(e){return errorViewModel(e,()=>{this.loadedViewModel=null;this.refreshForReason("Error retry button tapped")})}get requiresLocalization(){return true}refreshViewModel(){return this.loadViewModel().then(e=>{this.loadedViewModel=e})}errorViewModel(e){return this.waitForLocalizationIfNeeded().then(()=>this.viewModelForError(e))}onLoadedViewModelChanged(e){this.viewModel=e}onLoadedViewModelErrored(e){if(e.viewModel){this.viewModel=e.viewModel}}didLoad(...e){super.didLoad(...e);this.appearanceState=AbstractContainerControllerMixin.APPEARANCE_STATE.DID_LOAD;this.callOnChildControllers("didLoad",e)}willAppear(...e){super.willAppear(...e);this.appearanceState=AbstractContainerControllerMixin.APPEARANCE_STATE.WILL_APPEAR;this.callOnChildControllers("willAppear",e)}didAppear(...e){super.didAppear(...e);this.appearanceState=AbstractContainerControllerMixin.APPEARANCE_STATE.DID_APPEAR;this.callOnChildControllers("didAppear",e);this.pageMetricsController.didAppear()}willDisappear(...e){super.willDisappear(...e);this.appearanceState=AbstractContainerControllerMixin.APPEARANCE_STATE.WILL_DISAPPEAR;this.callOnChildControllers("willDisappear",e);this.pageMetricsController.willDisappear()}didDisappear(e,t){super.didDisappear(e,t);this.appearanceState=AbstractContainerControllerMixin.APPEARANCE_STATE.DID_DISAPPEAR;this.callOnChildControllers("didDisappear",[e,t]);this.pageMetricsController.didDisappear(t)}reportImpressionsForApplicationWillResignActiveEvent(e){super.didDisappear(e);this.callOnChildControllers("reportImpressionsForApplicationWillResignActiveEvent",[e]);this.pageMetricsController.reportImpressionsForApplicationWillResignActiveEvent(e)}willUnload(...e){super.willUnload(...e);this.appearanceState=AbstractContainerControllerMixin.APPEARANCE_STATE.WILL_UNLOAD;this.callOnChildControllers("willUnload",e)}onEnvironmentChanged(...e){super.onEnvironmentChanged(...e);this.callOnChildControllers("onEnvironmentChanged",e)}waitForLocalizationIfNeeded(){return this.requiresLocalization?waitForLocInitialization():Promise.resolve()}};return r});const BaseClass$o=mix(ComponentController).with(ContainerComponentControllerMixin);const URLSymbol=Symbol("URL");const recommendationIdSymbol=Symbol("recommendationId");class ListenNowSeeAllController extends BaseClass$o{constructor({URL:e,title:t,shouldInvalidateCachedPageResource:r,recommendationId:i}){super(...arguments);this.URL=e;this.title=t;this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD;this.shouldInvalidateCachedPageResource=r;this[recommendationIdSymbol]=i;this.loadPage()}get URL(){return this[URLSymbol]}set URL(e){this[URLSymbol]=e}get recommendationId(){return this[recommendationIdSymbol]}loadViewModel(){const e={pageType:"SeeAll",pageId:this.recommendationId};if(shouldSocialSync()){this.URL.queryString.with.add("social");this.URL.queryString.with.add("friendsMix");this.URL.queryString.addParameters({meta:"catalogIds"})}this.URL.queryString.displayFilterKind=new Set([MusicAPIRecommendationDisplayKind.MUSIC_CIRCLE_COVER_GRID,MusicAPIRecommendationDisplayKind.MUSIC_COVER_GRID]);if(this.childViewModelController){this.childViewModelController.pageMetricsController=null;this.removeChildController(this.childViewModelController)}const t=new ListenNowRecommendationsController(this.URL.string(),this.shouldInvalidateCachedPageResource,e);this.addChildController(t);this.childViewModelController=t;t.pageMetricsController=this.pageMetricsController;return t.loadedViewModel}onChildLoadedViewModelChanged(e,t){this.viewModel=t}onChildLoadedViewModelErrored(e,t){if(t.viewModel){this.viewModel=t.viewModel}}}const ListenNowResourceTypes=new Set([MusicAPIResourceType.ACTIVITIES,MusicAPIResourceType.ALBUMS,MusicAPIResourceType.APPLE_CURATORS,MusicAPIResourceType.ARTISTS,MusicAPIResourceType.CURATORS,MusicAPIResourceType.EDITORIAL_ITEMS,MusicAPIResourceType.LIBRARY_ALBUMS,MusicAPIResourceType.LIBRARY_PLAYLISTS,MusicAPIResourceType.MUSIC_MOVIES,MusicAPIResourceType.PLAYLISTS,MusicAPIResourceType.SOCIAL_PROFILES,MusicAPIResourceType.SOCIAL_UPSELLS,MusicAPIResourceType.SONGS,MusicAPIResourceType.STATIONS,MusicAPIResourceType.TV_SHOWS,MusicAPIResourceType.UPLOADED_AUDIOS,MusicAPIResourceType.UPLOADED_VIDEOS]);const ListenNowRecommendationDisplayKinds=new Set([MusicAPIRecommendationDisplayKind.MUSIC_COVER_SHELF,MusicAPIRecommendationDisplayKind.MUSIC_COVER_GRID,MusicAPIRecommendationDisplayKind.MUSIC_NOTES_HERO_SHELF,MusicAPIRecommendationDisplayKind.MUSIC_SUPER_HERO_SHELF,MusicAPIRecommendationDisplayKind.MUSIC_CIRCLE_COVER_SHELF]);const ListenNowVoiceResourceTypes=new Set([MusicAPIResourceType.ALBUMS,MusicAPIResourceType.PLAYLISTS,MusicAPIResourceType.STATIONS]);const ListenNowVoiceRecommendationDisplayKinds=new Set([MusicAPIRecommendationDisplayKind.MUSIC_CARD_SHELF,MusicAPIRecommendationDisplayKind.MUSIC_HORIZONTAL_LOCKUP_GRID]);class ListenNowURL extends MusicAPIURL{constructor(e,t=false){super(e);this.queryString.types=t?new Set(ListenNowVoiceResourceTypes):new Set(ListenNowResourceTypes);this.queryString.displayFilterKind=t?new Set(ListenNowVoiceRecommendationDisplayKinds):new Set(ListenNowRecommendationDisplayKinds);this.queryString.shouldIncludeTimezoneOffset=true;this.queryString.extend.add("offers");this.queryString.with.add("library");this.queryString.with.add("voice");if(!t){this.queryString.sparse.add("library-albums");this.queryString.sparse.add("library-playlists")}this.queryString.addParameters({"art[url]":"f","omit[resource]":"autos","include[personal-recommendation]":"primary-content","displayFilter[card]":"musicSuperHero"})}domain(){return getBagValue("ampMusicAPIDomains.listenNow")}}const socialProfileBadgingControllerSymbol=Symbol("socialProfileBadgingController");class MusicCoverShelfController extends PersonalRecommendationController{loadViewModel(){const e=this.shelfSectionForPersonalRecommendation(this.personalRecommendation);if(!e){return null}const t=this.personalRecommendation.attributes;const r=this.personalRecommendation.relationships?.["primary-content"]?.data?.[0];let i=t?.titleWithoutName?.stringForDisplay;let n=t?.title?.stringForDisplay;let o;if(i&&r){const e=this.resourceManager.resourceForResourceIdentifier(r);const t=e.attributes;const s=t?.name;if(s){n=s}else{i=null}o=createArtwork({dictionary:t.artwork,treatment:r.type===MusicAPIResourceType.ARTISTS?Artwork.TREATMENT.CIRCLE:Artwork.TREATMENT.DEFAULT})}const s=i==null?t?.reason?.stringForDisplay:null;const a={supertitle:i,title:n,subtitle:s,contentArtwork:o,sections:[e],editorialID:this.personalRecommendation?.id};const l=this.accessoryButtonPropertiesForPersonalRecommendation(this.personalRecommendation);if(l){Object.assign(a,l)}Object.assign(a,metricsPropertiesForPersonalRecommendation(this.personalRecommendation));return createShelf(a)}refreshViewModel(e){const t=e;if(!t){return Promise.reject(new Error("Missing existing view model."))}const r=new ListenNowURL(this.refreshPath);r.queryString.shouldIncludeLanguage=false;r.queryString.displayFilterKind=new Set([MusicAPIRecommendationDisplayKind.MUSIC_COVER_SHELF]);r.queryString.addParameters({action:"refresh"});r.queryString.extend.add("plainEditorialNotes");r.queryString.extend.add("plainEditorialCard");r.queryString.extend.add("editorialVideo");if(shouldSocialSync()){r.queryString.addParameters({meta:"catalogIds"})}return r.string().then(e=>requestMusicAPIResource(e,{method:HTTP.METHOD.POST})).then(e=>{this.resourceManager.addResources(e.resources);const r=e.data?.[0];if(!r){return Promise.reject(new Error("Missing resource identifier for personal recommendation."))}const i=this.resourceManager.resourceForResourceIdentifier(r);if(!i){return Promise.reject(new Error("Missing resource for personal recommendation."))}this.personalRecommendation=i;const n=this.shelfSectionForPersonalRecommendation(this.personalRecommendation);const o=n?[n]:[];t.sections=o;this.socialProfileBadgingController.badgeViewModel(t,true);const s=this.accessoryButtonPropertiesForPersonalRecommendation(this.personalRecommendation);if(s){Object.assign(t,s)}})}get refreshPath(){return this.personalRecommendation.href}shelfSectionForPersonalRecommendation(e){const t=e.relationships?.contents?.data;const r=this.resourceManager.itemsForResourceIdentifiers(t,this.musicCoverShelfStoreItem.bind(this),this.musicCoverShelfLibraryItem.bind(this));if(r.length===0){return null}const i=e?.attributes?.display?.kind;const n=i===MusicAPIRecommendationDisplayKind.MUSIC_CIRCLE_COVER_SHELF?ShelfSection.UNIFORM_CELL_TYPE.ARTIST:ShelfSection.UNIFORM_CELL_TYPE.ALBUM;return createShelfSection({items:r,uniformCellType:n})}containerDetailLinkForSeeAllURL(e,t,r){const i=createContainerDetailLink({onSelect:()=>createPushSegue({componentController:new ListenNowSeeAllController({URL:e,title:t,recommendationId:r})})});return Object.assign(i,MetricsClickHandlers.containerDetailLink,{title:t,recommendationId:r})}containerDetailLinkForPrimaryContentResourceIdentifier(e){const t=this.resourceManager.resourceForResourceIdentifier(e);const r=createContainerDetailLink({onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t,null,false,null,true)});return Object.assign(r,MetricsClickHandlers.containerDetailLink,e)}accessoryButtonPropertiesForPersonalRecommendation(e){const t=e.attributes?.hasSeeAll;const r=e.attributes?.title?.stringForDisplay;const i=e.relationships?.["primary-content"]?.data?.[0];const n=i!==undefined;if(!t&&!n){return null}const o=e.id;let s;if(t){const e=new ListenNowURL(`/v1/me/recommendations/${o}/view/see-all`);e.queryString.name="listen-now";e.queryString.addParameters({"include[personal-recommendation]":"contents"});e.queryString.extend.add("plainEditorialNotes");e.queryString.extend.add("editorialVideo");s=this.containerDetailLinkForSeeAllURL(e,r,o)}else if(n){const e={recommendationId:o,title:r};Object.assign(i,e);s=this.containerDetailLinkForPrimaryContentResourceIdentifier(i)}else{return null}return{containerDetailLink:s}}musicCoverShelfStoreItem(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping personal recommendation item with id "${e.id}".`);return null}const i={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),backgroundArtwork:createArtwork({dictionary:r.artwork}),reco_id:this.recommendationMetrics?.reco_id,displayStyle:"small",name:r.name};const n=r?.editorialVideo;if(n&&containsMotionDetailVideo(n)){i.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(n),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(n)})}switch(e.type){case MusicAPIResourceType.ALBUMS:Object.assign(i,{title:r.name,subtitle:r.artistName});break;case MusicAPIResourceType.ARTISTS:Object.assign(i,{title:r.name});break;case MusicAPIResourceType.MUSIC_MOVIES:Object.assign(i,{title:r.name,subtitle:r.artistName});break;case MusicAPIResourceType.PLAYLISTS:Object.assign(i,{title:r.name,subtitle:r.curatorName});break;case MusicAPIResourceType.STATIONS:{const e=true;Object.assign(i,{title:getWordMarkString(r.name),subtitle:getBroadcastRadioShowSubtitleForMusicAPIAttributes(r,e)});if(r?.kind===RadioStationKinds.DISCOVERY){Object.assign(i,{radioStationType:RadioStationKinds.DISCOVERY,subtitle:""})}break}case MusicAPIResourceType.TV_SHOWS:Object.assign(i,{title:r.name,subtitle:""});break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new ShelfItem,sharingPropertiesForMusicAPIResource(t,i),MetricsClickHandlers.baseItem)}musicCoverShelfLibraryItem(e){const t={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e),reco_id:this.recommendationMetrics?.reco_id,displayStyle:"small"};switch(e.type){case MusicAPIResourceType.LIBRARY_ALBUMS:break;case MusicAPIResourceType.LIBRARY_PLAYLISTS:break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new ShelfItem,t,MetricsClickHandlers.baseItem)}get socialProfileBadgingController(){let e=this[socialProfileBadgingControllerSymbol];if(!e){e=new SocialProfileBadgingController;this[socialProfileBadgingControllerSymbol]=e}return e}}class MusicHorizontalLockupGridController extends MusicCoverGridController{didLoad(){super.didLoad();this.onPlayActivityBound=this.onPlayActivity.bind(this);subscribe(PLAY_ACTIVITY_TOPIC,this.onPlayActivityBound)}willUnload(){super.willUnload();unsubscribe(PLAY_ACTIVITY_TOPIC,this.onPlayActivityBound)}onViewModelLoaded(){const e=get(this.personalRecommendation,"attributes.nextUpdateDate");if(e){const t=new Date(e);if(Date.now()>t){this.refreshForReason("Exceeded next update date")}}}gridSectionForPersonalRecommendation(e){const t=get(e,"relationships.contents.data");const r=this.resourceManager.itemsForResourceIdentifiers(t,this.musicCoverGridStoreItem.bind(this),this.musicCoverGridLibraryItem.bind(this));const i={items:r,uniformCellType:GridSection.UNIFORM_CELL_TYPE.FEATURED_RADIO_SHOW};const n=e.attributes;if(r.length>0){i.title=get(n,"title.stringForDisplay")}return createGridSection(i)}musicCoverGridStoreItem(e,t){const r=t.attributes;const i=true;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping personal recommendation item with id "${e.id}".`);return null}const n=identifierSetForMusicAPIResourceIdentifier(e);const o={isDirectPlayEnabled:i,onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t,null,i,n),identifierSet:n,backgroundArtwork:createArtwork({dictionary:r.artwork}),name:get(r,"name")};const s=r?.editorialVideo;if(s&&containsMotionDetailVideo(s)){o.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(s),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(s)})}switch(e.type){case MusicAPIResourceType.ALBUMS:Object.assign(o,{title:r.name,subtitle:r.artistName});break;case MusicAPIResourceType.PLAYLISTS:Object.assign(o,{title:r.name,subtitle:r.curatorName});break;case MusicAPIResourceType.STATIONS:{const e=true;const t=r?.streamingRadioSubType;const i=t==="Episode"?r?.plainEditorialNotes?.standard:"";Object.assign(o,{title:getWordMarkString(r.name),subtitle:getBroadcastRadioShowSubtitleForMusicAPIAttributes(r,e),headline:i});break}default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return Object.assign(new GridItem,sharingPropertiesForMusicAPIResource(t,o),MetricsClickHandlers.baseItem)}refreshViewModel(e){if(!e){return Promise.reject(new Error("Missing existing view model."))}const t=true;const r=new ListenNowURL(this.refreshPath,t);r.queryString.shouldIncludeLanguage=false;r.queryString.displayFilterKind=new Set([MusicAPIRecommendationDisplayKind.MUSIC_HORIZONTAL_LOCKUP_GRID]);r.queryString.addParameters({action:"refresh",meta:"vacToken","extend[playlists]":"artistNames,versionHash","extend[albums]":"versionHash"});r.queryString.extend.add("plainEditorialNotes");r.queryString.extend.add("editorialVideo");return r.string().then(e=>requestMusicAPIResource(e,{method:HTTP.METHOD.POST})).then(t=>{this.resourceManager.addResources(t.resources);const r=t.data?.[0];if(!r){return Promise.reject(new Error("Missing resource identifier for personal recommendation."))}const i=this.resourceManager.resourceForResourceIdentifier(r);if(!i){return Promise.reject(new Error("Missing resource for personal recommendation."))}this.personalRecommendation=i;const n=this.gridSectionForPersonalRecommendation(this.personalRecommendation);const o=n?[n]:[];e.sections=o})}get refreshPath(){return this.personalRecommendation.href}onPlayActivity(){this.refreshForReason("Play Activity")}}class AirTimeScheduler{constructor(e){this.airTimeMap=new Map;this.resourceTimerMap=new Map;this.onScheduleDidChange=null;this.resourceManager=e;this.watchedResourceIdentifiers=[];this.fetchAirTimeSchedulesCallback=this.fetchAirTimeSchedules.bind(this);this.forceStateLiveCallback=this.forceState.bind(this,AirTimeScheduler.Debugger.Event.FORCE_LIVE_BADGE);this.forceStateUpcommingCallback=this.forceState.bind(this,AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_BADGE);this.forceStateUpcommingWeekCallback=this.forceState.bind(this,AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_WEEK_BADGE);this.forceNoBadgeCallback=this.forceState.bind(this,AirTimeScheduler.Debugger.Event.FORCE_NO_BADGE);subscribe(AirTimeScheduler.Debugger.Event.FORCE_SCHEDULE_UPDATE,this.fetchAirTimeSchedulesCallback);subscribe(AirTimeScheduler.Debugger.Event.FORCE_LIVE_BADGE,this.forceStateLiveCallback);subscribe(AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_BADGE,this.forceStateUpcommingCallback);subscribe(AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_WEEK_BADGE,this.forceStateUpcommingWeekCallback);subscribe(AirTimeScheduler.Debugger.Event.FORCE_NO_BADGE,this.forceNoBadgeCallback)}forceState(e){this.clearTimers(this.watchedResourceIdentifiers);this.delegateScheduleDidChange(e)}delegateScheduleDidChange(e){if(this.onScheduleDidChange&&typeof this.onScheduleDidChange==="function"){this.onScheduleDidChange(e)}}removeTimer(e){const t=this.resourceTimerMap.get(e.id);t?.cancel();this.resourceTimerMap.delete(e)}setTimer(e,t){this.removeTimer(e);const r=new Timer;r.delay=t;r.onTimeout=()=>{this.removeTimer(e);this.delegateScheduleDidChange(e);this.setupTimerIfNeeded(e)};this.resourceTimerMap.set(e.id,r);r.schedule()}clearTimers(){if(Array.isArray(this.watchedResourceIdentifiers)){this.watchedResourceIdentifiers.forEach(e=>{this.removeTimer(e)})}unsubscribe(AirTimeScheduler.Debugger.Event.FORCE_SCHEDULE_UPDATE,this.fetchAirTimeSchedulesCallback);unsubscribe(AirTimeScheduler.Debugger.Event.FORCE_LIVE_BADGE,this.forceStateLiveCallback);unsubscribe(AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_BADGE,this.forceStateUpcommingCallback);unsubscribe(AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_WEEK_BADGE,this.forceStateUpcommingWeekCallback)}fetchAirTimeSchedules(){const e=this.watchedResourceIdentifiers.map(e=>e.id);if(e.length<0){return null}const t=e.join(",");const r=new MusicAPIURL("/v1/catalog/us");r.queryString.addParameters({"ids[stations]":t,"meta[stations]":"inflectionPoints"});r.queryString.extend.add("editorialCard");r.queryString.extend.add("editorialVideo");r.queryString.extend.add("plainEditorialNotes");r.queryString.extend.add("plainEditorialCard");r.string().then(e=>requestMusicAPIResource(e,{method:HTTP.METHOD.GET})).then(e=>{this.resourceManager.addResources(e.resources);e?.data?.forEach(e=>{this.updateAirTimeScheduleMap(e);this.setupTimerIfNeeded(e)});this.delegateScheduleDidChange()})}handleAirTimeResources(e=[]){if(!e||e.length===0){return null}this.watchedResourceIdentifiers=e;e.forEach(e=>{this.updateAirTimeScheduleMap(e);this.setupTimerIfNeeded(e)});this.fetchAirTimeSchedules(e)}handleAirTimeResource(e){if(this.watchedResourceIdentifiers.findIndex(t=>t.id===e.id)===-1){this.watchedResourceIdentifiers.push(e)}this.updateAirTimeScheduleMap(e)}updateAirTimeScheduleMap(e){const t=this.resourceManager.resourceForResourceIdentifier(e);const r=t?.meta?.inflectionPoints;const i=r?.points;const n=i?.[0]?.timestamp;const o=r?.start;const s=r?.end;let a;if(o&&s){a={start:o,end:s}}else{a=t?.attributes?.airTime}if(e){this.airTimeMap.set(e.id,{airTime:a,dirtyTimestamp:n})}}setupTimerIfNeeded(e){const t=this.airTimeMap.get(e.id)?.airTime;const r=Date.now();let i=new Date(t?.start);let n=new Date(t?.end);if(AirTimeScheduler.Debugger.shouldUseDebugger){i=AirTimeScheduler.Debugger.eventStartTime;n=AirTimeScheduler.Debugger.eventEndTime}const o=r-i;const s=Math.abs(o);const a=r-n;const l=Math.abs(a);if(i-r>0){this.setTimer(e,s)}if(i-r<0&&n-r>0){this.setTimer(e,l)}}checkIfUpdateIsNeeded(){if(!this.watchedResourceIdentifiers?.length){return}const e=this.watchedResourceIdentifiers;const t=Date.now();let r=0;e.forEach(e=>{const{dirtyTimestamp:i,airTime:n}=this.airTimeMap.get(e.id);const o=new Date(n?.end);const s=new Date(i);if(rt){r=s}});if(r>t){this.fetchAirTimeSchedules(e)}}}AirTimeScheduler.Debugger={forceUpdate:()=>{publish(AirTimeScheduler.Debugger.Event.FORCE_SCHEDULE_UPDATE)},forceLive:()=>{publish(AirTimeScheduler.Debugger.Event.FORCE_LIVE_BADGE)},forceUpcoming:()=>{publish(AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_BADGE)},forceUpcomingWeek:()=>{publish(AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_WEEK_BADGE)},forceNoBadge:()=>{publish(AirTimeScheduler.Debugger.Event.FORCE_NO_BADGE)},shouldUseDebugger:false,eventStartTime:Date.now()+2e4,eventEndTime:Date.now()+6e4,Event:{FORCE_SCHEDULE_UPDATE:"FORCE_SCHEDULE_UPDATE",FORCE_LIVE_BADGE:"FORCE_LIVE_BADGE",FORCE_UPCOMING_BADGE:"FORCE_UPCOMING_BADGE",FORCE_UPCOMING_WEEK_BADGE:"FORCE_UPCOMING_WEEK_BADGE",FORCE_NO_BADGE:"FORCE_NO_BADGE"}};function constructLiveScheduleDateFormatter(e,t){const r={template:e,dateStyle:DateFormattingOptions.STYLE.SHORT,timeStyle:DateFormattingOptions.STYLE.SHORT,excludedPatterns:[],uppercasedDateComponentSymbols:t};return constructDateFormatter(r)}function createPosterItem(e){return Object.assign(new PosterItem,e,MetricsClickHandlers.baseItem)}function createPosterBadgeForRadioStation(e,t){if(t===AirTimeScheduler.Debugger.Event.FORCE_NO_BADGE){return null}const r=isUsing24HourLocaleSync();let i=new Date(e?.start);let n=new Date(e?.end);if(AirTimeScheduler.Debugger.shouldUseDebugger){i=AirTimeScheduler.Debugger.eventStartTime;n=AirTimeScheduler.Debugger.eventEndTime}const o=Date.now();if(o>n){return null}else if(o>i){const e=new PosterBadge;e.badgeText=localize("FUSE.ListenNow.Module.Badge.Live");e.badgeColor=PosterBadge.BADGE_COLOR.KEY_COLOR;return e}const s=24*60*60*1e3;const a=o+30*s;const l=o+7*s;const c=o+s;const u=i.toLocaleDateString("en-US",{weekday:"long"});const d=new Date(o).toLocaleDateString("en-US",{weekday:"long"});const g=constructDateDescriptor(e?.start);const h=[];const f=isClientUsingEnglishBasedDateLocale();const p=new PosterBadge;p.badgeColor=PosterBadge.BADGE_COLOR.SYSTEM_MATERIAL;let m;if(c>i){if(u===d){m=r?"HH:mm":"h:mm a"}else{m=r?"E HH:mm":"E h:mm a";if(f){h.push(DateFormattingOptions.DATE_COMPONENT_SYMBOLS.SHORT_DAY)}}}else if(l>i){m=r?"E HH:mm":"E h:mm a";if(f){h.push(DateFormattingOptions.DATE_COMPONENT_SYMBOLS.SHORT_DAY)}}else if(a>i){m="MMM d";if(f){h.push(DateFormattingOptions.DATE_COMPONENT_SYMBOLS.SHORT_MONTH)}}switch(t){case AirTimeScheduler.Debugger.Event.FORCE_LIVE_BADGE:p.badgeText=localize("FUSE.ListenNow.Module.Badge.Live");p.badgeColor=PosterBadge.BADGE_COLOR.KEY_COLOR;m=null;break;case AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_BADGE:p.badgeColor=PosterBadge.BADGE_COLOR.SYSTEM_MATERIAL;m="h:mm a";break;case AirTimeScheduler.Debugger.Event.FORCE_UPCOMING_WEEK_BADGE:m="E h:mm a";break}if(m){const e=constructLiveScheduleDateFormatter(m,h);const t=constructValueTransformerOptions(e,"badgeText",g);p.applyValueTransformer(t)}return p}const airTimeSchedulerSymbol=Symbol("AirTimeScheduler");class MusicNotesHeroShelfController extends PersonalRecommendationController{constructor(...e){super(...e);this.resourceIdentifiersWithAirTimes=[];this.onScheduleDidChangeCallback=this.onScheduleDidChange.bind(this)}get airTimeScheduler(){if(!this[airTimeSchedulerSymbol]){this[airTimeSchedulerSymbol]=new AirTimeScheduler(this.resourceManager);this[airTimeSchedulerSymbol].onScheduleDidChange=this.onScheduleDidChangeCallback}return this[airTimeSchedulerSymbol]}loadViewModel(){const e=this.personalRecommendation.attributes;const t=get(e,"title.stringForDisplay");const r=this.shelfSectionsForPersonalRecommendation(this.personalRecommendation);if(!r||r.count===0){return null}const i={title:t,sections:r,editorialID:this.personalRecommendation?.id};Object.assign(i,metricsPropertiesForPersonalRecommendation(this.personalRecommendation));return createShelf(i)}onViewModelLoaded(){if(this.hasAirTimeResources){this.airTimeScheduler.fetchAirTimeSchedules()}}shelfSectionsForPersonalRecommendation(e){const t=get(e,"relationships.contents.data");const r=this.resourceManager.itemsForResourceIdentifiers(t,this.musicNotesHeroShelfItem.bind(this));if(r.length===0){return null}return r.map(e=>createShelfSection({items:[e],uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.POSTER,title:e.sectionTitle}))}playlistItemProperties(e){const t=e.isChart;const r=e.playlistType;const i=["personal-mix","replay"];const n=e.artistNames;if(t||i.indexOf(r)!==-1){const t={altText:e.name};if(n){t.description=n}return t}return{title:e.name,subtitle:get(e,"plainEditorialNotes.short")??e.curatorName}}musicNotesHeroShelfItem(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping personal recommendation item with id "${e.id}".`);return null}const i=get(e,"meta.reason.stringForDisplay");const n=createArtwork({dictionary:r.artwork});const o=this.createEditorialProperties(e,t);let s;const a=get(this,"recommendationMetrics.reco_id");let l;if(t.type===MusicAPIResourceType.STATIONS){const t=this.airTimeScheduler.airTimeMap.get(e.id)?.airTime??r.airTime;if(t){l=createPosterBadgeForRadioStation(t,this.forcedState)}if(r.supportsAirTimeUpdates){this.hasAirTimeResources=true;this.airTimeScheduler.handleAirTimeResource(e)}}if(o){const e=sharingPropertiesForMusicAPIResource(t,o);const i=createPosterItem(Object.assign(e,{reco_id:a}));if(l){i.posterBadge=l}if(r.name){i.name=r.name}return i}if(e.type!==MusicAPIResourceType.EDITORIAL_ITEMS){s=identifierSetForMusicAPIResourceIdentifier(e)}const c=l?.badgeText??null;const u=this.createVideoProperties(e,t);const d=Object.assign({backgroundArtwork:n,resourceIdentifier:e,identifierSet:s,isChinEnabled:true,isGradientEnabled:false,overlayTitle:c,sectionTitle:i,reco_id:a,displayStyle:"large",name:r.name,onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t)},u);let g;if(l){d.posterBadge=l}if(r.releaseDate){const e=Date.now()-24*60*60*1e3;const t=new Date(r.releaseDate);const i=localizedYearStringFromReleaseDate(r.releaseDate);const n=localizedMonthDayStringFromReleaseDate(r.releaseDate);g=t0){const e=createVideoArtwork({dictionary:excludeMotionDetailVideo(o),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});s={videoBackgroundArtwork:e};if(containsMotionDetailVideo(o)){s.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(o),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(o)})}}return s}createEditorialProperties(e,t){const r=t?.attributes;const i=e?.meta?.editorialCard;const n=r?.plainEditorialCard?.[i];if(n){const r=n.editorialArtwork||{};const i=n.display?.decorations||[];const o=r.superHeroTall;if(!o){logger$5.warn(`resource missing tall artwork for super hero, ${e.type} ${e.id} for item.`);return null}const s=n?.plainEditorialNotes?.short;const a=!!i.find(e=>e==="gradient");const l=createArtwork({dictionary:o,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});const c=this.createVideoProperties(e,t);const u=e?.meta?.reason?.stringForDisplay??n.plainEditorialNotes?.tagline;let d;if(e.type!==MusicAPIResourceType.EDITORIAL_ITEMS){d=identifierSetForMusicAPIResourceIdentifier(e)}const g=n?.title;const h=n?.subtitle;return Object.assign({backgroundArtwork:l,identifierSet:d,isChinEnabled:n.kind!=="musicSuperHero",isGradientEnabled:a,isPlayButtonEnabled:false,description:s,onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),sectionTitle:u,resourceIdentifier:e,overlayTitle:g,overlaySubtitle:h},c)}}refreshViewModel(e){const t=e;const r=e?.sections;const i=r.map(e=>e?.items?.[0]?.resourceIdentifier);const n=i.map(e=>{const t=this.resourceManager.resourceForResourceIdentifier(e);const r=this.musicNotesHeroShelfItem(e,t);return createShelfSection({items:[r],uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.POSTER,title:r.sectionTitle})});t.sections=n;return Promise.resolve(t)}didAppear(){if(this.hasAirTimeResources){this.airTimeScheduler.checkIfUpdateIsNeeded()}}willUnload(){if(this.hasAirTimeResources){this.airTimeScheduler.clearTimers()}}onScheduleDidChange(e){this.forcedState=e;if(this.hasAirTimeResources){this.refreshForReason("Air Time has changed")}}}const airTimeSchedulerSymbol$1=Symbol("AirTimeScheduler");class MusicSuperHeroShelfController extends PersonalRecommendationController{constructor(...e){super(...e);this.resourceIdentifiersWithAirTimes=[];this.onScheduleDidChangeCallback=this.onScheduleDidChange.bind(this)}get airTimeScheduler(){if(!this[airTimeSchedulerSymbol$1]){this[airTimeSchedulerSymbol$1]=new AirTimeScheduler(this.resourceManager);this[airTimeSchedulerSymbol$1].onScheduleDidChange=this.onScheduleDidChangeCallback}return this[airTimeSchedulerSymbol$1]}loadViewModel(){const e=this.gridSectionForPersonalRecommendation(this.personalRecommendation);if(!e){return null}const t={sections:[e]};Object.assign(t,metricsPropertiesForPersonalRecommendation(this.personalRecommendation));return createGrid(t)}onViewModelLoaded(){if(this.hasAirTimeResources){this.airTimeScheduler.fetchAirTimeSchedules()}}gridSectionForPersonalRecommendation(e){const t=get(e,"relationships.contents.data");const r=this.resourceManager.itemsForResourceIdentifiers(t,this.musicSuperHeroItem.bind(this));if(r.length===0){return null}const i=get(e,"attributes.title.stringForDisplay")??get(r,"[0].sectionTitle");return createGridSection({items:r,title:i,uniformCellType:GridSection.UNIFORM_CELL_TYPE.HERO})}musicSuperHeroItem(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping personal recommendation item with id "${e.id}".`);return null}const i=get(e,"meta.editorialCard");const n=get(r,["plainEditorialCard",i]);const o=get(n,"plainEditorialNotes.short");const s=get(n,"editorialArtwork");const a=onSelectHandlerForMusicAPIResourceIdentifier(e,t);const l=get(n,"display.decorations",[]);const c=!!l.find(e=>e==="gradient");if(!s){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing editorial artwork, dropping personal recommendation item with id "${e.id}".`);return null}if(!s.superHeroTall||!s.superHeroWide){logger$5.warn(`${this.constructor.name}: resource missing tall artwork for super hero, ${e.type} ${e.id} for item.`);return null}const u=createArtwork({dictionary:s.superHeroTall,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});const d=createArtwork({dictionary:s.superHeroWide,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});const g=s.superHeroTall.alt??s.superHeroWide.alt;let h;if(t.type===MusicAPIResourceType.STATIONS){const t=this.airTimeScheduler.airTimeMap.get(e.id)?.airTime??r.airTime;if(t){h=createPosterBadgeForRadioStation(t,this.forcedState)}if(r.supportsAirTimeUpdates){this.hasAirTimeResources=true;this.airTimeScheduler.handleAirTimeResource(e)}}const f=h?.badgeText??null;const p={identifierSet:identifierSetForMusicAPIResourceIdentifier(e),resourceIdentifier:e,editorialArtwork:d,backgroundArtwork:u,isGradientEnabled:c,overlaySubtitle:f,description:o,onSelect:a,sectionTitle:get(n,"plainEditorialNotes.tagline"),reco_id:get(this,"recommendationMetrics.reco_id"),displayStyle:"large",name:r.name,altText:g};if(h){p.posterBadge=h}const m=get(n,"editorialVideo")??get(r,"editorialVideo");if(get(r,"link.feature")==="onboarding-bubbles"){p.overlayTitle=get(n,"plainEditorialNotes.name");p.onSelect=()=>createPresentationSegue({componentController:new OnboardingController})}if(m){p.videoBackgroundArtwork=createVideoArtwork({dictionary:excludeMotionDetailVideo(m),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});if(containsMotionDetailVideo(m)){p.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(m),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(m)})}}return createPosterItem(p)}refreshViewModel(e){const t=e;const r=e?.sections?.[0];const i=r?.items?.[0]?.resourceIdentifier;const n=this.resourceManager.resourceForResourceIdentifier(i);const o=n?.attributes?.airTime;const s=r?.title;if(o){const e=this.musicSuperHeroItem(i,n);const r=createGridSection({items:[e],title:s,uniformCellType:GridSection.UNIFORM_CELL_TYPE.HERO});t.sections=[r]}return Promise.resolve(t)}didAppear(){if(this.hasAirTimeResources){this.airTimeScheduler.checkIfUpdateIsNeeded()}}willUnload(){if(this.hasAirTimeResources){this.airTimeScheduler.clearTimers()}}onScheduleDidChange(e){this.forcedState=e;if(this.hasAirTimeResources){this.refreshForReason("Air Time has changed")}}}class MusicCardShelfController extends MusicNotesHeroShelfController{musicNotesHeroShelfItem(e,t){const r=t.attributes;if(!r){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping personal recommendation item with id "${e.id}".`);return null}const i=e?.meta?.utterance?.stringForDisplay;const n=e?.meta?.reason?.stringForDisplay;const o=createArtwork({dictionary:r.artwork});const s=this.createEditorialProperties(e,t);let a;const l=this.recommendationMetrics?.reco_id;if(s){const e=sharingPropertiesForMusicAPIResource(t,s);const r=createPosterItem(Object.assign(e,{reco_id:l}));return r}if(e.type!==MusicAPIResourceType.EDITORIAL_ITEMS){a=identifierSetForMusicAPIResourceIdentifier(e)}const c=this.createVideoProperties(e,t);const u=true;const d=Object.assign({backgroundArtwork:o,resourceIdentifier:e,identifierSet:a,sectionTitle:n,isDirectPlayEnabled:u,isChinEnabled:true,isGradientEnabled:false,reco_id:l,displayStyle:"large",name:r.name,onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t,null,u,a)},c);switch(e.type){case MusicAPIResourceType.ALBUMS:case MusicAPIResourceType.PLAYLISTS:case MusicAPIResourceType.STATIONS:Object.assign(d,{title:i});break;default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`);return null}return createPosterItem(Object.assign(sharingPropertiesForMusicAPIResource(t,d),{textAlignment:"left"}))}}const shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol=Symbol("shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol");class RecentlyPlayedShelfController extends MusicCoverShelfController{didLoad(){super.didLoad();this.onPlayActivityBound=this.onPlayActivity.bind(this);subscribe(PLAY_ACTIVITY_TOPIC,this.onPlayActivityBound)}willUnload(){super.willUnload();unsubscribe(PLAY_ACTIVITY_TOPIC,this.onPlayActivityBound)}onViewModelLoaded(){const e=get(this.personalRecommendation,"attributes.nextUpdateDate");if(e){const t=new Date(e);if(Date.now()>t){this.refreshForReason("Exceeded next update date")}}}containerDetailLinkForSeeAllURL(e,t,r){const i=createContainerDetailLink({URL:e,title:t,recommendationId:r,onSelect:()=>{const i=this.shouldIgnoreCacheWhenRequestingSeeAllResource;this.shouldIgnoreCacheWhenRequestingSeeAllResource=false;return createPushSegue({componentController:new ListenNowSeeAllController({URL:e,title:t,shouldInvalidateCachedPageResource:i,recommendationId:r})})}});return Object.assign(i,MetricsClickHandlers.containerDetailLink,{title:t,recommendationId:r})}onPlayActivity(){this.shouldIgnoreCacheWhenRequestingSeeAllResource=true;this.refreshForReason("Play Activity")}get shouldIgnoreCacheWhenRequestingSeeAllResource(){return this[shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol]}set shouldIgnoreCacheWhenRequestingSeeAllResource(e){this[shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol]=e}}const shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol$1=Symbol("shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol");class ArtistFavoritesShelfController extends MusicCoverShelfController{didLoad(){super.didLoad();this.onFavoriteActivityBound=this.onFavoriteActivity.bind(this);subscribe(FAVORITING_ACTIVITY_TOPIC,this.onFavoriteActivityBound)}willUnload(){super.willUnload();unsubscribe(FAVORITING_ACTIVITY_TOPIC,this.onFavoriteActivityBound)}onViewModelLoaded(){const e=this.personalRecommendation.attributes?.nextUpdateDate;if(e){const t=new Date(e);if(Date.now()>t){this.refreshForReason("Exceeded next update date")}}}refreshViewModel(e){const t=e;if(!t){return Promise.reject(new Error("Missing existing view model."))}const r=new ListenNowURL(this.refreshPath);r.queryString.shouldIncludeLanguage=false;r.queryString.displayFilterKind=new Set([MusicAPIRecommendationDisplayKind.MUSIC_CIRCLE_COVER_SHELF]);r.queryString.addParameters({action:"refresh"});return r.string().then(e=>requestMusicAPIResource(e,{method:HTTP.METHOD.POST})).then(e=>{this.resourceManager.addResources(e.resources);const r=e.data?.[0];if(!r){return Promise.reject(new Error("Missing resource identifier for personal recommendation."))}const i=this.resourceManager.resourceForResourceIdentifier(r);if(!i){return Promise.reject(new Error("Missing resource for personal recommendation."))}this.personalRecommendation=i;const n=this.shelfSectionForPersonalRecommendation(this.personalRecommendation);const o=n?[n]:[];t.sections=o;const s=this.accessoryButtonPropertiesForPersonalRecommendation(this.personalRecommendation);if(s){Object.assign(t,s)}})}containerDetailLinkForSeeAllURL(e,t,r){const i=createContainerDetailLink({URL:e,title:t,recommendationId:r,onSelect:()=>{const i=true;return createPushSegue({componentController:new ListenNowSeeAllController({URL:e,title:t,shouldInvalidateCachedPageResource:i,recommendationId:r})})}});return Object.assign(i,MetricsClickHandlers.containerDetailLink,{title:t,recommendationId:r})}onFavoriteActivity(){this.shouldIgnoreCacheWhenRequestingSeeAllResource=true;this.refreshForReason("Favorite Activity")}get shouldIgnoreCacheWhenRequestingSeeAllResource(){return this[shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol$1]}set shouldIgnoreCacheWhenRequestingSeeAllResource(e){this[shouldIgnoreCacheWhenRequestingSeeAllResourceSymbol$1]=e}}class SharedWithYouController extends PersonalRecommendationController{loadViewModel(){const e=new InterstellarViewModel;Object.assign(e,metricsPropertiesForPersonalRecommendation(this.personalRecommendation));return e}}const PROMPT={CARRIER_BUNDLING_LINKAGE_REQUIRED:"carrierBundlingLinkageRequired",LOGIN_REQUIRED:"loginRequired",ONBOARDING_REQUIRED:"onboardingRequired",SUBSCRIPTION_REQUIRED_TRIAL_ELIGIBLE:"subscriptionRequiredTrialEligible",SUBSCRIPTION_REQUIRED_TRIAL_NOT_ELIGIBLE:"subscriptionRequiredTrialNotEligible"};class ListenNowPromptController extends ContainerChildController{constructor(e){super();this.prompt=e}loadViewModel(){return waitForLocInitialization().then(()=>{const e=this.viewModelPropertiesForPrompt(this.prompt);if(!e){return}const{paragraphProperties:t,gridItemButtonProperties:r}=e;return[createParagraph(t),createGrid({sections:[createGridSection({items:[createGridItemButton(r)]})]})]})}viewModelPropertiesForPrompt(e){const t={};const r={};switch(e){case ListenNowPromptController.PROMPT.SUBSCRIPTION_REQUIRED_TRIAL_NOT_ELIGIBLE:Object.assign(t,{title:localize("FUSE.ForYou.NotSubscribed.NonTrial.Header"),text:localize("FUSE.ForYou.NotSubscribed.NonTrial.Description")});Object.assign(r,{title:localize("FUSE.ForYou.NotSubscribed.NonTrial.CTA"),onSelect:()=>createSegueToFinanceSync("subscriptionoffers","",{reason:"ForYouCTA"})});break;case ListenNowPromptController.PROMPT.CARRIER_BUNDLING_LINKAGE_REQUIRED:Object.assign(t,{title:localize("FUSE.CarrierBundling.UnlinkedForYou.Header"),text:localize("FUSE.CarrierBundling.UnlinkedForYou.Subheader")});Object.assign(r,{title:localize("FUSE.CarrierBilling.LinkToAppleID.Title"),onSelect:()=>createSegueToFinanceSync("carrierAccountLinking")});break;case ListenNowPromptController.PROMPT.ONBOARDING_REQUIRED:Object.assign(t,{title:localize("FUSE.Upsell.Onboard.Header"),text:localize("FUSE.Upsell.Onboard.Description")});Object.assign(r,{title:localize("FUSE.Upsell.Onboard.CTA"),onSelect:()=>createPresentationSegue({componentController:new OnboardingController})});break;case ListenNowPromptController.PROMPT.LOGIN_REQUIRED:case ListenNowPromptController.PROMPT.SUBSCRIPTION_REQUIRED_TRIAL_ELIGIBLE:Object.assign(t,{title:localize("FUSE.ForYou.NotSubscribed.FreeTrial.Header"),text:localize("FUSE.ForYou.NotSubscribed.FreeTrial.Description")});Object.assign(r,{title:localize("FUSE.ForYou.NotSubscribed.FreeTrial.CTA"),onSelect:()=>createSegueToFinanceSync("subscriptionoffers","",{reason:"ForYouCTA"})});break;default:logger$5.error(`${this.constructor.name} invalid ListenNowPromptController.PROMPT`,e);return null}return{paragraphProperties:t,gridItemButtonProperties:r}}}ListenNowPromptController.PROMPT=PROMPT;function childViewModelsFromChildControllers(e){const t=e.map(e=>e.loadedViewModel);return Promise.all(t).then(e=>{const t=[];e.forEach(e=>{if(Array.isArray(e)){t.push(...e)}else if(e){t.push(e)}});return t})}function verticalStackFromChildControllers(e){return childViewModelsFromChildControllers(e).then(e=>createVerticalStack({childViewModels:e}))}let sharedContactsDerivedRecommendedFriendsManager;const recommendedFriendsSymbol=Symbol("recommendedFriends");const expirationDateSymbol=Symbol("expirationDate");class RecommendedFriendsCache{constructor(e,t){this[recommendedFriendsSymbol]=e;this[expirationDateSymbol]=t}get recommendedFriends(){return this[recommendedFriendsSymbol]}get expirationDate(){return this[expirationDateSymbol]}get isExpired(){return this.expirationDate&&Date.now()>this.expirationDate}get isEmpty(){return get(this.recommendedFriends,"results.recommendedFriends",[]).length===0}}const recommendedFriendsCacheSymbol=Symbol("recommendedFriendsCache");class ContactsDerivedRecommendedFriendsManager{constructor(){subscribe(USER_FOLLOWEES_DID_CHANGE,()=>{this.clearRecommendedFriendsCacheForReason("User followees did change")});subscribe(USER_REMOVED_RECOMMENDED_FRIEND,()=>{this.clearRecommendedFriendsCacheForReason("User removed recommended friend")})}static get shared(){if(!sharedContactsDerivedRecommendedFriendsManager){sharedContactsDerivedRecommendedFriendsManager=new ContactsDerivedRecommendedFriendsManager}return sharedContactsDerivedRecommendedFriendsManager}hasUserConsented(){return getUserProfile().then(e=>e.isContactsCheckAllowed).catch(e=>{logger$5.error(`${this.constructor.name}: Failed to get user profile for user contacts consent check.`,e);return false})}fetchRecommendedFriends(){if(this.isRecommendedFriendsCached){return Promise.resolve(this.recommendedFriendsCache.recommendedFriends)}return getFriendsDiscoverySocialProfileIDs().then((e=[])=>{if(e.length===0){return Promise.resolve()}return socialRequests.musicAPIRecommendedFriendsPOST(e).then(e=>{this.cacheRecommendedFriends(e?.body,e.expirationDate);return e})}).catch(e=>logger$5.error(`${this.constructor.name}: Failed to fetch recommended friends.`,e))}cacheRecommendedFriends(e,t=new Date(Date.now()+24*60*60*1e3)){this.recommendedFriendsCache=new RecommendedFriendsCache(e,t)}clearRecommendedFriendsCacheForReason(e){logger$5.log(`${this.constructor.name} clearing recommended friends cache for reason "${e}".`);this.recommendedFriendsCache=null}get recommendedFriendsCache(){return this[recommendedFriendsCacheSymbol]}set recommendedFriendsCache(e){this[recommendedFriendsCacheSymbol]=e}get isRecommendedFriendsCached(){return this.recommendedFriendsCache&&!this.recommendedFriendsCache.isExpired&&!this.recommendedFriendsCache.isEmpty}}class RecommendedFriendsShelfController extends PersonalRecommendationController{loadViewModel(){const e=get(this,"environment.mediaPickerEnvironment");if(e){return null}const t=this.personalRecommendation.attributes;const r=get(t,"title.stringForDisplay");const i=this.shelfSectionForPersonalRecommendation(this.personalRecommendation);if(!i){return null}const n={title:r,sections:[i]};return createShelf(n)}onViewModelLoaded(){this.refreshWithContactsDerivedRecommendedFriendsIfNeeded()}refreshViewModel(e){const t=e;const r=get(t,"sections[0]");if(!r){return Promise.reject(new Error("Missing existing view model."))}return ContactsDerivedRecommendedFriendsManager.shared.fetchRecommendedFriends().then(e=>{const i=get(e,"results.recommendedFriends");if(!i||i.length===0){return}this.personalRecommendation=undefined;this.resourceManager.addResources(e.resources);const n=this.resourceManager.itemsForResourceIdentifiers(i,this.shelfItem.bind(this));if(!n){return}r.items=n;t.sections=[r]})}shelfSectionForPersonalRecommendation(e){const t=get(e,"relationships.contents.data");const r=this.resourceManager.itemsForResourceIdentifiers(t,this.shelfItem.bind(this));if(r.length===0){return null}return createShelfSection({items:r,uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.SOCIAL_PERSON_CARD})}shelfItem(e,t){switch(e.type){case MusicAPIResourceType.SOCIAL_PROFILES:return this.recommendedFriendShelfItem(e,t);case MusicAPIResourceType.SOCIAL_UPSELLS:return this.findMoreFriendsUpsellShelfItem(e,t);default:logger$5.warn(`${this.constructor.name}: "${e.type}" resource type unsupported, dropping shelf item with id "${e.id}".`);return null}}recommendedFriendShelfItem(e,t){const r=identifierSetForMusicAPIResourceIdentifier(e);if(!r){return null}const i=t.attributes;if(!i){logger$5.warn(`${this.constructor.name}: "${e.type}" resource missing attributes, dropping personal recommendation item with id "${e.id}".`);return null}let n=get(e,"meta.reason.stringForDisplay");if(!n){const e=get(i,"topGenreNames");if(e&&e.length>0){n=e.join(", ")}}const o={subtitle:n,identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t),onCloseButtonSelectionPerformed:e=>{const t=get(e,"identifierSet.socialProfileID");if(!t){return}this.removeRecommendedFriendWithSocialProfileID(t)},reco_id:get(this,"recommendationMetrics.reco_id"),displayStyle:"small"};return Object.assign(new ShelfItem,o,MetricsClickHandlers.baseItem)}findMoreFriendsUpsellShelfItem(e,t){const r={title:t?.meta?.reason?.stringForDisplay??e?.meta?.reason?.stringForDisplay,buttonText:get(t,"attributes.action"),backgroundArtwork:createArtwork({dictionary:get(t,"attributes.artwork")}),onSelect:()=>createPresentationSegue({componentController:new FriendsProfileController({isEditing:true})}),reco_id:get(this,"recommendationMetrics.reco_id"),displayStyle:"small"};return Object.assign(new ShelfItem,r,MetricsClickHandlers.baseItem)}refreshWithContactsDerivedRecommendedFriendsIfNeeded(){const e=get(this,"environment.mediaPickerEnvironment");if(e){return null}ContactsDerivedRecommendedFriendsManager.shared.hasUserConsented().then(e=>{if(e){this.refreshForReason("Contacts derived recommended friends")}})}removeRecommendedFriendWithSocialProfileID(e){removeRecommendedFriend(e);this.loadedViewModel.then(t=>{const r=get(t,"sections[0]");if(!r){return Promise.reject(new Error("Missing existing view model."))}const i=r.items.filter(t=>{const r=get(t,"identifierSet.socialProfileID");return!r||r!==e});r.items=i;t.sections=[r]}).catch(e=>logger$5.error("Couldn't remove recommended friend from view model",e))}}let sharedBackgroundFetchController;class BackgroundFetchController{static get shared(){if(!sharedBackgroundFetchController){sharedBackgroundFetchController=new BackgroundFetchController}return sharedBackgroundFetchController}registerIdentifierForURL(e,t){if(BackgroundFetchManager){BackgroundFetchManager.register(e,t)}}registerIdentifierWithPromisedURL(e,t){t.then(t=>this.registerIdentifierForURL(e,t)).catch(t=>logger$5.error(`${this.constructor.name}: Couldn't register identifer "${e}" for URL.`,t))}removeURLWithIdentifier(e){if(BackgroundFetchManager){BackgroundFetchManager.remove(e)}}removeAll(){if(BackgroundFetchManager){BackgroundFetchManager.removeAll()}}}BackgroundFetchController.URL_IDENTIFIERS={RECOMMENDATIONS_LISTEN_NOW:"recommendationsListenNow",RECOMMENDATIONS_SEARCH_LANDING:"recommendationsSearchLanding"};function createInlineSocialUpsell(e){return Object.assign(new InlineSocialUpsell,e)}function createSegueToShortenedSocialOnboarding(e=(()=>{})){e(createPresentationSegue({componentController:new HandleProfileController({isDismissable:true})}))}function shouldDisplayInlineSocialUpsell(e){const t=Storage.getItem(StorageKeys.User.LAST_DISMISSED_INLINE_SOCIAL_UPSELL_BANNER_VERSION);const r=get(e,"attributes.version",0);return!t||r>t}function createUpsellSocialOnboardingRow({resource:e={},onCloseButtonSelectionPerformed:t}){if(!canSocialOnboardSync()){return null}const r=e.attributes;if(!r){logger$5.warn("MusicUpsellShelfController: resource missing attributes");return null}if(!shouldDisplayInlineSocialUpsell(e)){return null}const recordCloseClickMetrics=(e,t)=>{const r={actionType:"dismiss",actionContext:"FriendsForYouCTA",targetId:"DismissX"};recordClickEvent(...clickMetricsForImpressions(e,t,r))};const storeForPersistantRemoval=()=>{const t=get(e,"attributes.version");Storage.setItem(StorageKeys.User.LAST_DISMISSED_INLINE_SOCIAL_UPSELL_BANNER_VERSION,t||1)};const i=get(e,"attributes.artwork",{});return createInlineSocialUpsell({title:get(e,"attributes.title",""),artwork:createArtwork({dictionary:i}),primaryButtonTitle:get(e,"attributes.action"),onPrimaryButtonSelectionPerformed:createSegueToShortenedSocialOnboarding,onCloseButtonSelectionPerformed:(e,r)=>{storeForPersistantRemoval();recordCloseClickMetrics(e,r);if(typeof t==="function"){t(e,r)}}})}class MusicUpsellShelfController extends PersonalRecommendationController{loadViewModel(){const e=get(this,"environment.mediaPickerEnvironment");if(e){return null}const t=get(this,"personalRecommendation.relationships.contents.data[0]");if(!t){logger$5.warn(`${this.constructor.name}: Missing resource identifier for personal recommendation child.`);return}const r=this.resourceManager.resourceForResourceIdentifier(t);const onCloseButtonSelectionPerformed=()=>{this.loadedViewModel=null};return createUpsellSocialOnboardingRow({resource:r,onCloseButtonSelectionPerformed:onCloseButtonSelectionPerformed})}}function createListenNowMusicSiriUpsell(e){return Object.assign(new ListenNowMusicSiriUpsell,MetricsClickHandlers.listenNowMusicSiriUpsell,e)}class MarketingItemController extends ContainerChildController{constructor(e){super();this.marketingItem=e}loadViewModel(){const e=this.marketingItem?.attributes?.placement;if(e==="musicListenNowBanner"){return this.musicSiriUpsellForMarketingItem(this.marketingItem)}const t=this.gridSectionForMarketingItem(this.marketingItem);if(!t){return null}const r={sections:[t]};return createGrid(r)}gridSectionForMarketingItem(e){const t=[this.superHeroItemForMarketingItem(e)];const r=e.attributes?.header;return createGridSection({items:t,uniformCellType:GridSection.UNIFORM_CELL_TYPE.HERO,title:r})}superHeroItemForMarketingItem(e){const t=e.attributes;const r=get(t,"title");const i=get(t,"offers[0]");const n=get(i,"callToActionLabel");const o=get(t,"marketingArtwork");const s=createArtwork({dictionary:get(o,"superHeroTall"),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});const a=get(e,"meta.metrics");const l=get(i,"metrics.adamId");const c=t?.subtitle;const u=!!n;let d={impressions:{name:r,id:l,kind:"upsell",marketing:{marketingItemId:get(a,["marketing.marketingItemId"]),offerDecisionId:get(a,["marketing.offerDecisionId"])}}};d=addAdditionalMarketingItemMetrics(d,e?.meta?.metrics);const g=createArtwork({dictionary:get(o,"superHeroWide"),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE});const h=onSelectHandlerForMarketingOffer(i);const f={editorialArtwork:g,backgroundArtwork:s,isGradientEnabled:false,isChinEnabled:false,isPlayButtonEnabled:false,title:n,overlayTitle:r,subtitle:c,onSelect:h,metrics:d,isTitleChevronEnabled:u};const p=createPosterItem(f);if(h){const e=i?.buyParams;addClickMetricsHandlerToItem(p,()=>({targetId:l,actionType:e?"buy":"navigate",actionDetails:e?{buyParams:i.buyParams}:{}}))}return p}musicSiriUpsellForMarketingItem(e){const t=e.attributes;const r=t?.title;const i=t?.offers[0];const n=i?.callToActionLabel;const o=e?.meta?.metrics;const s=i?.metrics?.adamId;const a=t?.title;const l=t?.subtitle;const c={impressions:{name:r,id:s,impressionType:"banner",kind:"upsell",marketing:{marketingItemId:o?.marketing?.marketingItemId,offerDecisionId:o?.marketing?.offerDecisionId}}};const u=onSelectHandlerForMarketingOffer(i);const d={title:a,subtitle:l,onSelect:u,buttonTitle:n,metrics:c};const g=createListenNowMusicSiriUpsell(d);if(u){const e=i?.buyParams;addClickMetricsHandlerToItem(g,()=>({targetId:s,actionType:e?"buy":"navigate",actionDetails:e?{buyParams:i.buyParams}:{}}))}return g}}const pageMetricsControllerSymbol$2=Symbol("pageMetricsController");const URLPromiseSymbol=Symbol("URLPromise");const metricsPageFieldsSymbol=Symbol("metricsPageFields");const socialProfileBadgingControllerSymbol$1=Symbol("socialProfileBadgingController");const BaseClass$p=mix(ContainerChildController).with(RequestDrivenControllerMixin,MusicAPIRequestDrivenControllerMixin);class ListenNowRecommendationsController extends BaseClass$p{constructor(e,t=false,r,i={pageType:"ListenNow",pageId:"ListenNowLanding",pageContext:"ListenNow"}){super();this.willAppearRefresh=r;this.URLPromise=e;this.metricsPageFields=i;if(t){this.invalidateCachedPageResource()}this.shouldPrioritizeRequest=true}get URLPromise(){return this[URLPromiseSymbol]}set URLPromise(e){this[URLPromiseSymbol]=e}get metricsPageFields(){return this[metricsPageFieldsSymbol]}set metricsPageFields(e){this[metricsPageFieldsSymbol]=e}onChildLoadedViewModelChanged(){Promise.all([childViewModelsFromChildControllers(this.childControllers),this.loadedViewModel]).then(([e,t])=>{if(t&&t instanceof VerticalStack){const r=t;r.childViewModels=e}else{this.loadedViewModel=createVerticalStack({childViewModels:e})}})}didLoad(){super.didLoad();this.onOnboardingCompleteBound=this.onOnboardingComplete.bind(this);subscribe(ONBOARD_COMPLETE,this.onOnboardingCompleteBound);this.onSocialOnboardingStatusChangeBound=this.onSocialOnboardingStatusChange.bind(this);subscribe(USER_SOCIAL_ONBOARDING_STATUS_CHANGED,this.onSocialOnboardingStatusChangeBound)}willUnload(){super.willUnload();unsubscribe(ONBOARD_COMPLETE,this.onOnboardingCompleteBound);unsubscribe(USER_SOCIAL_ONBOARDING_STATUS_CHANGED,this.onSocialOnboardingStatusChangeBound)}URL(){return this.URLPromise}get shouldAutomaticalyRefreshAfterResponseExpiration(){return true}viewModelForPageResponse(e){this.updateContainerChildControllersForPageResponse(e);return verticalStackFromChildControllers(this.childControllers)}refreshViewModelForPageResponse(e,t){this.updateContainerChildControllersForPageResponse(t);return childViewModelsFromChildControllers(this.childControllers).then(t=>{if(e&&e instanceof VerticalStack){const r=e;r.childViewModels=t}else{this.loadedViewModel=createVerticalStack({childViewModels:t})}})}updatePageMetricsForPageResponse(e,t,r){const i=t;super.updatePageMetricsForPageResponse(e,t,r);if(get(e,"meta.account")==="OnboardingRequired"){this.pageMetricsController.pageFields={pageType:"Prompt",pageId:"ListenNowWelcome"}}else{this.metricsPageFields.pageUrl=i;this.pageMetricsController.pageFields=this.metricsPageFields}}decorateViewModel(e){return this.socialProfileBadgingController.badgeViewModel(e,true)}get pageMetricsController(){return this[pageMetricsControllerSymbol$2]}set pageMetricsController(e){this[pageMetricsControllerSymbol$2]=e}willAppear(e){if(this.willAppearRefresh){super.willAppear(e);if(this.shouldAutomaticalyRefreshAfterResponseExpiration&&this.responseExpirationDate&&Date.now()>this.responseExpirationDate){this.refreshForReason("Response expired. Refresh on willAppear")}}}updateContainerChildControllersForPageResponse(e){if(get(e,"meta.account")==="OnboardingRequired"){this.updateControllersForOnboarding()}else{BackgroundFetchController.shared.registerIdentifierWithPromisedURL(BackgroundFetchController.URL_IDENTIFIERS.RECOMMENDATIONS_LISTEN_NOW,this.URL());this.updatePersonalRecommendationControllersForPageResponse(e)}}updateControllersForOnboarding(){const e=this.removeChildControllers();const t=e&&e[0];if(t instanceof ListenNowPromptController&&t.prompt===ListenNowPromptController.PROMPT.ONBOARDING_REQUIRED){this.addChildController(t)}else{this.addChildController(new ListenNowPromptController(ListenNowPromptController.PROMPT.ONBOARDING_REQUIRED))}}updatePersonalRecommendationControllersForPageResponse(e){const t=this.removeChildControllers();const r=e.data;if(!r||r.length===0){throw new Error("Listen Now response missing recommendation resource identifiers.")}let i;if(t){i={};t.forEach(e=>{const t=e.uniqueIdentifier;if(t){i[t]=e}})}const childControllerCreationFunction=(e,t)=>this.childViewModelControllerForPersonalRecommendation(e,t,i);this.resourceManager.itemsForResourceIdentifiers(r,childControllerCreationFunction).forEach(this.addChildController.bind(this))}childViewModelControllerForPersonalRecommendation(e,t,r){const i=get(t,"meta.metrics.reco_id");if(r&&i){const e=r[i];if(e){return e}}const n=t.attributes;const o=get(n,"display.kind");const s=get(n,"kind");const a=t.type;if(s==="shared-with-you"){return new SharedWithYouController({},t)}if(a==="marketing-items"){const e=t;return new MarketingItemController(e)}const l=get(t,"attributes.isGroupRecommendation");if(l){return new MusicCoverGridController(this.resourceManager.resources,t)}switch(o){case MusicAPIRecommendationDisplayKind.MUSIC_CIRCLE_COVER_SHELF:if(s==="your-favorites"){return new ArtistFavoritesShelfController(this.resourceManager.resources,t)}return new MusicCoverShelfController(this.resourceManager.resources,t);case MusicAPIRecommendationDisplayKind.MUSIC_COVER_SHELF:{if(s==="recently-played"){return new RecentlyPlayedShelfController(this.resourceManager.resources,t)}return new MusicCoverShelfController(this.resourceManager.resources,t)}case MusicAPIRecommendationDisplayKind.MUSIC_HORIZONTAL_LOCKUP_GRID:return new MusicHorizontalLockupGridController(this.resourceManager.resources,t);case MusicAPIRecommendationDisplayKind.MUSIC_NOTES_HERO_SHELF:return new MusicNotesHeroShelfController(this.resourceManager.resources,t);case MusicAPIRecommendationDisplayKind.MUSIC_SUPER_HERO_SHELF:return new MusicSuperHeroShelfController(this.resourceManager.resources,t);case MusicAPIRecommendationDisplayKind.MUSIC_CIRCLE_COVER_GRID:case MusicAPIRecommendationDisplayKind.MUSIC_COVER_GRID:return new MusicCoverGridController(this.resourceManager.resources,t);case MusicAPIRecommendationDisplayKind.MUSIC_UPSELL_SHELF:return new MusicUpsellShelfController(this.resourceManager.resources,t);case MusicAPIRecommendationDisplayKind.MUSIC_SOCIAL_CARD_SHELF:return new RecommendedFriendsShelfController(this.resourceManager.resources,t);case MusicAPIRecommendationDisplayKind.MUSIC_CARD_SHELF:return new MusicCardShelfController(this.resourceManager.resources,t);default:{const e=get(n,"title.stringForDisplay");logger$5.warn(`Unsupported display kind "${o}" dropping personal recommendation with title "${e}".`);return null}}}get socialProfileBadgingController(){let e=this[socialProfileBadgingControllerSymbol$1];if(!e){e=new SocialProfileBadgingController;this[socialProfileBadgingControllerSymbol$1]=e}return e}onOnboardingComplete(){this.refreshForReason("Onboarding Complete")}onSocialOnboardingStatusChange(e){const t=e?"Social Onboarded":"Social Offboarded";this.refreshForReason(t)}}const URLPromiseSymbol$1=Symbol("URLPromise");const metricsPageFieldsSymbol$1=Symbol("metricsPageFields");const pageMetricsControllerSymbol$3=Symbol("pageMetricsController");const BaseClass$q=mix(ContainerChildController).with(RequestDrivenControllerMixin,MusicAPIRequestDrivenControllerMixin);class ListenNowUpsellController extends BaseClass$q{constructor(e,t={pageType:"ListenNow",pageId:"ListenNowLanding"}){super();this.URLPromise=e;this.metricsPageFields=t}get URLPromise(){return this[URLPromiseSymbol$1]}set URLPromise(e){this[URLPromiseSymbol$1]=e}get metricsPageFields(){return this[metricsPageFieldsSymbol$1]}set metricsPageFields(e){this[metricsPageFieldsSymbol$1]=e}onChildLoadedViewModelChanged(){verticalStackFromChildControllers(this.childControllers).then(e=>{this.loadedViewModel=e})}get pageMetricsController(){return this[pageMetricsControllerSymbol$3]}set pageMetricsController(e){this[pageMetricsControllerSymbol$3]=e}URL(){return this.URLPromise}viewModelForPageResponse(e){this.removeChildControllers();const t=get(e,"results.data");if(!t||t.length===0){throw new Error(`${this.constructor.name}: No marketing item resource identifiers provided.`)}this.resourceManager.itemsForResourceIdentifiers(t,this.childViewModelControllerForMarketingItem.bind(this)).forEach(this.addChildController.bind(this));return verticalStackFromChildControllers(this.childControllers)}updatePageMetricsForPageResponse(e,t,r){super.updatePageMetricsForPageResponse(e,t,r);this.pageMetricsController.pageFields=this.metricsPageFields}childViewModelControllerForMarketingItem(e,t){const r=get(t,"type");if(r!==MusicAPIResourceType.MARKETING_ITEMS){return null}return new MarketingItemController(t)}}const BaseClass$r=mix(ComponentController).with(ContainerComponentControllerMixin,ApplicationMessageUpsellBannerControllerMixin);class ListenNowTabController extends BaseClass$r{constructor(...e){super(...e);this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE;this.applicationMessageTargetIdentifier="for_you_tab";this.hasCachedPageResourceBeenInvalidated=false;this.waitForPreviewPurchaseBeforeLoadingViewModel=false;this.loadPage()}didLoad(){super.didLoad();this.onSubscriptionChangeBound=this.onSubscriptionChange.bind(this);registerOnSubscriptionChange(this.onSubscriptionChangeBound);this.onAccountChangeBound=this.onAccountChange.bind(this);registerOnAccountChange(this.onAccountChangeBound);this.onCanShowRadioChangeBound=this.onCanShowRadioChange.bind(this);registerOnCanShowRadioChange(this.onCanShowRadioChangeBound);this.onWillContinueUserActivityBound=this.onWillContinueUserActivity.bind(this);registerGlobalCallback(Application,"onWillContinueUserActivity",this.onWillContinueUserActivityBound)}willUnload(){super.willUnload();unregisterOnSubscriptionChange(this.onSubscriptionChangedBound);unregisterOnAccountChange(this.onAccountChangeBound)}didAppear(){this.pageMetricsController.pageContext=currentPageContext();super.didAppear()}loadViewModel(){logger$5.log("[ListenNowTabController] - loadViewModel");return getSubscriptionStatus().then(e=>{if(hasVoiceAccount(e)){this.waitForPreviewPurchaseBeforeLoadingViewModel=false}const t=isUserSignedIn();if(this.waitForPreviewPurchaseBeforeLoadingViewModel){logger$5.log("Voice Preview Subscription in progress, not setting child view controller");return}const r=this.childViewModelControllerForUserStatus(t,e);return this.viewModelFromUpdatedChildViewController(r)})}onChildLoadedViewModelChanged(e,t){this.viewModel=t}onChildLoadedViewModelErrored(e,t){if(t.viewModel){this.viewModel=t.viewModel}}viewModelFromUpdatedChildViewController(e){if(this.childViewModelController){e.pageMetricsController=null;this.removeChildController(this.childViewModelController)}this.addChildController(e);this.childViewModelController=e;e.pageMetricsController=this.pageMetricsController;return e.loadedViewModel}childViewModelControllerForUserStatus(e,t){BackgroundFetchController.shared.removeURLWithIdentifier(BackgroundFetchController.URL_IDENTIFIERS.RECOMMENDATIONS_LISTEN_NOW);const r=t.carrierBundlingStatus===SubscriptionStatusResponse.CARRIER_BUNDLING_STATUS.UNLINKED;const i=hasVoiceAccount(t);const n=hasSubscriptionTier(t);if(!e){const e=getBagValue("countryCode").then(e=>{const t=new MusicAPIURL(`/v1/engagement/${e}/upsell/marketing-items`);const i="2";t.queryString.addParameters({serviceType:"music",placement:"musicListenNowUpsell"});{t.queryString.addParameters({limit:i})}if(r){t.queryString.addParameters({[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.CARRIER})}return t.string()});return new ListenNowUpsellController(e)}const o=shouldSocial().then(t=>{const o=new ListenNowURL("/v1/me/recommendations",i);o.queryString.name="listen-now";o.queryString.extend.add("editorialVideo");o.queryString.extend.add("plainEditorialNotes");if(!i){o.queryString.extend.add("plainEditorialCard")}o.queryString.addParameters({"limit[contents]":12,"include[personal-recommendation]":"primary-content"});if(i){o.queryString.with.add("marketingItems");o.queryString.addParameters({meta:"vacToken","extend[playlists]":"artistNames,versionHash","extend[albums]":"versionHash"})}else{o.queryString.addParameters({"extend[playlists]":"artistNames"})}if(!e||!n||r||i){o.queryString.with.add("marketingItems")}if(r){o.queryString.addParameters({[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]:dynamicAMSUISegueForURL.OFFER_HINTS.CARRIER})}const s=Application.sharedWithYouMetadata;const a=s?.date;const l=s?.score;if(a&&l){o.queryString.with.add("sharedWithYou");o.queryString.addParameters({sharedWithYouDate:a,sharedWithYouScore:l})}if(t){o.queryString.with.add("social");o.queryString.displayFilterKind.add(MusicAPIRecommendationDisplayKind.MUSIC_UPSELL_SHELF);o.queryString.displayFilterKind.add(MusicAPIRecommendationDisplayKind.MUSIC_SOCIAL_CARD_SHELF);o.queryString.with.add("friendsMix");o.queryString.addParameters({"extend[social-profiles]":"topGenreNames",meta:"catalogIds"})}return o.string()});const s=this.hasCachedPageResourceBeenInvalidated;this.hasCachedPageResourceBeenInvalidated=false;return new ListenNowRecommendationsController(o,s,i)}handleSubscriptionPurchase(){this.waitForPreviewPurchaseBeforeLoadingViewModel=false;unsubscribe(SUBSCRIPTION_PURCHASE_DID_SUCCEED,this.onSubscriptionPurchaseDidSucceedBound);this.onSubscriptionPurchaseDidSucceedBound=null;unsubscribe(SUBSCRIPTION_PURCHASE_DID_FAIL,this.onSubscriptionPurchaseDidFailBound);this.onSubscriptionPurchaseDidFailBound=null}onSubscriptionChange(){this.hasCachedPageResourceBeenInvalidated=true;this.refreshForReason("Subscription Changed")}onAccountChange(e,t){if(t===Store.ACCOUNT_CHANGE_REASON.UNIQUE_IDENTIFIER_CHANGED){this.refreshForReason("Account Unique Identifier Changed")}}onCanShowRadioChange(){this.refreshForReason("Can show radio restriction changed")}onSubscriptionPurchaseDidSucceed(){this.handleSubscriptionPurchase()}onSubscriptionPurchaseDidFail(){if(!this.waitForPreviewPurchaseBeforeLoadingViewModel){return}this.handleSubscriptionPurchase();this.refreshForReason("Preview subscription failed")}onWillContinueUserActivity(e){if(e.activityType!=="com.apple.Music.voicePreview"){return}logger$5.log("[ListenNowTabController] - onWillContinueUserActivity");this.onSubscriptionPurchaseDidSucceedBound=this.onSubscriptionPurchaseDidSucceed.bind(this);subscribe(SUBSCRIPTION_PURCHASE_DID_SUCCEED,this.onSubscriptionPurchaseDidSucceedBound);this.onSubscriptionPurchaseDidFailBound=this.onSubscriptionPurchaseDidFail.bind(this);subscribe(SUBSCRIPTION_PURCHASE_DID_FAIL,this.onSubscriptionPurchaseDidFailBound);this.waitForPreviewPurchaseBeforeLoadingViewModel=true}}const BaseClass$s=mix(GroupingController).with(ApplicationMessageUpsellBannerControllerMixin);class BrowseTabController extends BaseClass$s{constructor(){super(...arguments);this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE;this.applicationMessageTargetIdentifier="browse_tab"}getURL(){return getBagValue("musicSubscription.browse")}fetchPageData(...e){return super.fetchPageData(...e).then(e=>{const t=get(e,"pageData.fcStructure.model");if(t&&!t.fcKind){t.fcKind="315"}if(t&&t.children instanceof Array){const r=get(e,"pageData.links",[]);const i=r.find(e=>e.type==="genres");const n=t.children;if(i){i.menu=[];const e=n.findIndex(e=>e.fcKind==="322");if(e!==-1){const t=n.splice(e,1);if(t.length>0){i.menu.push({name:localize("FUSE.Browse.AllGenres"),links:t[0].links||[]})}}}t.children.push({fcKind:"391",links:r})}return e}).catch(e=>{logger$5.error("oops",e);throw e})}}const REFRESH_TTL$2=5*60*1e3;const BaseClass$t=mix(GroupingController).with(ApplicationMessageUpsellBannerControllerMixin);class RadioTabController extends BaseClass$t{constructor(){super(...arguments);this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_ADAPTIVE;this.refreshTTL=REFRESH_TTL$2;this.recentlyPlayedCallback=debounce(this.refreshRecentlyPlayed.bind(this),1e3);this.applicationMessageTargetIdentifier="radio_tab"}getURL(){return Promise.all([getBagValue("radioTab.grouping"),getBagValue("musicSubscription.browseNavigation")])}createPageMetrics(e){super.createPageMetrics(e);this.pageContext=currentPageContext();this.pageIdentifier=get(e,"pageData.metricsBase.pageId");this.pageType=get(e,"pageData.metricsBase.pageType");this.pageURL=this.url}willUnload(){super.willUnload();unsubscribe(PLAY_ACTIVITY_TOPIC,this.recentlyPlayedCallback)}setInitializersForRefresh(){subscribe(PLAY_ACTIVITY_TOPIC,this.recentlyPlayedCallback)}refreshRecentlyPlayed(){fetchRecentlyPlayedRadio().then(e=>{const t=get(this,"responseData.storePlatformData",{});return fetchContent({ids:e.map(e=>e.id)}).then(r=>{this.responseData.storePlatformData=Object.assign({},t,r);return e})}).then(e=>{const t=get(this,"viewModel.childViewModels",[]);const r=t.find(({metrics:e})=>get(e,"impressions.fcKind")==="332");if(r){const t=get(this,"responseData.storePlatformData",{});const i=createRecentlyPlayedRadioShelfItems.call(this,t,e);const n=r.sections;n[0].items=i;r.sections=n}}).catch(e=>{logger$5.error("Error refreshing radio recently played",e)})}fetchPageData([e,t]){this.url=e;return Promise.all([super.fetchPageData(e),fetchJSON(t)]).then(([e,t])=>{const r=get(e,"pageData.fcStructure.model");if(r&&r.children instanceof Array){let e=r.children;if(e[0]&&e[0].fcKind==="382"){e=e[0].children||[]}const i=get(t,"pageData.radioLinks",[]);const n=e.find(e=>e.fcKind==="391");if(n&&n.links){n.links=n.links.map(e=>{let t;if(e.url){const r=i.find(t=>t.url===e.url);if(r){t=Object.assign({controllerTitle:r.label},e)}}return t||e})}}return e}).catch(e=>{logger$5.error("oops",e);throw e})}}class SearchLandingURL extends MusicAPIURL{domain(){return getBagValue("ampMusicAPIDomains.searchLanding")}}function createSearchLandingSection(e){return Object.assign(new SearchLandingViewModel,e)}function createSearchLandingItem(e){return Object.assign(new SearchLandingItem,e)}function createSearchLandingUpsell(e){return Object.assign(new SearchLandingUpsell,MetricsClickHandlers.searchLandingUpsell,e)}SearchLandingUpsell.ACTION={ACCESSORY_BUTTON_SELECT:"accessoryButtonSelect",SELECT:"select",CLOSE_BUTTON_SELECT:"closeButtonSelect"};function musicSearchLandingItem(e,t={},r,i){const n=t.attributes;if(!n){return null}const o=get(n,"editorialArtwork.subscriptionHero");if(!o||!o.url){logger$5.warn(`Missing artwork for resource id ${t.id}`);return null}const s={displayStyle:r,id:t.id,reco_id:get(i,"reco_id"),containerType:"category",kind:get(n,"kind"),backgroundArtwork:createArtwork({dictionary:o,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),metrics:{impressions:{id:t.id}}};switch(t.type){case MusicAPIResourceType.APPLE_CURATORS:{const e=get(n,"shortName");Object.assign(s,{title:e,onSelect:()=>createPushSegueForURL(n.url,{title:e})});break}case MusicAPIResourceType.EDITORIAL_ITEMS:{const r=get(n,"editorialNotes.name");Object.assign(s,{title:r,onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t,r)});break}case MusicAPIResourceType.ACTIVITIES:{const r=get(n,"name");Object.assign(s,{title:r,onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t,r)});break}default:logger$5.warn(`"${e.type}" resource type unsupported, dropping personal recommendation item with id "${e.id}".`)}return Object.assign(createSearchLandingItem(),s,MetricsClickHandlers.searchLandingItem)}function itemsForPersonalRecommendationChildren(e,t,r,i,n){const o=[];e.forEach(e=>{const s=get(t,[e.type,e.id]);if(!s){logger$5.warn(`Missing resource ${e.type} ${e.id} for recommendation item.`);return}const a=r(e,s,i,n);if(!a){return}o.push(a)});return o}function musicNamedBrickShelfProperties(e={},t){const r=e.attributes;const i=get(r,"display.size");const n=get(r,"title.stringForDisplay");const o=get(e,"relationships.contents.data");const s=get(e,"meta.metrics");const a=itemsForPersonalRecommendationChildren(o,t,musicSearchLandingItem,i,s);const l=get(e,"id");const c={items:a,title:n,editorialID:l};return c}function currentUserHasManuallyDismissedSearchLandingUpsellWithinCurrentMajorVersion(){const e=Storage.getItem(StorageKeys.User.LAST_MAJOR_VERSION_HAS_MANUALLY_DISMISSED_SEARCH_LANDING_UPSELL);return Device.majorVersion()===e}function searchLandingUpsellForResource(e,t,r){if(t||currentUserHasManuallyDismissedSearchLandingUpsellWithinCurrentMajorVersion()||!canShowSubscriptionContent()){logger$5.log(`Hiding Search Landing Upsell. isMediaPicker: '${t}', currentUserHasManuallyDismissedSearchLandingUpsellWithinCurrentMajorVersion: '${currentUserHasManuallyDismissedSearchLandingUpsellWithinCurrentMajorVersion()}', canShowSubscriptionContent: '${canShowSubscriptionContent()}'`);return null}const i=e.attributes;if(!i){logger$5.error(`Required attributes not found on resource. Resource: '${JSON.stringify(e)}'`);return null}const n=i.offers;if(!n){logger$5.error(`Required offers not found on the marketing item atttributes. Resource: '${JSON.stringify(e)}'`);return null}const o=n[0];const s=n[1];const a=onSelectHandlerForMarketingOffer(o);const l=onSelectHandlerForMarketingOffer(s);let c={impressions:{name:i.title,description:o?.callToActionLabel,kind:"upsell",impressionType:"platter",id:e.id,marketing:{marketingItemId:e.meta?.metrics?.["marketing.marketingItemId"],offerDecisionId:e.meta?.metrics?.offerDecisionId}}};c=addAdditionalMarketingItemMetrics(c,e?.meta?.metrics);const u={marketingId:e.id,headline:i.title,subtitle:i.subtitle,primaryButtonTitle:o?.callToActionLabel,accessoryButtonTitle:s?.callToActionLabel,tallArtwork:createArtwork({dictionary:i.marketingArtwork.searchLandingTall,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),wideArtwork:createArtwork({dictionary:i.marketingArtwork.searchLandingWide,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),onSelect:a,onAccessoryButtonSelect:l,onCloseButtonSelectionPerformed:(e,t)=>{Storage.setItem(StorageKeys.User.LAST_MAJOR_VERSION_HAS_MANUALLY_DISMISSED_SEARCH_LANDING_UPSELL,Device.majorVersion());MetricsClickHandlers.searchLandingUpsell.onCloseButtonSelectionPerformed(e,t);r()},primaryOffer:o,secondaryOffer:s,metrics:c};if(i.marketingVideo?.searchLandingTall){u.tallVideoArtwork=createVideoArtwork({dictionary:i.marketingVideo.searchLandingTall})}if(i.marketingVideo?.searchLandingWide){u.wideVideoArtwork=createVideoArtwork({dictionary:i.marketingVideo?.searchLandingWide})}return createSearchLandingUpsell(u)}function viewModelForPageResponse(e,t,r){const i=e?.data;const n=e?.resources;if(!i){logger$5.warn("Search page response missing recommendations.");return null}const o=[];let s=[];let a=null;i.forEach(e=>{const i=get(n,[e.type,e.id]);if(!i){logger$5.warn(`Search Landing page response missing resource for id "${e.id}".`);return}if(i.type===MusicAPIResourceType.MARKETING_ITEMS){const e=searchLandingUpsellForResource(i,t,r);if(e){o.push(e)}return}const l=i.attributes;const c=get(l,"display.kind");switch(c){case MusicAPIRecommendationDisplayKind.MUSIC_NAMED_BRICK_SHELF:{const e=musicNamedBrickShelfProperties(i,n);if(e){s=s.concat(e.items)}if(!a){a=get(e,"title")}break}default:{logger$5.warn(`Unsupported display kind "${c}". Dropping personal recommendation.`)}}});o.push(createSearchLandingSection({items:s,title:a}));return createVerticalStack({childViewModels:o})}const BaseClass$u=mix(ComponentController).with(RequestDrivenComponentControllerMixin,MusicAPIRequestDrivenControllerMixin);class SearchLandingTabController extends BaseClass$u{constructor(...e){super(...e);this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.LARGE_FIXED;this.loadPage()}didLoad(){super.didLoad();this.onSubscriptionChangeBound=this.onSubscriptionChange.bind(this);registerOnSubscriptionChange(this.onSubscriptionChangeBound);this.onAccountChangeBound=this.onAccountChange.bind(this);registerOnAccountChange(this.onAccountChangeBound);this.boundDebouncedOnHasUserRequestedSubscriptionHiddenChange=debounce(this.onHasUserRequestedSubscriptionHiddenChange.bind(this),100);registerOnHasUserRequestedSubscriptionHiddenChange(this.boundDebouncedOnHasUserRequestedSubscriptionHiddenChange)}willUnload(){super.willUnload();unregisterOnSubscriptionChange(this.onSubscriptionChangeBound);unregisterOnAccountChange(this.onAccountChangeBound);unregisterOnHasUserRequestedSubscriptionHiddenChange(this.onHasUserRequestedSubscriptionHiddenChange)}didAppear(){this.pageMetricsController.pageContext=currentPageContext();super.didAppear()}URL(){return Promise.all([getBagValue("countryCode"),getSubscriptionStatus()]).then(([e,t])=>this.makeURL(e,t,canShowSubscriptionContent(),currentUserHasManuallyDismissedSearchLandingUpsellWithinCurrentMajorVersion()).string())}updatePageMetricsForPageResponse(e,t,r){const i=t;super.updatePageMetricsForPageResponse(e,t,r);this.pageMetricsController.pageFields={pageType:"Search",pageId:"SearchLanding",pageUrl:i}}viewModelForPageResponse(e){BackgroundFetchController.shared.registerIdentifierWithPromisedURL(BackgroundFetchController.URL_IDENTIFIERS.RECOMMENDATIONS_SEARCH_LANDING,this.URL());const t=get(this,"environment.mediaPickerEnvironment");const onCloseButtonSelectionPerformedSearchLandingUpsell=()=>{this.loadedViewModel.then(e=>{if(e instanceof VerticalStack&&Array.isArray(e.childViewModels)){e.childViewModels=e.childViewModels.filter(e=>e instanceof SearchLandingUpsell===false)}else{logger$5.log(`${this.constructor.name}: Unexpected loaded view model type when attempting to dismiss search landing upsell: '${JSON.stringify(e)}'`)}})};return viewModelForPageResponse(e,t,onCloseButtonSelectionPerformedSearchLandingUpsell)}refreshViewModelForPageResponse(e,t){const r=this.viewModelForPageResponse(t);if(r!==e){this.loadedViewModel=r}return Promise.resolve()}makeURL(e,t,r,i){const n=new SearchLandingURL(`/v1/recommendations/${e}`);n.queryString.name="search-landing";n.queryString.extend.add("editorialArtwork");n.queryString.with.add("voice");n.queryString.addParameters({"art[url]":"c,f"});if(!t.isSubscribed&&r&&!i){n.queryString.with.add("marketingItems")}n.queryString.types=new Set([MusicAPIResourceType.ACTIVITIES,MusicAPIResourceType.APPLE_CURATORS,MusicAPIResourceType.EDITORIAL_ITEMS]);return n}onSubscriptionChange(){this.refreshForReason("Subscription Changed")}onAccountChange(e,t){if(t===Store.ACCOUNT_CHANGE_REASON.UNIQUE_IDENTIFIER_CHANGED){this.refreshForReason("Account Unique Identifier Changed")}}onHasUserRequestedSubscriptionHiddenChange(){this.refreshForReason("refresh due to subscription hidden change")}}class SearchResultController extends SearchResultComponentController{constructor(...e){super(...e);this.boundDebouncedConsiderFetchingFollowStateForIds=debounce(considerFetchingFollowStateForIds.bind(),500,true);this.onSearchResultSelectionPerformed=()=>{};this.onUpdateSearchResultSections=e=>{const t=[];e.forEach(e=>{e.items.forEach(e=>{const r=e.storePlatformDictionary;const i=e.mediaAPIDictionary;let n;if(r?.kind===MusicAPIResourceType.SOCIAL_PROFILES&&r.id){t.push(r.id)}else if(i?.type===MusicAPIResourceType.SOCIAL_PROFILES&&i?.id){t.push(i.id)}const o=i?.attributes?.editorialVideo;if(o&&containsMotionDetailVideo(o)){e.videoDetailArtwork=createVideoArtwork({dictionary:getMotionDetailVideo(o),cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE,supportsUberArtwork:containsMotionDetailTallVideo(o)})}if(r?.kind===MusicAPIResourceType.EDITORIAL_ITEMS){const e={type:MusicAPIResourceType.EDITORIAL_ITEMS,id:i?.id??r.id};const t={attributes:i?.attributes??r};n=onSelectHandlerForMusicAPIResourceIdentifier(e,t)}else if(r?.kind===MusicAPIResourceType.RECORD_LABELS){const e={type:MusicAPIResourceType.RECORD_LABELS,id:r.id};n=onSelectHandlerForMusicAPIResourceIdentifier(e,i)}else if(Object.keys(i).length>0){const e={type:i.type,id:i.id};const t={attributes:i.attributes};n=onSelectHandlerForMusicAPIResourceIdentifier(e,t)}Object.assign(e,{onSelect:n})})});if(t.length>0){this.boundDebouncedConsiderFetchingFollowStateForIds.bind(this,t)()}}}}function conformsToChildSettingsBehavior(e){const t=e.prototype;t.buildSections=t.buildSections||function buildSections(){};t.doneButtonSelected=t.doneButtonSelected||function doneButtonselected(){};t.isOwnerOf=t.isOwnerOf||function isOwnerOf(){return false};t.removeItem=t.removeItem||function removeItem(){return Promise.resolve()};return t}function getBagCatchError(e){return getBagValue(e).catch(t=>{logger$5.warn(`Missing bag key ${e}`,t)})}function createDeepLinkSegue(e){return Object.assign(new DeepLinkSegue,e)}function buildUserDetailsSection(e,t,r=[],i={},n){const o=i.isSubscribed;if(!e||!t||!o||!n){return}const s=[];s.push(createSettingsItem({kind:SettingsItem.KIND.USER_DETAILS,onSelect:()=>{const e=[createPushSegue({componentController:new SocialProfileController({storePlatformDictionary:n})})];const t=createDeepLinkSegue({pushSegues:e,viewIdentifier:DeepLinkSegue.VIEW_IDENTIFIER.FOR_YOU_TAB,animated:true});return t},hasChevron:true}));if(r.length>0){s.push(createSettingsItem({title:localize("FUSE.Settings.AMF.FollowRequest.Label"),kind:SettingsItem.KIND.FOLLOW_REQUESTS,onSelect:()=>createPushSegue({componentController:new FollowRequestController}),hasChevron:true}))}return createSettingsSection({items:s})}function buildAccountSection(e={},t,r,i,n={}){const o=[];const s=get(n,"rawResponseData.music.isNotEligibleForFreeTrial",true);const a=hasSubscriptionTier(n);const l=hasVoiceAccount(n);const c=get(n,"rawResponseData.music.reason");const u=c==="Family"||c==="Member";const d=n.isFamilyOrganizer||!n.hasFamily;const g=n.hasFamilyMembers;const h=get(n,"rawResponseData.music.isPartOfBundle");const f=get(n,"rawResponseData.music.ownsBundle");const p=get(e,"offers[0]");const m=get(p,"priceFormatted");const S=locWithIntroPricing("FUSE.Settings.Upsell.Label",p,m);const I=get(e,"userInfo.isStudent",false);let C;let y;let P;switch(n.carrierBundlingStatus){case SubscriptionStatusResponse.CARRIER_BUNDLING_STATUS.ELIGIBLE:case SubscriptionStatusResponse.CARRIER_BUNDLING_STATUS.UNLINKED:case SubscriptionStatusResponse.CARRIER_BUNDLING_STATUS.NEEDS_MANUAL_VERIFICATION:C=true;break;default:C=n.rawResponseData?.music?.partner||false;break}if(t){o.push(createSettingsItem({title:localize("FUSE.Settings.Redeem.Label"),onSelect:()=>createFinanceSegue(t)}))}if(r&&d){o.push(createSettingsItem({title:localize("AddFunds.Main.TitleAppStore"),onSelect:()=>createStoreFlowSegue({url:r})}))}if(a&&d){const e=constructURL(i,{params:{subscriptionType:"music"}});o.push(createSettingsItem({title:localize("FUSE.Settings.ManageSubscription.Label"),onSelect:()=>createStoreFlowSegue({url:e})}))}if(!a&&s){o.push(createSettingsItem({title:localize("FUSE.Settings.Upsell.NonTrial.Label"),onSelect:()=>createSegueToFinanceSync("subscribe","",{})}))}else if(!a&&!s){const e=S;if(e){o.push(createSettingsItem({title:S,onSelect:()=>createSegueToFinanceSync("subscriptionoffers","",{})}))}}else if(a&&!u&&d&&!C&&!h&&!f&&!l){let t="";dynamicAMSUIURLForPlacement(dynamicAMSUIURLForPlacement.PLACEMENTS.MUSIC_PRE_BUY).then(e=>{t=e}).catch(e=>logger$5.error(e,"Failed to get the URL for placement=musicPreBuyFlow"));o.push(createSettingsItem({title:localize("FUSE.Settings.Upsell.Subscribed.UpgradeFamily.Label"),onSelect:()=>createStoreFlowSegue({url:t})}));const r={priceDiff:I?e.formattedFamilyandStudentPriceDiff:e.formattedFamilyAndIndividualPriceDiff};P=localize("FUSE.Settings.Upsell.Subscribed.UpgradeFamily.explanation",r)}else if(a&&u&&d){const e="prefs:root=APPLE_ACCOUNT&action=setupFamily";o.push(createSettingsItem({title:!g?localize("FUSE.Settings.AddFamily.Label"):localize("FUSE.Settings.ManageFamily.Label"),onSelect:()=>createRedirectSegue({url:e})}))}if(o.length>0){y=createSettingsSection({items:o,footerText:P})}return y}function buildViewAppleIdSection(e){return createSettingsSection({items:[createSettingsItem({title:localize("FUSE.ViewAppleId"),onSelect:()=>createStoreFlowSegue({url:e})})]})}function buildSocialOnboardSection(e,t,r,i={}){if(!r||!i.isSubscribed||t||!e){return}const n=localize("FUSE.Settings.FriendsAreListeningTo.Label");const o=createSettingsItem({title:n,onSelect:()=>createSegueToSocialOnboarding()});addClickMetricsHandlerToItem(o,()=>({actionContext:"AccountSettingsCTA",actionDetails:{title:"See What Friends Are Listening To"}}));return createSettingsSection({items:[o],footerText:localize("FUSE.Settings.FriendsAreListeningTo.Explanation")})}class SettingsAccountController{constructor(){this.responseData=[]}loadPage(){return Promise.all([getBagValue("getSubscriptionOffersSrv").catch(),isSocialOnboarded()]).then(([e,t])=>{const r=get(Store,"account.userSocialProfile.storePlatformDictionary");let i;if(t){i=r?Promise.resolve(r):fetchUserSocialProfileStorePlatformDictionary()}else{i=Promise.resolve()}return Promise.all([fetchJSON(e).catch(()=>{}),getSubscriptionStatus().catch(()=>{}),getBagCatchError("modifyAccount"),getBagCatchError("redeemCodeLanding"),getBagCatchError("AddFundsUrl"),getBagCatchError("manageSubscriptionsUrl"),shouldSocial().catch(()=>false),Promise.resolve(t).catch(()=>false),canSocialOnboard().catch(()=>false),getFollowRequests().catch(()=>{}),i.catch(()=>{})])}).then((e={})=>{this.responseData=e;this.modifyAccountUrl=this.responseData[2]}).catch(e=>logger$5.error(e,"Failed load page of SettingsAccountController"))}buildSections(){if(this.responseData.length===0){return[]}const[e,t,,r,i,n,o,s,a,l,c]=this.responseData;const u=buildUserDetailsSection(o,s,get(l,"followRequests",[]),t,c);const d=buildAccountSection(e,r,i,n,t);const g=buildSocialOnboardSection(o,s,a,t);const h=[];if(u){h.push(u)}if(d){h.push(d)}if(g){h.push(g)}return h}buildDisconnectedSections(){const e=this.modifyAccountUrl;const t=[];if(e){t.push(buildViewAppleIdSection(e))}return t}}conformsToChildSettingsBehavior(SettingsAccountController);class SettingsNotificationsController{buildSections(){const e=[];e.push(createSettingsItem({title:localize("FUSE.Settings.Notifications"),usesApplicationTintColor:false,hasChevron:true,onSelect:()=>{const e=createPushSegue({componentController:new NotificationPreferencesController});return e}}));return createSettingsSection({items:e})}}conformsToChildSettingsBehavior(SettingsNotificationsController);function createSocialNetworkAuthSegue(e){return Object.assign(new SocialNetworkAuthSegue,e)}const AUTH_AUTHENTICATION_DID_CHANGE="authAuthenticationDidChange";class SettingsSocialController{constructor(){this.responseData=[]}loadPage(){return shouldSocial().then(e=>{if(!e){return}return getSocialBagValue("getOAuthSocialNetworks").then(e=>Promise.all([fetchJSON(e),getUserProfile(),fetchUsingSameAccountForCloudAndStore(),isSocialOnboarded(),getSubscriptionStatus()])).then(e=>{this.responseData=e}).catch(e=>logger$5.error("Failed to fetch social data in SettingsSocialController",e))})}buildConsentSection(e={},t){const r=SocialContactsConsentController.getAppropriateLinkForAppleID(t);this.isDiscoverableConsentItem=createSettingsItem({title:localize("FUSE.Social.ContactsConsent.Onboarding.HowYouShare.Title"),accessoryItem:createSettingsItemToggle({isToggled:!!e.isDiscoverableByContact}),usesApplicationTintColor:false});return createSettingsSection({items:[this.isDiscoverableConsentItem],footerText:localize("FUSE.Social.ContactsConsent.HelpOthers.Text",{link:r})})}buildSocialNetworkSection(e=[],t={}){let r;const i=localize("FUSE.Settings.FindFriends.Connected");const n=localize("FUSE.Settings.FindFriends.NotConnected");const o=e.map(e=>createSettingsItem({title:e.nameForDisplay,artwork:createArtwork({dictionary:e.artwork}),usesApplicationTintColor:false,accessoryItem:createSettingsItemText({text:e.isAuthenticated?i:n}),onSelect:()=>{const t=createSocialNetworkAuthSegue();const r={identifier:e.name,name:e.nameForDisplay,authURL:e.oauth_url,redirectURL:e.redirectUrl,authenticated:e.isAuthenticated,authProtocol:e.oauthProtocol};const i=createSocialOnboardingNetwork(r);i.authenticationDidChange=()=>{publish(AUTH_AUTHENTICATION_DID_CHANGE)};t.network=i;return t}}));this.contactsConsentItem=createSettingsItem({title:localize("FUSE.Social.ContactsConsent.Onboarding.Title"),usesApplicationTintColor:false,accessoryItem:createSettingsItemToggle({isToggled:!!t.isContactsCheckAllowed})});o.push(this.contactsConsentItem);if(o.length>0){r=createSettingsSection({items:o,headerText:localize("FUSE.Settings.FindFriends.Header"),footerText:localize("FUSE.Social.ContactsConsent.Onboarding.Subtitle")})}return r}buildSections(){if(this.responseData.length===0){return[]}const[e,t,r,i,n={}]=this.responseData;const o=[];const s=n.isSubscribed;if(!i||!s){return o}const a=this.buildSocialNetworkSection(e.socialNetworks,t,i);const l=this.buildConsentSection(t,r);if(a){o.push(a)}if(l){o.push(l)}return o}doneButtonSelected(){if(!this.contactsConsentItem&&!this.isDiscoverableByContact){return}const e=get(this.contactsConsentItem,"accessoryItem.isToggled");const t=get(this.isDiscoverableConsentItem,"accessoryItem.isToggled");const r={body:Object.assign({isContactsCheckAllowed:e},socialRequests.getIsDiscoverableByContactRequestBody(t))};return socialRequests.updateProfile(r).then(()=>{Store.account.reloadUserProfileIfNeeded();const r=get(Store,"account.userProfile");r.isContactsCheckAllowed=e;r.isDiscoverableByContact=t;r.discoverabilityConsentVersion=SocialContactsConsentController.discoverabilityConsentVersion}).catch(e=>logger$5.error("Failed to send up user profile data in SettingsSocialController",e))}}conformsToChildSettingsBehavior(SettingsSocialController);const SETTINGS_SDK_SECTION_ID="sdk";const ownedSectionIds=[SETTINGS_SDK_SECTION_ID];const revokeAuthorization=(e,t)=>fetch(e,{method:HTTP.METHOD.POST,body:{musicId:t}});class SettingsSDKController{loadPage(){return getBagValue("getMusicSDKAuthorizationsSrv").then(fetchJSON).then(e=>{this.responseData=e}).catch(e=>logger$5.error("Failed to load SettingsSDKController",e))}buildSections(){const e=get(this.responseData,"data.attributes.appList",[]);if(e.length===0){return[]}const t=e.map(e=>createSettingsItem({id:e.id,appId:e.id,isDeletable:true,sectionId:SETTINGS_SDK_SECTION_ID,title:e.name,usesApplicationTintColor:false}));return createSettingsSection({items:t,headerText:localize("FUSE.Settings.SDK.AppsAccess.Header"),sectionId:SETTINGS_SDK_SECTION_ID})}removeItem(e){return getBagValue("revokeMusicSDKAuthorizationSrv").then(t=>revokeAuthorization(t,e.appId)).catch(t=>logger$5.error("Failed to revoke Music authorization for item",e.appId,t))}isOwnerOf(e){return ownedSectionIds.indexOf(e)!==-1}}conformsToChildSettingsBehavior(SettingsSDKController);class SettingsManagerListController extends ComponentController{constructor(e){super();this.responseData=e}didLoad(){super.didLoad();if(!this.responseData){return}this.headerItem.title=localize("FUSE.Settings.ManagedAccounts.PageTitle");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD;const{permissions:e=[],storePlatformData:t={}}=this.responseData;const r=get(t,"artist.results",{});if(e.length===0){return}const i=e.map(e=>get(r,e.entityId)).filter(e=>!!e).map(e=>createSettingsItem({title:e.name,onSelect:()=>createPushSegueForStoreContent(e),usesApplicationTintColor:false}));const n=createSettingsSection({items:i});this.viewModel=createSettingsViewModel({sectionsForAuthenticatedState:[n],sectionsForUnauthenticatedState:[n]})}}class SettingsManagerController{loadPage(){return getBagValue("musicCommon.profilePermissions").then(e=>fetchJSON(e)).then(e=>{this.responseData=e}).catch(e=>logger$5.error("Failed to fetch Managed profiles in SettingsManagerController",e))}buildSections(){if(!this.responseData){return}const{permissions:e=[],storePlatformData:t={}}=this.responseData;const r=get(t,"artist.results",{});if(e.length===0){return}if(e.length<=5){const t=e.map(e=>get(r,e.entityId)).filter(e=>!!e).map(e=>createSettingsItem({title:e.name,onSelect:()=>createPushSegueForStoreContent(e),usesApplicationTintColor:false}));return createSettingsSection({items:t,headerText:localize("FUSE.Settings.ManagedAccounts.Header")})}return createSettingsSection({items:[createSettingsItem({title:localize("FUSE.Settings.ManagedAccounts.PageTitle"),onSelect:()=>createPushSegue({componentController:new SettingsManagerListController(this.responseData)}),usesApplicationTintColor:false,hasChevron:true})]})}}conformsToChildSettingsBehavior(SettingsManagerController);class SettingsVersionController{buildSections(){return createSettingsSection({headerText:`Version: ${config$3.version}`})}}const findSectionIndex=(e=[],t)=>e.findIndex(e=>e.sectionId===t);const findSectionOnViewModel=(e,t)=>{let r=findSectionIndex(e.sectionsForAuthenticatedState,t);let i="sectionsForAuthenticatedState";if(r>-1){return{sectionType:i,sectionIndex:r,section:e[i][r]}}r=findSectionIndex(e.sectionsForUnauthenticatedState,t);i="sectionsForUnauthenticatedState";if(r>-1){return{sectionType:i,sectionIndex:r,section:e[i][r]}}return{sectionIndex:-1}};const BaseClass$v=mix(ComponentController).with(MetricsMixin);class SettingsController extends BaseClass$v{didLoad(){super.didLoad();this.refreshCallback=this.loadPage.bind(this);this.settingsAccountController=new SettingsAccountController;this.settingsVersionController=new SettingsVersionController;const e=new SettingsNotificationsController;this.children=[this.settingsAccountController,new SettingsManagerController,e,new SettingsSocialController,new SettingsSDKController];this.loadPage();registerOnAccountChange(this.refreshCallback);registerOnSubscriptionChange(this.refreshCallback);subscribe(AUTH_AUTHENTICATION_DID_CHANGE,this.refreshCallback)}willUnload(){super.willUnload();unregisterOnAccountChange(this.refreshCallback);unregisterOnSubscriptionChange(this.refreshCallback);unsubscribe(AUTH_AUTHENTICATION_DID_CHANGE,this.refreshCallback)}createPageMetrics(){this.pageContext="AccountSettings";this.pageFields={pageType:"AccountMain",pageId:"AccountSettings"}}loadPage(){waitForLocInitialization().then(()=>{this.updateViewModel();this.headerItem.title=localize("FUSE.Account");this.headerItem.titleHeaderStyle=HeaderItem.TITLE_HEADER_STYLE.STANDARD}).then(()=>{this.createPageMetrics();this.considerRecordingPageEvent()}).catch(e=>logger$5.error("SettingsController failed to load",e))}updateViewModel(){const e=[createSettingsAuthenticationSection({identifierLabelText:localize("FUSE.SignIn.AppleId.Label"),passwordLabelText:localize("FUSE.SignIn.Password.Label"),submitButtonText:localize("FUSE.SignIn"),forgotCredentialsLink:createSettingsLink({text:localize("FUSE.SignIn.ForgotAppleId")})})];if(!isUserSignedIn()){if(isInternalInstall()){e.push(...[this.settingsVersionController.buildSections()])}this.viewModel=createSettingsViewModel({sectionsForUnauthenticatedState:e});return}this.loadChildren().then(()=>{const t=this.createSectionsFromChildren();t.push(...this.settingsAccountController.buildDisconnectedSections());if(isInternalInstall()){t.push(...[this.settingsVersionController.buildSections()])}this.viewModel=createSettingsViewModel({didSelectDoneButton:()=>this.tellChildrenDoneButtonSelected(),onRemoveItemPerformed:(e,t)=>{const r=t.sectionId;const i=this.children.find(e=>e.isOwnerOf(r));const{section:n,sectionIndex:o,sectionType:s}=findSectionOnViewModel(this.viewModel,r);i.removeItem(t);if(n.items.length!==0){return}const a=this.viewModel[s];a.splice(o,1);this.viewModel[s]=a;this.viewModel=this.viewModel},sectionsForUnauthenticatedState:e,sectionsForAuthenticatedState:t})}).catch(e=>logger$5.error("Loading of children in SettingsController failed",e))}tellChildrenDoneButtonSelected(){this.children.forEach(e=>{if(typeof e.doneButtonSelected==="function"){e.doneButtonSelected()}})}loadChildren(){const e=this.children.map(e=>{if(typeof e.loadPage==="function"){return e.loadPage()}return Promise.resolve()});return Promise.all(e)}createSectionsFromChildren(){const e=this.children.map(e=>{let t;if(typeof e.buildSections==="function"){t=e.buildSections()}return t}).filter(e=>!!e);const t=flatten(e);return t}}let ShellLibraryController;if(typeof LibraryCollectionComponentController==="undefined"){ShellLibraryController=class Dummy{}}else{ShellLibraryController=LibraryCollectionComponentController}class RoutingLibraryComponentController extends ShellLibraryController{didLoad(){super.didLoad();const e=get(this,"viewModel.collectionStorePlatformDictionary");if(e){const t=get(e,"id");let r;if(t){fetchContent({ids:[String(t)]}).then((e={})=>{const i=e[t];const n=[];if(i){r=get(i,"showBrandId");n.push(r)}return fetchContent({ids:n})}).then((e={})=>{const t=e[r];if(t){const e=new ContainerDetailLink;e.onSelect=()=>createPushSegueForStoreContent(t);this.viewModel.relatedContentLink=e}})}}}}function metricsFieldsForCurrentItemHasTimeSyncedLyrics(e){if(e!==null&&e!==undefined){return{pageDetails:{currentItemHasTimeSyncedLyrics:e}}}}const LyricsSyllableUserPreferenceMapping=e=>{switch(e){case 0:return"off";case 1:return"attenuationOnly";case 2:return"always";default:return null}};const PageFieldsForPage={nowPlayingControlsMode:e=>{const t={pageType:"NowPlaying",page:"NowPlaying"};assignPageMetricsFields(t,metricsFieldsForCurrentItemHasTimeSyncedLyrics(e));return t},nowPlayingUpNextMode:e=>{const t={pageId:"UpNext",pageType:"NowPlaying"};assignPageMetricsFields(t,metricsFieldsForCurrentItemHasTimeSyncedLyrics(e));return t},nowPlayingLyricsMode:(e,t)=>{let r;if(t){switch(e){case NowPlayingViewModel.LYRICS_MODE.NONE:r="LyricsNone";break;case NowPlayingViewModel.LYRICS_MODE.STATIC:r="LyricsStatic";break;case NowPlayingViewModel.LYRICS_MODE.TIME_SYNCED:r="LyricsTimeSynced";break;case NowPlayingViewModel.LYRICS_MODE.SYLLABLE_BY_SYLLABLE:r="LyricsSyllable";break;case NowPlayingViewModel.LYRICS_MODE.LOADING:default:return null}}else{r="LyricsNone"}if(!r){return null}const i={pageId:r,pageType:"NowPlaying",attenuationAvailable:t.attenuationAvailable,userPreferenceLyricsSyllable:LyricsSyllableUserPreferenceMapping(t.userPreferenceLyricsSyllable)};const n=t&&t.hasTimeSyncedLyrics;assignPageMetricsFields(i,metricsFieldsForCurrentItemHasTimeSyncedLyrics(n));return i}};const BaseClass$w=mix(NowPlayingComponentController).with(MetricsMixin);let lastKnownIsSubscribedStatus=null;let onSubscriptionStatusInvalidated;const onSubscriptionChange=()=>{lastKnownIsSubscribedStatus=null;if(typeof onSubscriptionStatusInvalidated==="function"){onSubscriptionStatusInvalidated()}};const onAccountChange=(e,t)=>{if(t===Store.ACCOUNT_CHANGE_REASON.UNIQUE_IDENTIFIER_CHANGED){onSubscriptionChange()}};const updateSubscriptionStatus=()=>hasSubscription().then(e=>{lastKnownIsSubscribedStatus=e;registerOnSubscriptionChange(onSubscriptionChange);registerOnAccountChange(onAccountChange)}).catch(e=>logger$5.error("Couldn't update subscription status for NowPlayingController",e));const isSubscribed=()=>{if(lastKnownIsSubscribedStatus!==null){return Promise.resolve(lastKnownIsSubscribedStatus)}return updateSubscriptionStatus().then(()=>lastKnownIsSubscribedStatus)};class NowPlayingController extends BaseClass$w{didLoad(){super.didLoad();this.updateMetricsReportingState();onSubscriptionStatusInvalidated=this.updateMetricsReportingState.bind(this)}didAppear(e){this.pageContext=currentPageContext();super.didAppear(e)}willUnload(){super.willUnload();onSubscriptionStatusInvalidated=undefined}shouldReportMetrics(){return isSubscribed()}updateMetricsReportingState(){this.shouldReportMetrics().then(e=>{if(e){this.startMetricsReporting()}else{this.stopMetricsReporting()}}).catch(e=>logger$5.error("Failed to update metrics reporting state",e))}startMetricsReporting(){this.metricsEnabled=true;this.pageFieldsForViewModelState().then(this.updatePageFields.bind(this)).then(this.considerRecordingPageEvent.bind(this)).catch(e=>logger$5.error("Failed to set fields for Now Playing page on load.",e));this.viewModel.onActionPerformed=(e,t,r,i,n)=>{const o={pageDetailsProvider:this};const s=metricsFieldsForNowPlayingViewModelAction(t,r,n);if(s){recordClickEvent(...clickMetricsForImpressions(e,o,s))}};this.viewModel.onModeChanged=()=>{this.pageFieldsForViewModelState().then(this.updatePageFieldsAndRecordPageEventIfNeeded.bind(this)).catch(e=>logger$5.error("Failed to record page event for Now Playing page on mode change",e))};this.viewModel.onCurrentItemChanged=()=>{this.pageFieldsForViewModelState().then(this.updatePageFieldsAndRecordPageEventIfNeeded.bind(this)).catch(e=>logger$5.error("Failed to record page event for Now Playing page on item change",e))}}stopMetricsReporting(){this.metricsEnabled=false;this.viewModel.onActionPerformed=undefined;this.viewModel.onModeChanged=undefined;this.viewModel.onCurrentItemChanged=undefined}pageFieldsForViewModelState(){const e=this.viewModel.mode;if(!NowPlayingViewModel.MODE){return Promise.resolve(PageFieldsForPage.nowPlayingControlsMode())}switch(e){case NowPlayingViewModel.MODE.CONTROLS:{const e=get(this.viewModel,"currentItem.hasTimeSyncedLyrics");const t=PageFieldsForPage.nowPlayingControlsMode(e);return Promise.resolve(t)}case NowPlayingViewModel.MODE.LYRICS:{const e=this.viewModel.currentItem;const t=PageFieldsForPage.nowPlayingLyricsMode(this.viewModel.lyricsMode,e);if(t){return Promise.resolve(t)}return new Promise(t=>{this.viewModel.onLyricsModeChanged=r=>{const i=PageFieldsForPage.nowPlayingLyricsMode(r,e);if(i){t(i)}}})}case NowPlayingViewModel.MODE.UP_NEXT_QUEUE:{const e=get(this.viewModel,"currentItem.hasTimeSyncedLyrics");const t=PageFieldsForPage.nowPlayingUpNextMode(e);return Promise.resolve(t)}default:return Promise.reject(new Error(`Couldn't derive page fields for unknown NowPlayingViewModel.MODE: ${e}`))}}updatePageFields(e){this.pageFields=e;this.pageIdentifier=get(e,"pageId");this.pageType=get(e,"pageType")}updatePageFieldsAndRecordPageEventIfNeeded(e){this.updatePageFields(e);this.onPagePresentationChanged()}}const VIEW_IDENTIFIERS_FOR_KNOWN_PATHNAMES={"/foryou":DeepLinkSegue.VIEW_IDENTIFIER.LISTEN_NOW_TAB,"/for-you":DeepLinkSegue.VIEW_IDENTIFIER.LISTEN_NOW_TAB,"/for_you":DeepLinkSegue.VIEW_IDENTIFIER.LISTEN_NOW_TAB,"/listennow":DeepLinkSegue.VIEW_IDENTIFIER.LISTEN_NOW_TAB,"/listen-now":DeepLinkSegue.VIEW_IDENTIFIER.LISTEN_NOW_TAB,"/new":DeepLinkSegue.VIEW_IDENTIFIER.BROWSE_TAB,"/browse":DeepLinkSegue.VIEW_IDENTIFIER.BROWSE_TAB,"/music_browse":DeepLinkSegue.VIEW_IDENTIFIER.BROWSE_TAB,"/beats1":DeepLinkSegue.VIEW_IDENTIFIER.RADIO_TAB,"/radio":DeepLinkSegue.VIEW_IDENTIFIER.RADIO_TAB,"/mymusic":DeepLinkSegue.VIEW_IDENTIFIER.LIBRARY_TAB,"/library":DeepLinkSegue.VIEW_IDENTIFIER.LIBRARY_TAB,"/connect":DeepLinkSegue.VIEW_IDENTIFIER.LISTEN_NOW_TAB,"/search":DeepLinkSegue.VIEW_IDENTIFIER.SEARCH_TAB};const FUZZY_MATCHES_FOR_PATHNAMES=[[/^\/radio-.+$/,DeepLinkSegue.VIEW_IDENTIFIER.RADIO_TAB],[/^\/browse-.+$/,DeepLinkSegue.VIEW_IDENTIFIER.BROWSE_TAB]];function attemptToMatchPathname(e={}){const{protocol:t,pathname:r=""}=e;let i=VIEW_IDENTIFIERS_FOR_KNOWN_PATHNAMES[r.toLowerCase()];if(!i&&t==="itsradio:"){i=DeepLinkSegue.VIEW_IDENTIFIER.RADIO_TAB}if(!i){FUZZY_MATCHES_FOR_PATHNAMES.some(([e,t])=>{const n=e.test(r);if(n){i=t}return n})}return i}function createPushSeguesForKnownURL(e,t){const r=[];const{browseNavigationData:i}=t;let{pathname:n}=e;const o=get(i,"pageData.links",[]);const s=get(i,"pageData.radioLinks",[]).concat(o);let a;n=n.indexOf("/")===0?n.slice(1):n;s.forEach(e=>{const t=get(e,"path","");if(t===n){a=e}});if((a||n==="beats1")&&n!=="radio"){const e=get(a,"label")||"Beats 1";const i=get(a,"url")||"https://itunes.apple.com/beats1";Object.assign(t,{title:e,showsLargeTitleHeader:true});r.push(createPushSegueForURL(i,t))}return r}function createKnownURLSegue(e,t){let r;let i;const n=url.parse(e,true);const{pathname:o}=n;if(o){i=attemptToMatchPathname(n)}if(i){const e=createPushSeguesForKnownURL(n,t);r=Promise.resolve(createDeepLinkSegue({viewIdentifier:i,pushSegues:e}))}else if(e.indexOf("notificationSettings")!==-1){const e=new NotificationPreferencesController;if(n.query.enableNewArtistContent){e.enablingNewArtistContentFromDeepLink=true}r=Promise.resolve(createPresentationSegue({componentController:e}))}else if(e.indexOf("onboarding")!==-1){r=considerCreatingOnboardingSeguePromise()}else if(o==="/redeem"||o&&o.indexOf("redeemLandingPage")!==-1){r=Promise.resolve(createFinanceSegue(e,t))}else if(o==="/sharing"){r=considerCreatingSocialOnboardingSegue(true)}else if(o==="/account/subscriptions"){const e=getBagValueSync("manageSubscriptionsUrl");const i=constructURL(e,{params:{subscriptionType:"music"}});r=Promise.resolve(createFinanceSegue(i,t))}return r}function getRoomIdFromURL(e){const t=url.parse(e,true);const{pathname:r}=t;let i=null;if(typeof r==="string"){const e=r.match(/^(?:\/\w{2}\/room\/)/);if(e){const e=r.match(/(\d.*)$/);i=e?.[0]||null}}return i}function getRoomSegue(e,t){const r=e?`https://music.apple.com/WebObjects/MZStore.woa/wa/viewRoom?fcId=${e}`:null;if(r){return constructDeeplinkSegue(r,Object.assign(t)).then(e=>e)}logger$5.warn("Deeplink request to room failed with no roomId");return createNoopSegue()}function constructRoomSegue(e,t){const r=getRoomIdFromURL(e);if(r){return getRoomSegue(r,t)}return Promise.resolve(null)}function getMultiRoomIdFromURL(e){const t=url.parse(e,true);const{pathname:r}=t;let i=null;if(typeof r==="string"){const e=r.match(/^(?:\/\w{2}\/multi-room\/)/);if(e){const e=r.match(/(\d.*)$/);i=e?.[0]||null}}return i}function getMultiRoomSegue(e,t){const r=e?`https://music.apple.com/WebObjects/MZStore.woa/wa/viewMultiRoom?fcId=${e}`:null;if(r){return constructDeeplinkSegue(r,Object.assign(t)).then(e=>e)}logger$5.warn("Deeplink request to multiRoom failed with no multiRoomId");return createNoopSegue()}function constructMultiRoomSegue(e,t){const r=getMultiRoomIdFromURL(e);if(r){return getMultiRoomSegue(r,t)}return Promise.resolve(null)}function getGroupingIdFromURL(e){const t=url.parse(e,true);const{pathname:r}=t;let i=null;if(typeof r==="string"){const e=r.match(/^(?:\/\w{2}\/grouping\/)/);if(e){const e=r.match(/(\d.*)$/);i=e?.[0]||null}}return i}function getGroupingSegue(e,t){const r=e?`https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewGrouping?id=${e}`:null;if(r){return constructDeeplinkSegue(r,Object.assign(t)).then(e=>e)}logger$5.warn("Deeplink request to grouping failed with no groupingId");return createNoopSegue()}function constructGroupingSegue(e,t){const r=getGroupingIdFromURL(e);if(r){return getGroupingSegue(r,t)}return Promise.resolve(null)}function getPersonalMixIdFromURL(e){const t=url.parse(e,true);const{pathname:r}=t;let i=null;if(typeof r==="string"){const e=r.match(/^(?:\/\w{2}\/personal-mix\/.*\/)((mx\.rp-\d{4})|(mx\.\d{1,2}))$/);i=e?.[1]}return i}function getPersonalizedRadioStationIdFromURL(e){const t=url.parse(e,true);const{pathname:r}=t;let i=null;if(typeof r==="string"){const e=r.match(/^(?:\/\w{2}\/personal-station\/.*\/)(rm\.[A-Za-z0-9-].*)$/);i=e?.[1]}return i}function constructPersonalMixErrorSegue(e){return waitForLocInitialization().then(()=>{const t=e?localize("FUSE.ListenNow.PersonalMix.Deeplink.Subscriber.Title"):localize("FUSE.ListenNow.PersonalMix.Deeplink.NonSubscriber.Title");const r=e?localize("FUSE.ListenNow.PersonalMix.Deeplink.Subscriber.Explanation"):localize("FUSE.ListenNow.PersonalMix.Deeplink.NonSubscriber.Explanation");const i=e?localize("FUSE.ListenNow.PersonalMix.Deeplink.Subscriber.CTA"):localize("FUSE.ListenNow.PersonalMix.Deeplink.NonSubscriber.CTA");const n=e?"https://music.apple.com/listennow":"https://music.apple.com/subscribe";const o=createAlertAction({title:i,onSelect:()=>createRedirectSegue({url:n})});const s=createAlertViewModel({title:t,message:r,alertActions:[o]});const a=createAlertComponentController({viewModel:s});return createPresentationSegue({componentController:a})})}function getPersonalizedRadioStationSegueFromMusicAPI(e,t,r){return getBagValue("countryCode").then(t=>{const r=new MusicAPIURL(`/v1/catalog/${t}/stations`);r.queryString.addParameters({"filter[identity]":e});return r.string()}).then(e=>requestMusicAPIResource(e)).then(e=>{const i=e.data?.[0]?.id;const n=e.resources?.stations?.[i]?.attributes?.url;if(n){return constructDeeplinkSegue(n,Object.assign(t)).then(e=>e)}return constructPersonalMixErrorSegue(r)}).catch(t=>{logger$5.error("Request to music api failed for stationId",e,t)})}function getPersonalMixSegueFromMusicAPI(e,t,r){return getBagValue("countryCode").then(t=>{const r=new MusicAPIURL(`/v1/catalog/${t}/playlists`);r.queryString.addParameters({"filter[personal-mix]":e});return r.string()}).then(e=>requestMusicAPIResource(e)).then(e=>{const i=e.data?.[0]?.id;const n=e.resources?.playlists?.[i]?.attributes?.url;if(n){return createURLSegue(n,Object.assign(t)).then(e=>e)}return constructPersonalMixErrorSegue(r)}).catch(t=>{logger$5.error("Request to music api failed for personalMixId",e,t)})}function getPersonalMixSegueCheckingForSubscriber(e,t){return hasSubscription().then(r=>{if(r){return getPersonalMixSegueFromMusicAPI(e,t,r)}return constructPersonalMixErrorSegue(r)})}function isPersonalStationURL(e){const t=url.parse(e,true);const{pathname:r}=t;if(typeof r==="string"){const t=new RegExp(/\/\w{2}\/station\/me$/,"i");return t.test(e)}}function getPersonalizedRadioStationSegueCheckingForSubscriber(e,t){return hasSubscription().then(r=>{if(r){return getPersonalizedRadioStationSegueFromMusicAPI(e,t,r)}return constructPersonalMixErrorSegue(r)})}function getPersonalStationSegueFromMusicAPI(e){return getBagValue("countryCode").then(e=>{const t=new MusicAPIURL(`/v1/catalog/${e}/stations`);t.queryString.addParameters({"filter[identity]":"personal"});return t.string()}).then(e=>requestMusicAPIResource(e)).then(t=>{const r=t.data?.[0]?.id;const i=t.resources?.stations?.[r]?.attributes?.url;if(i){return constructDeeplinkSegue(i,Object.assign(e)).then(e=>e)}return createNoopSegue()}).catch(e=>{logger$5.error("Request to music api failed for personal station",e)})}function getPersonalStationSegueCheckingForSubscriber(e){return hasSubscription().then(t=>{if(t){return getPersonalStationSegueFromMusicAPI(e)}return createNoopSegue()})}function isPersonalGenreStationURL(e){const t=url.parse(e,true);const{pathname:r}=t;if(typeof r==="string"){const t=new RegExp(/\/\w{2}\/genre-stations|station-genres\//,"i");return t.test(e)}}function getPersonalGenreStationSegueFromMusicAPI(e,t){return getBagValue("countryCode").then(t=>{const r=new MusicAPIURL(`/v1/catalog/${t}/search/query`);const i=url.parse(e,true);const{query:n}=i;Object.entries(n).forEach(([e,t])=>{r.queryString.addParameters({[`filter[${e}]`]:t})});return r.string()}).then(e=>requestMusicAPIResource(e)).then(e=>{const r=e.data?.[0]?.id;const i=e.resources?.stations?.[r]?.attributes?.url;if(i){return constructDeeplinkSegue(i,Object.assign(t)).then(e=>e)}return createNoopSegue()}).catch(e=>{logger$5.error("Request to music api failed for genre station",e)})}function getPersonalGenreStationSegueCheckingForSubscriber(e,t){return hasSubscription().then(r=>{if(r){return getPersonalGenreStationSegueFromMusicAPI(e,t)}return createNoopSegue()})}function isReplayURL(e){const t=url.parse(e,true);const{pathname:r}=t;if(r==="/replay"){return true}return false}function getReplayMixIdFromDate(e=new Date){const t=e.getFullYear();const r=e.getMonth();const i="mx.rp-";const n=3;if(r{const t={};t[dynamicAMSUISegueForURL.OPTION_KEYS.OFFER_HINT]=dynamicAMSUISegueForURL.OFFER_HINTS.VOICE;return dynamicAMSUIURLForPlacement(dynamicAMSUIURLForPlacement.PLACEMENTS.LAUNCH_UPSELL).then(r=>dynamicAMSUISegueForURL(r,Object.assign(e,t)))})}function constructVoiceUpsellSegue(e,t){if(isVoiceURL(e)){return getVoiceUpsellSegueCheckingForSubscriber(t)}return Promise.resolve(null)}function getSongIdFromURL(e){const t=url.parse(e,true);const{pathname:r}=t;let i=null;if(typeof r==="string"){const e=r.match(/^(?:\/\w{2}\/song\/)(\d.*)$/);i=e?.[1]}return i}function getAlbumWithSongIDSegue(e,t){return getBagValue("countryCode").then(t=>{const r=new MusicAPIURL(`/v1/catalog/${t}/songs/${e}?relate=albums`);return r.string()}).then(e=>requestMusicAPIResource(e)).then(e=>{const r=e.data?.[0]?.id;const i=e.resources?.songs?.[r]?.attributes?.url;if(i){return constructDeeplinkSegue(i,Object.assign(t)).then(e=>e)}return createNoopSegue()}).catch(t=>{logger$5.error(`Deeplink request to music api failed for song url with song id ${e}`,t)})}function constructSongSegue(e,t){const r=getSongIdFromURL(e);if(r){return getAlbumWithSongIDSegue(r,t)}return Promise.resolve(null)}function placementForMarketingCampaignByIdentifier(e){switch(e){case placementForMarketingCampaignByIdentifier.IDENTIFIERS.CAR_PLAY_UPSELL_V1:return dynamicAMSUIURLForPlacement.PLACEMENTS.MUSIC_PRE_BUY;case placementForMarketingCampaignByIdentifier.IDENTIFIERS.PREVIEW:return dynamicAMSUIURLForPlacement.PLACEMENTS.MUSIC_VOICE_UPSELL;default:return null}}placementForMarketingCampaignByIdentifier.IDENTIFIERS={CAR_PLAY_UPSELL_V1:"marketing-carplay-upsell",IAM_DEEPLINK:"in-app-messages",PREVIEW:"preview"};function marketingIdentifiersFromURL(e){const t=url.parse(e);const r=t.host;let i=null;if(Object.values(placementForMarketingCampaignByIdentifier.IDENTIFIERS).includes(r)){i=r}if(!i){return null}let n=t.pathname;if(n&&n.startsWith("/")){n=n.substring(1)}const o={};const s=t.query;if(s){const e=s.split("&");e.forEach(e=>{const t=e.split("=");const r=t?.[0];const i=t?.[1];o[r]=i})}return{matchedIdentifier:i,messageIdentifier:n,parameterMap:o}}function hasRadioIds(e){let t;if(typeof e==="string"){t=e.match(/st\.[a-zA-Z0-9-]+|ra\.[a-zA-Z0-9-]+/g)}return t}function getPlaybackDataForUrl(e){const t=url.parse(e,true);const{pathname:r,query:i}=t;const n=r==="/beats1";let o=hasRadioIds(r);let s;if(i){const e=i.i;const t=r?r.match(/id[0-9]+/):null;const n=t?t[0].replace("id",""):null;const s=i.autoplay==="true";if(e&&s){o=[e]}else if(n&&s){o=[n]}}if(n){s=fetchDataForBeats1()}else if(o){s=fetchDataForID(o[0])}else{s=Promise.resolve({})}return s}function replaceProtocolsWithHttps(e){const t=url.parse(e,true);const{protocol:r=""}=t;t.protocol=r.replace(/^(music:|musics:|itsradio:|http:)/,"https:");return url.format(t)}function constructFinanceFlowSegue(e,t){const r=URLPatternMatcher.typeForURL(e);if(r===URLPatternMatcher.TYPES.CONTENT_TYPE){return}if(r===URLPatternMatcher.TYPES.AMS_DYNAMIC_TYPE){return dynamicAMSUISegueForURL(replaceProtocolsWithHttps(e),t)}if(r===URLPatternMatcher.TYPES.COMMERCE_APP_TYPE){return createFinanceSegue(replaceProtocolsWithHttps(e),t)}return getBagValue("financeApp").catch(e=>{if(!(e instanceof BagError)){throw e}}).then((r={})=>{const{baseUrl:i=""}=r;const n=i.replace(/^(https?:)/,"");if(e.indexOf(n)!==-1||e.indexOf("MZFinance.woa")!==-1){return createFinanceSegue(replaceProtocolsWithHttps(e),t)}const o=url.parse(e,true);let s=get(o,"pathname")||"/";const a=s.split("/");const l=a[a.length-1];if(l==="redeem"){const r=e.indexOf("itunes.apple")!==-1?e.replace("itunes.apple","music.apple"):e;return createFinanceSegue(replaceProtocolsWithHttps(r),t)}const c=get(o,"search","");if(s==="/"&&get(o,"hostname")==="subscribe"){s="subscribe"}const u=createSegueToFinanceSync(s,c,t,"",r,["genericDeeplinks","musicDeeplinks","musicInternal"]);if(u){return u}return false})}function isResponseDialog(e){return get(e,"output.dialog")&&get(e,"ok")}function createArtistUploadedContentSegue(e={}){const t=["uploadedAudio","uploadedVideo"];const r=get(e,"storePlatformData.lockup.results",{});const i=get(e,"activity.targetId");const n=get(e,"activity.targetType");const o=get(e,"activity.ownerEntityId");const s=t.indexOf(n)!==-1;const a=get(e,"activity.url");if(s){const e=r[i];if(isUserSignedIn()&&e){return Promise.resolve(createNowPlayingSegue({storePlatformDictionary:e}))}const t=get(r[o],"url");if(t){return Promise.resolve(createRedirectSegue({url:t}))}logger$5.warn(`No curator content for post url ${a}.`);return createNoopSegue()}logger$5.warn(`Unsupported artist uploaded content post of kind ${n} for post url ${a}.`);return createNoopSegue()}function getViewIdentifierForUnknownURL(e,t){const r=e.match(/\/profile\/|\/socialProfile\?/);const i=e.match(/\/pl\.pm-|\/pl\.rp-/);const n=t?.subscriptionStatus?.isSubscribed;if(r||i||!n){return DeepLinkSegue.VIEW_IDENTIFIER.LISTEN_NOW_TAB}return DeepLinkSegue.VIEW_IDENTIFIER.BROWSE_TAB}function constructUnknownURLSegueWithPageData(e,t,r){const i=getViewIdentifierForUnknownURL(e,t);const n=r?Object.assign({pageData:r},t):t;const o=[createPushSegueForURL(e,n)];return createDeepLinkSegue({viewIdentifier:i,pushSegues:o})}function constructUnknownURLSegueRequestingPageData(e,t){const r=url.parse(e,true);const{pathname:i}=r;const n=hasRadioIds(i);let o;if(n){o=Promise.resolve(createNowPlayingSegue())}else{const r=replaceProtocolsWithHttps(e);const i=r.match(/\/post\//);const n=constructUnknownURLSegueWithPageData(r,t);if(!i&&n){return Promise.resolve(n)}o=fetchJSON(r).then(e=>{const i=get(e,"componentName");if(!i&&get(e,"activity")){return createArtistUploadedContentSegue(e)}return constructUnknownURLSegueRequestingPageData(r,t)}).catch(e=>{if(!isResponseDialog(get(e,"response"))){logger$5.error(e)}})}return o}function createURLSegue(e,t){const r=createKnownURLSegue(e,t);if(r){return r}return constructUnknownURLSegueRequestingPageData(e,t)}function getBrowseNavigationData(){return getBagValue("musicSubscription.browseNavigation").then(e=>fetchJSON(e))}function constructDeeplinkSegue(e,t){return Promise.all([getBrowseNavigationData(),getPlaybackDataForUrl(e),getSubscriptionStatus()]).then(([r,i={},n])=>createURLSegue(e,Object.assign(t,{browseNavigationData:r,subscriptionStatus:n})).then(e=>{if(e&&Object.keys(i).length>0){const t=getPlaybackIntentForContent(i);t.playActivityFeatureName="transient";e.playbackIntent=t}return e}))}function formatURLAndCheckForAllowListedHostname(e){return getBagValue("trustedDomains").then((t=[])=>{t.push("subscribe");t.push("notificationsettings");t.push(...URLPatternMatcher.trustedDomainForType(URLPatternMatcher.TYPES.COMMERCE_APP_TYPE));t.push(...URLPatternMatcher.trustedDomainForType(URLPatternMatcher.TYPES.AMS_DYNAMIC_TYPE));const r=url.parse(e,true);const{hostname:i,pathname:n}=r;let o;let s;function endsWith(e,t){return e.indexOf(t,e.length-t.length)!==-1}t.forEach(e=>{const t=e.replace("*","");if(t.match(/^\./)&&endsWith(i,t)){o=true}else if(i===t){o=true}});if(!o){const e=`untrusted domain: ${r.hostname}`;throw new Error(e)}if(n&&n.indexOf("deeplink")!==-1){r.pathname=get(r,"query.p","");s=url.format(r)}else{s=e}return s})}function checkAffiliateParams(e){return getBagValue("processRedirectUrl").then((t={})=>{const r=url.parse(e,true);const{whitelistedQueryParams:i=[],endpoint:n=""}=t;const o=Object.keys(r.query||{});const s=o.reduce((e,t)=>e||i.indexOf(t)!==-1,false);let a;if(s){a=fetchJSON(n,{method:HTTP.METHOD.POST,queryItems:{url:e},timeout:1e3})}return a}).then((t={})=>{const{redirectUrl:r=e,setCookies:i=[]}=t;i.forEach(e=>{setCookie(e.name,e.value,e)});return r}).catch(t=>{logger$5.error(t);return e})}function modifyDeeplinkURLHack(e){let t=e;if(Device.systemVersion==="14.1"){t=decodeURI(e);const r=url.parse(t);const i=r.query;if(!i){return e}const n=i.split("&");const o=Object.keys(n);let s=`${r.protocol}//${r.host}${r.pathname}?`;n.forEach((e,t)=>{const r=e.split("=");const i=r?.[0];let n=r?.[1];n=n?.replace(/:\s*/g,"%3A").replace(/[/]/g,"%2F").replace(/=/g,"%3D").replace(/[?]/g,"%3F");if(i&&n){s+=`${i}=${n}`;if(tcheckAffiliateParams(e)).then(e=>Promise.all([e,constructFinanceFlowSegue(e,n)])).then(([e,t])=>{if(t){return[e,t]}return Promise.all([e,constructPersonalizedMediaSegue(e,n)])}).then(([e,t])=>{if(t){return[e,t]}return Promise.all([e,constructRoomSegue(e,n)])}).then(([e,t])=>{if(t){return[e,t]}return Promise.all([e,constructMultiRoomSegue(e,n)])}).then(([e,t])=>{if(t){return[e,t]}return Promise.all([e,constructGroupingSegue(e,n)])}).then(([e,t])=>{if(t){return[e,t]}return Promise.all([e,constructLyricsUpsellSegue(e,n)])}).then(([e,t])=>{if(t){return[e,t]}return Promise.all([e,constructVoiceUpsellSegue(e,n)])}).then(([e,t])=>{if(t){return[e,t]}return Promise.all([e,constructSongSegue(e,n)])}).then(([e,t])=>t||constructDeeplinkSegue(e,n)).then(e=>e||createNoopSegue()).catch(e=>{logger$5.error("Failed to perform deeplink from URL",i,e);return createNoopSegue()}).then(e=>r(e))}function handleCampaignMarketingPreview(e,t){if(!!e.marketingMessageIdentifier?.parameterMap?.bypassPurchase===true){attemptPreviewPlaybackForOptions(e.marketingMessageIdentifier,t)}else{return previewPurchaseSegueForPurchaseOptions(e).then(e=>e||createNoopSegue()).catch(t=>{logger$5.error("Failed to perform preview purchase for identifier",e.marketingMessageIdentifier,t);return createNoopSegue()}).then(e=>t(e))}}function handleCampaignMarketingInAppMessageDeeplink(e){const t=e.marketingMessageIdentifier;if(t){Application.triggerMessagePresentationWithIdentifier(t)}else{logger$5.error("Failed to perform IAM deeplink for identifier. Message Identifier is missing",t)}}function handleCampaignMarketingDefaultDeeplink(e,t,r){return dynamicAMSUIURLForPlacement(placementForMarketingCampaignByIdentifier(e)).then(e=>constructFinanceFlowSegue(e,t)).then(e=>e||createNoopSegue()).catch(t=>{logger$5.error("Failed to perform marketing deeplink for identifier",e,t);return createNoopSegue()}).then(e=>r(e))}function performDeeplinkFromFromMarketingCampaignIdentifier(e,t,r){switch(e){case placementForMarketingCampaignByIdentifier.IDENTIFIERS.IAM_DEEPLINK:return handleCampaignMarketingInAppMessageDeeplink(t);case placementForMarketingCampaignByIdentifier.IDENTIFIERS.PREVIEW:return handleCampaignMarketingPreview(t,r);default:return handleCampaignMarketingDefaultDeeplink(e,t,r)}}class UserNotificationAuthorizationController extends ComponentController{constructor(){super();this.viewModel=new UserNotificationAuthorizationViewModel;this.viewModel.isModalInPresentation=false;this.viewModel.metricsOverlay={topic:DEFAULT_TOPIC,pageContext:currentPageContext(),dsId:Store.account.uniqueIdentifier};this.viewModel.onUserNotificationAuthorizationDidComplete=e=>{logger$5.log("onUserNotificationAuthorizationDidComplete");e(null)};logger$5.log("Creating UserNotificationAuthorizationViewModel")}didLoad(){super.didLoad();logger$5.log("UserNotificationAuthorizationController did load")}didDisappear(e,t){super.didDisappear(e,t);logger$5.log("UserNotificationAuthorizationController did disappear.")}}const ObjectGraphType={EDITORIAL_ELEMENT_COLLECTED_MARKERS:"editorialElementCollectedMarkers",EDITORIAL_ELEMENT_SECTION_FILTER:"editorialElementSectionFilter"};class ObjectGraph{constructor(e){this._members={};this.name=e}adding(e,t){const r=this.clone();r._members[e]=t;return r}removing(e){const t=this.clone();delete t._members[e];return t}optional(e){return this._members[e]}required(e){const t=this._members[e];if(!t){const t=Object.keys(this._members).sort().join(", ");throw new Error(`No member with type ${e} found in ${this.name}. Candidates ${t}`)}return t}clone(){const e=new ObjectGraph(this.name);Object.assign(e._members,this._members);return e}}const EditorialElementKind={HERO_LIST_SHELF:"316",HERO:"317",COPPER_SWOOSH:"326",TAB_ROOT:"382",BRICK_SWOOSH:"385",BRICK:"386",CUSTOM_BRICK:"394"};const MarkerEditorialElementKinds=new Set([EditorialElementKind.RecentlyPlayedRadioMarker]);function isMarkerEditorialElementKind(e){return MarkerEditorialElementKinds.has(e)}const SectionEditorialElementKinds=new Set([EditorialElementKind.HERO_LIST_SHELF,EditorialElementKind.COPPER_SWOOSH,EditorialElementKind.BRICK_SWOOSH]);function isSectionEditorialElement(e){return SectionEditorialElementKinds.has(e)}const editorialElementResourceSymbol=Symbol("editorialElementResource");const resourceManagerSymbol$3=Symbol("resourceManager");class EditorialChildController extends ContainerChildController{constructor(e,t){super();this.editorialElementResource=e;this.resourceManager=t}get resourceManager(){return this[resourceManagerSymbol$3]}set resourceManager(e){this[resourceManagerSymbol$3]=e}get editorialElementResource(){return this[editorialElementResourceSymbol]}set editorialElementResource(e){this[editorialElementResourceSymbol]=e}}class BrickSwooshEditorialController extends EditorialChildController{loadViewModel(){const e=this.editorialElementResource;const t=this.resourceManager;const r=e.relationships?.children?.data;if(!r||r.length===0){logger$5.warn(`Dropping brick swoosh shelf with id '${e.id}' and type '${e.type}', missing child resource identifiers.`);return null}const i=[];r.forEach(e=>{const r=t.resourceForResourceIdentifier(e);const n=r.attributes;if(!n){logger$5.warn(`Dropping brick swoosh shelf item with id '${r.id}' and type '${r.type}', missing resource attributes.`);return null}let o;const s=r.attributes?.editorialElementKind;switch(s){case EditorialElementKind.BRICK:o=this.brickLockup(r);break;case EditorialElementKind.CUSTOM_BRICK:o=this.customBrickLockup(r);break;default:logger$5.warn(`Dropping brick swoosh item resource with id '${r.id}' and type '${r.type}', invalid editorialElementKind '${s}'.`);break}if(o){i.push(o)}});if(!i.length){return null}const n=createShelfSection({items:i,uniformCellType:ShelfSection.UNIFORM_CELL_TYPE.FEATURED_MUSIC_VIDEO});return createShelf({title:e.attributes?.name,sections:[n]})}brickLockup(e){const t=this.resourceManager;const r=e.relationships?.contents?.data?.[0];if(!r){logger$5.warn(`Dropping editorial brick lockup item with id '${e.id}' and type '${e.type}', missing content resource identifier.`);return null}const i=t.resource(r);if(!i){return null}const n=i.attributes;if(!n){logger$5.warn(`Dropping editorial brick lockup item with id '${e.id}' and type '${e.type}', missing content resource attributes.`);return null}const o=n.artistName??n.curatorName??n.editorialNotes?.tagline;return createShelfItem({title:n.name,subtitle:o,backgroundArtwork:createArtwork({dictionary:n.editorialArtwork?.subscriptionHero,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),displayStyle:"small",onSelect:onSelectHandlerForMusicAPIResourceIdentifier(r,i),identifierSet:identifierSetForMusicAPIResourceIdentifier(r)})}customBrickLockup(e){const t=e.relationships?.contents?.data?.[0];if(!t){logger$5.warn(`Dropping editorial brick lockup item with id '${e.id}' and type '${e.type}', missing content resource identifier.`);return null}const r=this.resourceManager.resource(t);if(!r){return null}const i=r.attributes;if(!i){logger$5.warn(`Dropping editorial brick lockup item with id '${e.id}' and type '${e.type}', missing content resource attributes.`);return null}const n=i.artistName??i.curatorName??i.editorialNotes?.tagline;return createShelfItem({title:e.attributes?.designTag,name:i.name,subtitle:n,backgroundArtwork:createArtwork({dictionary:e.attributes?.artwork,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),identifierSet:identifierSetForMusicAPIResourceIdentifier(t),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(t,r)})}}const DisplayStyle={COMPACT:"compact",EXPANDED:"expanded"};class CopperSwooshEditorialController extends EditorialChildController{loadViewModel(){const e=this.editorialElementResource;const t=e.relationships?.contents?.data;if(!t||t.length===0){logger$5.warn(`Dropping copper swoosh with id '${e.id}' and type '${e.type}', missing child resource identifiers.`);return null}const r=e.attributes?.displayStyle??DisplayStyle.COMPACT;switch(r){case DisplayStyle.COMPACT:return this.compactSwoosh();case DisplayStyle.EXPANDED:logger$5.error("Expanded swoosh is not yet handled");return null;default:logger$5.warn(`Dropping copper swoosh view model with id '${e.id}' and type '${e.type}', unsupported displayStyle '${r}'.`);return null}}compactSwoosh(){const e=this.editorialElementResource;const t=e.relationships?.contents?.data;if(!t||t.length===0){logger$5.warn(`Dropping compact copper swoosh with id '${e.id}' and type '${e.type}', missing child resource identifiers.`);return null}const r=t[0];const i=r.type;switch(i){case MusicAPIResourceType.MUSIC_MOVIES:case MusicAPIResourceType.MUSIC_VIDEOS:return this.shelfItem(ShelfSection.UNIFORM_CELL_TYPE.FEATURED_MUSIC_VIDEO);case MusicAPIResourceType.CURATORS:case MusicAPIResourceType.ARTISTS:case MusicAPIResourceType.SOCIAL_PROFILES:logger$5.error(`Dropping compact copper swoosh shelf item with id '${e.id}' and type '${e.type}', circles not yet handled`);return null;default:logger$5.warn(`Dropping compact copper swoosh shelf item with id '${e.id}' and type '${e.type}', unsupported first child type '${i}'.`);return null}}shelfItem(e){const t=this.editorialElementResource;const r=this.resourceManager;const i=t.relationships?.contents?.data;if(!i||i.length===0){logger$5.warn(`Dropping copper swoosh shelf item with id '${t.id}' and type '${t.type}', missing child resource identifiers.`);return null}const n=[];i.forEach(e=>{const t=r.resourceForResourceIdentifier(e);const i=t.attributes;if(!i){logger$5.warn(`Dropping copper swoosh shelf item with id '${t.id}' and type '${t.type}', missing resource attributes.`);return null}const o={headline:i.name,title:i.name,subtitle:i.artistName,backgroundArtwork:createArtwork({dictionary:i.artwork,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),displayStyle:"small",name:i.name,identifierSet:identifierSetForMusicAPIResourceIdentifier(e),onSelect:onSelectHandlerForMusicAPIResourceIdentifier(e,t)};n.push(createShelfItem(o))});if(n.length===0){return null}const o=createShelfSection({items:n,uniformCellType:e});return createShelf({title:t.attributes?.name??t?.attributes?.title,sections:[o]})}}const TYPES_WITH_COVER_ARTWORK=[MusicAPIResourceType.MUSIC_VIDEOS];class HeroListEditorialController extends EditorialChildController{loadViewModel(){const e=this.editorialElementResource;const t=this.resourceManager;const r=e.relationships?.children?.data;if(!r||r.length===0){logger$5.warn(`Dropping hero list shelf with id '${e.id}' and type '${e.type}', missing child resource identifiers.`);return null}const i=[];r.forEach(e=>{const r=t.resourceForResourceIdentifier(e);let n;const o=r.attributes?.editorialElementKind;switch(o){case EditorialElementKind.HERO:n=this.editorialFlowcaseItem(r,t,false);break;default:logger$5.warn(`Dropping hero list item resource with id '${r.id}' and type '${r.type}', invalid editorialElementKind '${o}'.`);break}if(n){i.push(n)}});if(i.length===0){return null}return createFlowcase({items:i})}editorialFlowcaseItem(e,t,r){const i=e.relationships?.contents?.data?.[0];if(!i){return this.editorialLinkFlowcaseItem(e)}const n=t.resourceForResourceIdentifier(i);if(!n){return null}const o=n.attributes;if(!o){logger$5.warn(`Dropping editorial flowcase item with id '${e.id}' and type '${e.type}', missing content resource attributes.`);return null}let s;if(TYPES_WITH_COVER_ARTWORK.includes(n.type)){s=createArtwork({dictionary:o.artwork})}const a=e.attributes?.designBadge;const l=identifierSetForMusicAPIResourceIdentifier(i);const c=o.artistName??o.curatorName??o.editorialNotes?.tagline??o.genreNames?.[0]??o.editorialNotes?.short;const u=o.editorialArtwork?.subscriptionHero??o.editorialArtwork?.subscriptionCover;return createFlowcaseItem({heading:a,title:r?e.attributes?.designTag:o.name,subtitle:c,backgroundArtwork:createArtwork({dictionary:u,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),identifierSet:l,description:o.editorialNotes?.short??o.plainEditorialNotes?.short,coverArtwork:s,onSelect:onSelectHandlerForMusicAPIResourceIdentifier(i,n,null,false,l)})}editorialLinkFlowcaseItem(e){const t=e.attributes;if(!t){logger$5.warn(`Dropping editorial flowcase item with id '${e.id}' and type '${e.type}', missing attributes.`);return null}if(!t.artwork){logger$5.warn(`Dropping flowcase because no artwork was found: ${JSON.stringify(e)}`);return null}return createFlowcaseItem({heading:t.designBadge,title:t.designTag,backgroundArtwork:createArtwork({dictionary:t.artwork,cropStyle:Artwork.CROP_STYLE.SPECIFIC_RECTANGLE}),onSelect:createRedirectSegue({url:t.link?.url})})}}function childViewModelControllerForTabRootSection(e,t,r,i){const n=e.attributes?.editorialElementKind;if(!n){logger$5.warn(i,`Dropping section with id '${e.id}', type '${e.type}', missing editorialElementKind.`);return null}if(!isSectionEditorialElement(n)){logger$5.warn(i,`Dropping section with id '${e.id}', type '${e.type}', editorialElementKind '${n}' is not a section.`);return null}const o=i.optional(ObjectGraphType.EDITORIAL_ELEMENT_SECTION_FILTER);if(o&&!o?.filterEditorialElementKind(n)){return null}switch(n){case EditorialElementKind.HERO_LIST_SHELF:return new HeroListEditorialController(e,r);case EditorialElementKind.COPPER_SWOOSH:return new CopperSwooshEditorialController(e,r);case EditorialElementKind.BRICK_SWOOSH:return new BrickSwooshEditorialController(e,r);default:logger$5.warn(`Unhandled case: '${n}'. Music JS currently only supports a limited number of editorial element kinds `)}}function childViewModelControllersForTabRootResourceIdentifiers(e,t,r,i){if(!e||e.length===0){throw new Error("No resource identifiers in tab root.")}const n=[];r.resourcesForResourceIdentifiers(e).forEach(e=>{const o=childViewModelControllerForTabRootSection(e,t,r,i);if(o){n.push(o)}});return n}function childViewModelControllersForTabRoot(e,t,r){const i=e.relationships?.children?.data;return childViewModelControllersForTabRootResourceIdentifiers(i,false,t,r)}function findTabRootResource(e,t){if(e.length===0){throw new Error("No root resource identifiers in editorial page response")}if(e.length>1){logger$5.warn("Received more than one top-level resource identifer in the editorial page response, dropping all but the first.")}const r=e[0];const i=t.resourceForResourceIdentifier(r);if(!i){throw new Error(`Missing top-level grouping resource with id '${r.id}' and type '${r.type}', in editorial page response.`)}if(i.type!==MusicAPIResourceType.GROUPINGS){throw new Error(`Top-level resource in editorial page response with id '${r.id}' and type '${r.type}' must be of type '${MusicAPIResourceType.GROUPINGS}'`)}const n=i.relationships?.tabs?.data;if(!n||n.length===0){throw new Error(`Top-level group resource with id '${i.id}' and type '${i.type}', missing tab resource identifers.`)}if(n.length>1){logger$5.warn("Received more than one grouping child resource identifer in the editorial page response, dropping all but the first.")}const o=n[0];const s=t.resourceForResourceIdentifier(o);if(!s){throw new Error(`Missing tab root resource with id '${o.id}' and type '${o.type}', in editorial page response.`)}if(s.type!==MusicAPIResourceType.EDITORIAL_ELEMENTS){throw new Error(`Tab root resource with id '${o.id}' and type '${o.type}' must be of type '${MusicAPIResourceType.EDITORIAL_ELEMENTS}.`)}const a=s.attributes?.editorialElementKind;if(a!==EditorialElementKind.TAB_ROOT){throw new Error(`Tab root resource with id '${o.id}' and element kind '${a}' must be a tab root.`)}return s}const pageMetricsControllerSymbol$4=Symbol("pageMetricsController");const URLPromiseSymbol$2=Symbol("URLPromise");const metricsPageFieldsSymbol$2=Symbol("metricsPageFields");const BaseClass$x=mix(ContainerChildController).with(RequestDrivenControllerMixin,MusicAPIRequestDrivenControllerMixin);class EditorialController extends BaseClass$x{constructor(e,t=false,r={pageType:"Editorial",pageId:"EditorialPage"}){super();this.URLPromise=e;this.metricsPageFields=r;if(t){this.invalidateCachedPageResource()}}get URLPromise(){return this[URLPromiseSymbol$2]}set URLPromise(e){this[URLPromiseSymbol$2]=e}get metricsPageFields(){return this[metricsPageFieldsSymbol$2]}set metricsPageFields(e){this[metricsPageFieldsSymbol$2]=e}onChildLoadedViewModelChanged(){Promise.all([childViewModelsFromChildControllers(this.childControllers),this.loadedViewModel]).then(([e,t])=>{if(t&&t instanceof VerticalStack){const r=t;r.childViewModels=e}else{this.loadedViewModel=createVerticalStack({childViewModels:e})}})}URL(){return this.URLPromise}get shouldAutomaticalyRefreshAfterResponseExpiration(){return true}get pageMetricsController(){return this[pageMetricsControllerSymbol$4]}set pageMetricsController(e){this[pageMetricsControllerSymbol$4]=e}didReceivePageResourceResponse(e){const t=new ObjectGraph("Editorial Page");const r=e?.data;if(!r||r.length===0){throw new Error("No resource identifiers in editorial page response")}const i=e?.resources;if(!i){throw new Error("No resource map in editorial page response")}const n=new MusicAPIResourceManager;n.addResources(i);const o=findTabRootResource(r,n);return this.collectMarkers(o,n,t).then(e=>{const r=t.adding(ObjectGraphType.EDITORIAL_ELEMENT_COLLECTED_MARKERS,e);return{objectGraphWithMarkers:r,resourceManager:n,tabRootResource:o}})}viewModelForPageResponse({tabRootResource:e,resourceManager:t,objectGraphWithMarkers:r}){this.removeChildControllers();const i=childViewModelControllersForTabRoot(e,t,r);i.forEach(this.addChildController.bind(this));return verticalStackFromChildControllers(this.childControllers)}updatePageMetricsForPageResponse(e,t,r){const i=t;super.updatePageMetricsForPageResponse(e,t,r);this.metricsPageFields.pageUrl=i;this.pageMetricsController.pageFields=this.metricsPageFields}collectMarkers(e,t,r){const i=this.findElementMarkerKinds(e,t,r);if(!i){return Promise.resolve({})}return Promise.resolve()}findElementMarkerKinds(e,t,r){let i=e.relationships?.children?.data;if(!i){return}i=[...i];const n=new Set;while(i.length>0){const e=i.pop();if(!e){continue}const o=t.resourceForResourceIdentifier(e);if(!o){continue}if(o.type!==MusicAPIResourceType.EDITORIAL_ELEMENTS){continue}const s=o.attributes?.editorialElementKind;if(!s){continue}if(isSectionEditorialElement(s)){const e=r.optional(ObjectGraphType.EDITORIAL_ELEMENT_SECTION_FILTER);if(e&&!e?.filterEditorialElementKind(s)){continue}}if(isMarkerEditorialElementKind(s)){n.add(s)}const a=o.relationships?.children?.data;if(a){i.push(...a)}}return n}}const BaseClass$y=mix(ComponentController).with(ContainerComponentControllerMixin,MusicAPIRequestDrivenControllerMixin);class VideosTabController extends BaseClass$y{constructor(...e){super(...e);this.loadPage()}didAppear(){this.pageMetricsController.pageContext=currentPageContext();super.didAppear()}URL(){return getBagValue("countryCode").then(e=>this.makeURL(e))}updatePageMetricsForPageResponse(e,t,r){const i=t;super.updatePageMetricsForPageResponse(e,t,r);this.pageMetricsController.pageFields={pageType:"Videos",pageId:"Videos",pageUrl:i}}loadViewModel(){logger$5.log("[VideosTabController] - loadViewModel");const e=new EditorialController(this.URL(),false);return this.viewModelFromUpdatedChildViewController(e)}onChildLoadedViewModelChanged(e,t){this.viewModel=t}onChildLoadedViewModelErrored(e,t){if(t.viewModel){this.viewModel=t.viewModel}}viewModelFromUpdatedChildViewController(e){if(this.childViewModelController){e.pageMetricsController=null;this.removeChildController(this.childViewModelController)}this.addChildController(e);this.childViewModelController=e;e.pageMetricsController=this.pageMetricsController;return e.loadedViewModel}makeURL(e){const t=new MusicAPIURL(`/v1/editorial/${e}/groupings/`);t.queryString.name="video";t.queryString.extend.add("editorialArtwork");t.queryString.with.add("voice");return t.string()}}Storage.keys=StorageKeys;function onLaunch(e){logger$5.log("Welcome to Music! Version",config$3.version,Application.identifier);logger$5.log("Application onLaunch with application URL",e.applicationScriptURL);logger$5.log("Application onLaunch active method",e.activationMethod);logger$5.log("Application onLaunch non_sub_upsell enabled true");onLaunch.shouldConsiderOnBecomingActivePresentations=e.activationMethod===Application.ACTIVATION_METHOD.REGULAR;initializeBag();initializeLocalization(e.applicationScriptURL);initializeCookies();initializeMetrics();initializeFinance();initializePlayActivity();initializePushNotifications();initializeUserProfile();initializeSocial();initializeIsUsing24HourLocale();Application.onSubscriptionRequired=onSubscriptionRequired;Application.shareRequest=ShareRequestHandler;Application.browseTabController=BrowseTabController;Application.forYouTabController=ListenNowTabController;Application.radioTabController=RadioTabController;Application.searchLandingController=SearchLandingTabController;Application.searchResultController=SearchResultController;Application.videosTabController=VideosTabController;Application.albumDetailController=AlbumDetailController;Application.musicKitAlbumDetailController=MusicKitAlbumDetailController;Application.playlistDetailController=PlaylistDetailController;Application.settingsController=SettingsController;Application.libraryCollectionComponentController=RoutingLibraryComponentController;Application.nowPlayingController=NowPlayingController}onLaunch.shouldConsiderOnBecomingActivePresentations=false;onLaunch.applicationIconIsBadged=false;onLaunch.privacyOnboardingIsPresenting=false;onLaunch.privacyTermsWereAcceptedDuringCurrentLaunch=false;function onOpenURL(e,t,r){logger$5.log("Application onOpenURL was called",e);const i=removeBundleIdentifiersFromOptionsForPrivacyCompliance(t);const n=marketingIdentifiersFromURL(e);if(n?.matchedIdentifier){const e=Object.assign({marketingMessageIdentifier:n},i);performDeeplinkFromFromMarketingCampaignIdentifier(n.matchedIdentifier,e,r)}else{updateLaunchData(Object.assign({url:e},i));performDeeplinkFromURL(e,i,r)}}function onEnteringForeground(e){logger$5.log("Application onEnteringForeground:",e.activationMethod,e.isBadged);onLaunch.shouldConsiderOnBecomingActivePresentations=e.activationMethod===Application.ACTIVATION_METHOD.REGULAR;onLaunch.applicationIconIsBadged=e.isBadged}function onEnteringBackground(){logger$5.log("Application onEnteringBackground");onLaunch.shouldConsiderOnBecomingActivePresentations=false}function onPrivacyOnboardingPresentationStatusDidChange(e,t){logger$5.log(`onPrivacyOnboardingPresentationStatusDidChange was called. Onboarding is presented: ${e}`);onLaunch.privacyOnboardingIsPresenting=e;if(!e&&t&&onLaunch.shouldConsiderOnBecomingActivePresentations){logger$5.log("Attempting finance on becoming active flow from privacy onboarding presentation status change.");checkFinanceOnBecomingActive({},t).catch(e=>{logger$5.error("Finance promise failed from privacy onboarding presentation status change",e)})}}function onPrivacyTermsAccepted(e){logger$5.log("onPrivacyTermsAccepted.");onLaunch.privacyTermsWereAcceptedDuringCurrentLaunch=true;publish(METRICS_SAFE_ON_BECOMING_ACTIVE);if(!isUserSignedIn()){logger$5.log("No account is signed in. Will not present UserNotificationAuthorizationController");e(createNoopSegue());return}userNotificationSettings().then(t=>{logger$5.log(`Notification Settings Response: ${t.authorizationStatus}`);if(t.authorizationStatus===UserNotificationSettings.AUTHORIZATION_STATUS.NOT_DETERMINED){const t=new UserNotificationAuthorizationController;e(createPushSegue({componentController:t}))}else{e(createNoopSegue())}})}function onLibraryOptInSheetSwipeDismissed(){setAllPushNotificationSettings(false)}function onBecomingActive$1(e,t){logger$5.log("Application onBecomingActive. Native application message will present: ",Application.applicationMessageWillPresent);if(onLaunch.privacyOnboardingIsPresenting){logger$5.log("privacyOnboardingIsPresenting. Blocking launch upsells.");t(createNoopSegue());if(onLaunch.privacyTermsWereAcceptedDuringCurrentLaunch){logger$5.log("privacyOnboardingIsPresenting, but privacy terms have been accepted.");publish(METRICS_SAFE_ON_BECOMING_ACTIVE)}return}publish(METRICS_SAFE_ON_BECOMING_ACTIVE);if(onLaunch.applicationIconIsBadged){const e={eventType:"badgedApplicationRetry"};Application.forwardEventForMessageEvaluation(e);t(createNoopSegue());logger$5.log("Retriggering message from badged application.");onLaunch.applicationIconIsBadged=false;return}if(Application.applicationMessageWillPresent){logger$5.log("An IAM message will present on launch, blocking onBecomingActive presentations.");t(createNoopSegue());return}if(!onLaunch.shouldConsiderOnBecomingActivePresentations){t(createNoopSegue());return}checkFinanceOnBecomingActive(e,t).catch(e=>{logger$5.error("Finance promise failed from onBecomingActive",e)});checkCachedAccountShowInLibraryEnabledSync().catch(e=>{logger$5.error("Cached account show in library sync promise failed",e)});onLaunch.shouldConsiderOnBecomingActivePresentations=false}function onResigningActive(){if(onLaunch.privacyOnboardingIsPresenting&&!onLaunch.privacyTermsWereAcceptedDuringCurrentLaunch){logger$5.log("GDPR sheet is still being displayed.");return}publish(METRICS_SAFE_ON_RESIGNING_ACTIVE)}function onPerformModalMessagePresentation(e,t){logger$5.log("onPerformModalMessagePresentation",e);const r=e.message;t(segueForApplicationMessage(r))}function onWillContinueUserActivity(e){logger$5.log("onWillContinueUserActivity",e.activityType);onLaunch.shouldConsiderOnBecomingActivePresentations=false}registerGlobalCallback(Application,"onLaunch",onLaunch);registerOnOpenURLCallback(onOpenURL);registerGlobalCallback(Application,"onBecomingActive",onBecomingActive$1);registerGlobalCallback(Application,"onResigningActive",onResigningActive);registerGlobalCallback(Application,"onEnteringForeground",onEnteringForeground);registerGlobalCallback(Application,"onEnteringBackground",onEnteringBackground);registerGlobalCallback(Application,"onPrivacyOnboardingPresentationStatusDidChange",onPrivacyOnboardingPresentationStatusDidChange);registerGlobalCallback(Application,"onPrivacyTermsAccepted",onPrivacyTermsAccepted);registerGlobalCallback(Application,"onPerformModalMessagePresentation",onPerformModalMessagePresentation);registerGlobalCallback(Application,"onWillContinueUserActivity",onWillContinueUserActivity);subscribe(LIBRARY_OPT_IN_SHEET_SWIPE_DISMISSED,onLibraryOptInSheetSwipeDismissed);