var e=function(e){"use strict";var t,s,i,r,n,o,a,l,u,c,d,h=Object.defineProperty,_=Object.defineProperties,g=Object.getOwnPropertyDescriptors,p=Object.getOwnPropertySymbols,m=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty,E=Object.prototype.propertyIsEnumerable,f=Reflect.get,b=(e,t,s)=>t in e?h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,v=(e,t)=>{for(var s in t||(t={}))S.call(t,s)&&b(e,s,t[s]);if(p)for(var s of p(t))E.call(t,s)&&b(e,s,t[s]);return e},y=(e,t)=>_(e,g(t)),I=(e,t)=>{var s={};for(var i in e)S.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&p)for(var i of p(e))t.indexOf(i)<0&&E.call(e,i)&&(s[i]=e[i]);return s},P=(e,t,s)=>(b(e,"symbol"!=typeof t?t+"":t,s),s),D=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},w=(e,t,s)=>(D(e,t,"read from private field"),s?s.call(e):t.get(e)),O=(e,t,s)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,s)},T=(e,t,s,i)=>(D(e,t,"write to private field"),i?i.call(e,s):t.set(e,s),s),N=(e,t,s)=>new Promise(((i,r)=>{var n=e=>{try{a(s.next(e))}catch(t){r(t)}},o=e=>{try{a(s.throw(e))}catch(t){r(t)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(n,o);a((s=s.apply(e,t)).next())})),C=(e=>(e.VERBOSE="verbose",e.DEBUG="debug",e.INFO="info",e.WARN="warn",e.ERROR="error",e.CRITICAL="critical",e.NONE="none",e))(C||{}),k="production",A="@pushly/push-sdk-web",R="3.0.44",L="cdn.p-n.io",M="k.p-n.io",U="PushlySDK";let x=class{static get _env(){return k}static get _libraryName(){return A}static get _libraryVersion(){return R}static get _cdnDomain(){return L}static get _kApiDomain(){return M}static get _publicNamespace(){return U}static get _kApiEventsUrl(){return`https://${this._kApiDomain}/event-stream`}static get _kApiAllowUrl(){return`https://${this._kApiDomain}/allow`}static get _cdnDomainSettingsUrl(){return`https://${this._cdnDomain}/domain-settings`}static get _isDev(){return"development"===this._env}static get _isProd(){return"production"===this._env}static get _sdkHasEventsOnlyDomainsFlag(){return"FEAT_SDK_EVENT_ONLY_DOMAINS"}static get _sdkHasForceDebugLogsEnabledFlag(){return"FEAT_WEB_FORCE_DEBUG_LOGS"}static get _sdkDebugEventsEnabledFlag(){return"SDK_DEBUG_EVENTS"}static get _pnCookieStorageKey(){return"_pn"}static get _pnCookieStorageKeyRegex(){return new RegExp(`^${this._pnCookieStorageKey}(_[0-9A-Za-z]{8})?=`)}static get _pnCookieStorageLegacyKeyPrefix(){return"_pn"}static get _pnCookieStorageLegacyKeyPrefixRegex(){return new RegExp(`^((${this._pnCookieStorageLegacyKeyPrefix}.+)|(pushly.+))`)}static get _pnStorageTypeLuaKey(){return"lua"}static get _pnStorageUpdatedAtKey(){return"ts"}static get _pnSessionStorageKey(){return"_ps"}static get _pnCookieStorageMaxDays(){return 180}static get _pnDomainConfigCacheTtlSeconds(){return 60}static get _eventQueueMaxSize(){return 100}static get _eventQueueFlushIntervalMS(){return 1e3}static get _eventMaxSendAttempts(){return 8}static get _eventQueueFlushTriggerSize(){return 10}static get _eventPriorityHeader(){return"X-Event-Priority"}static get _eventPriorityHeaderImmFlag(){return"1"}static get _tevChannel(){return"WEB"}static get _tevVapidProvider(){return"VAPID"}static get _tevFieldErrorCode(){return"error_code"}static get _tevFieldErrorDescription(){return"error_description"}static get _tevFieldErrorMessage(){return"error_message"}static get _tevFieldErrorStack(){return"error_stack"}static get _tevFieldErrorContext(){return"context"}};function $(e){try{const t=parseInt(String(e));return isNaN(t)?e:t}catch(t){return e}}const K={V8:{signature:/^\s*at\s+\S+\s+\(?\S+\)?$/,split:/:(?!\/)|\s+/},SpiderMonkeyOrJSCore:{signature:/^[^@]*@\S*$/,split:/:(?!\/)|@+/}};function W(e,t){if(!e)return[];let s=e.replace(/(.*?\()(?:eval\s)?(at(?!.+at).*?)\),\s?(.*)/gm,"$1$3\n$2").split(/[\n\r]\s*/).map((e=>[e,Object.keys(K).find((t=>K[t].signature.test(e)))])).filter((([,e])=>e)).map((([e,t])=>e.split(K[t].split).filter((e=>"at"!==e)).map((e=>e.replace(/^\(|\)$/g,""))))).map((([e,t,s,i])=>({function:e||"unknown",file:t||"unknown",line:void 0===s?0:$(s),column:void 0===i?0:$(i)})));return null==t||t.forEach((e=>{s=e(s)})),s}function F(e){return{message:e}}function V(e){return{message:e,isExitException:!0}}var B=(e=>(e.EXCEPTION="exception",e.DUPLICATE_SDK_DETECTED="duplicate_sdk_detected",e.SDK_ALREADY_LOADED="sdk_already_loaded",e.DOMAIN_CONFIGURATION_LOAD_FAILED="domain_config_load_failed",e.HOST_NOT_ALLOWED="host_not_allowed",e.PROMPTS_LOAD_FAILED="prompts_load_failed",e.WEB_PUSH_NOT_SUPPORTED="web_push_not_supported",e.WEB_PUSH_CONFIGURATION_MISSING="web_push_config_missing",e.WEB_PUSH_SUBSCRIPTION_FAILED="web_push_subscription_failed",e.PUSH_WORKER_NOT_FOUND_EXCEPTION="push_worker_not_found_exception",e.PUSH_WORKER_REGISTRATION_EXCEPTION="push_worker_registration_exception",e.PUSH_WORKER_SUBSCRIPTION_EXCEPTION="push_worker_subscription_exception",e.STORAGE_NOT_AVAILABLE="storage_not_available",e.STORAGE_FAILED_TO_OPEN="storage_failed_to_open",e.STORAGE_NS_REQUIRED="storage_ns_required",e.STORAGE_KEY_EMPTY="storage_key_empty",e.IDB_INVALID_STORE_NAME="idb_invalid_store_name",e.IDB_BLOCKED="idb_blocked",e.REQUEST_FAILED="request_failed",e.REQUEST_URL_INVALID="request_url_invalid",e.REQUEST_NO_RESULT="request_no_result",e.REQUEST_DESERIALIZATION_FAILED="request_deserialization_failed",e.UNKNOWN_CONTEXT_KEY="unknown_context_key",e.UNKNOWN_CONFIG_KEYS="unknown_config_keys",e.UNKNOWN_ASYNC_COMMAND="unknown_async_command",e.UNKNOWN_PROMPT_MESSAGE="unknown_prompt_message",e.WORKER_MISSING_PUSH_DATA="worker_missing_push_data",e.UNKNOWN_WORKER_PUSH="unknown_worker_push",e.UNKNOWN_WORKER_PUSHLY_INTERACTION="unknown_worker_pushly_interaction",e.UNKNOWN_WORKER_3P_INTERACTION="unknown_worker_3p_interaction",e))(B||{});const G={exception:F("Unknown exception"),duplicate_sdk_detected:V("Another instance of the SDK is already running"),sdk_already_loaded:V("The SDK has already been loaded"),domain_config_load_failed:V("Failed to load Domain configuration from remote"),host_not_allowed:V("Current host is not allowed for use"),prompts_load_failed:F("Failed to load Prompts from remote"),web_push_not_supported:V("Web push not supported"),web_push_subscription_failed:F("Error encountered during subscription"),web_push_config_missing:V("Web push configuration missing"),push_worker_not_found_exception:F("Service Worker file not found"),push_worker_registration_exception:F("Service Worker registration exception encountered"),push_worker_subscription_exception:F("Web push subscription exception encountered"),storage_not_available:F("Storage not available"),storage_failed_to_open:F("Storage failed to open"),storage_ns_required:F("Store name is required"),storage_key_empty:F("No data for storage key"),idb_invalid_store_name:F("IndexedDB requires a valid store name; `null` provided"),idb_blocked:F("IndexedDB is blocked"),request_failed:F("Request exception encountered"),request_url_invalid:F("Invalid URL"),request_no_result:F("No result"),request_deserialization_failed:F("Failed to decode response"),unknown_context_key:F("Unknown context key"),unknown_config_keys:F("Unknown configuration key"),unknown_async_command:F("Unknown pushly() command"),unknown_prompt_message:F("Unknown prompt message"),worker_missing_push_data:F("Push event data missing"),unknown_worker_push:F("Unknown worker push event"),unknown_worker_pushly_interaction:F("Unknown worker pushly interaction"),unknown_worker_3p_interaction:F("Unknown worker 3rd-party interaction")};function H(e,t){let s=new Error(null!=t?t:"Unknown error");if(e instanceof Error)s=e;else if(null!=e)try{s=new Error(String(e))}catch(i){}return s}const j=class e extends Error{constructor(t,s,i,r=!1){null!=t||(t=B.EXCEPTION);const n=[G[t].message];i&&n.push(i),super(n.join(" - ")),P(this,"originalError"),P(this,"code"),this.details=i,this.isSuppressed=r,this.originalError=null!=s?s:void 0,this.code=t,Object.setPrototypeOf(this,e.prototype),this.name="PNException"}static _from(t,s,i,r=!1){return t instanceof e?t:s?s(t):new e(i,null===t?null:H(t),void 0,r)}static _filterBuilderStackEntry(t){return t.filter((t=>t.function!==`${e.name}.${e._from.name}`))}static _isSuppressed(t){const s=t instanceof e?t._name:t.name,i=t instanceof e?t._compositeMessage:t.message,r=t instanceof e&&t.isSuppressed,n=e.KNOWN_NAMES.includes(s),o=e.KNOWN_NAMES.some((e=>new RegExp(e).test(i)));return!e.FORCE_ALLOW_MESSAGE_PATTERNS.some((e=>e.test(i)))&&(r||n||o)}get _compositeMessage(){var t,s,i;let r=this.message;return this.originalError instanceof e?r=`${r.replace(/\.$/,"")}. ${this.originalError._compositeMessage}`:(null==(t=this.originalError)?void 0:t.message)&&(null==(s=this.originalError)?void 0:s.message)!==r&&(r=`${r.replace(/\.$/,"")}. ${null==(i=this.originalError)?void 0:i.message}`),r}get _isExitException(){return!!G[this.code].isExitException}get _name(){var e,t;return null!=(t=null==(e=this.originalError)?void 0:e.name)?t:this.name}get _stack(){var t;const s=W(null==(t=this.originalError)?void 0:t.stack,[e._filterBuilderStackEntry]),i=W(this.stack,[e._filterBuilderStackEntry]);return s.length?s:i}toString(){return this._compositeMessage}};P(j,"KNOWN_NAMES",["AbortError","SecurityError","NetworkError"]),P(j,"FORCE_ALLOW_MESSAGE_PATTERNS",[/no active service worker/i]);let q=j;function Y(e){return Object.keys(e).filter((t=>(isNaN(Number(t))||/^0\d+/.test(t))&&("string"==typeof e[t]||"number"==typeof e[t])))}function Q(e,t){const s=function(e){return Y(e).map((t=>e[t]))}(e).includes(t)?t:void 0;if(void 0===s)throw new Error(`Invalid enum member ${"string"==typeof t?`"${t}"`:t}. ${JSON.stringify(function(e){return Object.fromEntries(Y(e).map((t=>[t,e[t]])))}(e))}`);return s}function z(e,t){try{return Q(e,t)}catch(s){}}const X={[C.VERBOSE]:{intValue:0,label:"Verbose",logMethod:"debug"},[C.DEBUG]:{intValue:1,label:"Debug",logMethod:"debug"},[C.INFO]:{intValue:2,label:"Info",logMethod:"info"},[C.WARN]:{intValue:3,label:"Warn",logMethod:"warn"},[C.ERROR]:{intValue:4,label:"Error",logMethod:"error"},[C.CRITICAL]:{intValue:5,label:"Critical",logMethod:"error"},[C.NONE]:{intValue:6,label:"None",logMethod:"info"}},Z="pn_ll",J=[],ee={},te={};class se{constructor(e){P(this,"_logLevel"),this.name=e,this._logLevel=C.NONE,this._restorePrevLogLevel()}static _getInstance(e){return e||(e=x._publicNamespace),ee[e]||(ee[e]=new se(e)),ee[e]}get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e,this.persistLogLevel(e)}_restorePrevLogLevel(){if("localStorage"in self)try{const e=self.localStorage.getItem(Z);e&&z(C,e)?(this._log("Logger",C.VERBOSE,["Restoring previous log level",this.logLevel]),this.logLevel=e):(this._log("Logger",C.VERBOSE,["Previous log level not found - setting default",this.logLevel]),this.persistLogLevel(this.logLevel))}catch(e){this._log("Logger",C.VERBOSE,["Unable to restore previous log level",e])}else this._log("Logger",C.VERBOSE,["Skipping log level restore in worker global scope"])}persistLogLevel(e){if("localStorage"in self)try{self.localStorage.setItem(Z,e)}catch(t){}}_log(e,t,s){const i=X[t],r=X[this.logLevel];e&&(s=s.slice()).unshift(`[${e}]`);let n=i.label[0];if(t===C.CRITICAL&&(n="!"+n),J.push([new Date,n,...s]),this.logLevel!=C.NONE&&t!=C.NONE&&i.intValue>=r.intValue)try{"console"in self&&"object"==typeof console&&i.logMethod in console&&"function"==typeof console[i.logMethod]&&console[i.logMethod](`[${this.name}: ${n}]`,...s)}catch(o){J.push([new Date,`!${X[C.CRITICAL].label[0]}`,o])}}}class ie{constructor(e,t){P(this,"_globalLogger"),P(this,"_tag"),this._globalLogger=se._getInstance(t),this._tag=null!=e?e:null}static _getInstance(e,t){const s=null!=e?e:"root";return ee[s]||(te[s]=new ie(e,t)),te[s]}get logLevel(){return this._globalLogger.logLevel}set logLevel(e){this._globalLogger.logLevel=e}_getLogs(e=!1){return e?J.map((([e,t,...s])=>[`${e.toISOString()} [${this._globalLogger.name}: ${t}]`,...s].map((e=>{if(e&&!Array.isArray(e)&&"object"==typeof e)try{return e instanceof q?e._compositeMessage:e instanceof Error?e.message:JSON.stringify(e)}catch(t){}return e})).join(" "))):J.map((([,...e])=>e))}verbose(...e){this._log(C.VERBOSE,...e)}debug(...e){this._log(C.DEBUG,...e)}info(...e){this._log(C.INFO,...e)}warn(...e){this._log(C.WARN,...e)}error(...e){this._log(C.ERROR,...e)}critical(...e){this._log(C.CRITICAL,...e)}_log(e,...t){this._globalLogger._log(this._tag,e,t)}}var re=(e=>(e.LOAD="load",e.SHOW_PROMPT="show_prompt",e.PROFILE="profile",e.PROFILE_APPEND="profile_append",e.PROFILE_REMOVE="profile_remove",e.PAGE_TAG_VISIT="page_tag_visit",e.EXTERNAL_ID="external_id",e.DEREGISTER_EXTERNAL_ID="deregister_external_id",e.REQUEST_USER_DELETION="request_user_deletion",e.VIEW_ITEM="view_item",e.SAVE_ITEM="save_item",e.ADD_TO_CART="add_to_cart",e.PURCHASE="purchase",e.UPDATE_CART="update_cart",e.DEBUG="debug",e.CONFIRM_CONSENT="confirm_consent",e.PAUSE_PUSH_NOTIFICATIONS="pause_notifications",e.RESUME_PUSH_NOTIFICATIONS="resume_notifications",e.GET_PUSH_NOTIFICATIONS_PAUSED_STATE="get_notifications_paused_state",e))(re||{}),ne=(e=>(e.WEB_PUSH_SUPPORTED="web_push_supported",e.WEB_PUSH_UNSUPPORTED="web_push_unsupported",e.LOADED="loaded",e.READY="ready",e.PROMPT_ELIGIBLE="prompt_eligible",e.PROMPT_INELIGIBLE="prompt_ineligible",e.PROMPT_SHOWN="prompt_shown",e.PROMPT_DISMISSED="prompt_dismissed",e.PROMPT_ALLOWED="prompt_allowed",e.PERMISSION_SHOWN="permission_shown",e.PERMISSION_ALLOWED="permission_allowed",e.PERMISSION_DENIED="permission_denied",e.PERMISSION_DISMISSED="permission_dismissed",e.LEGACY_PERMISSION_SHOWN="permission_prompted",e.LEGACY_PERMISSION_ALLOWED="permission_accepted",e))(ne||{});const oe=["subscribe"];var ae=(e=>(e.ERROR="error",e.SDK_IMPRESSION="sdk_impression",e.DEBUG="debug",e.PROFILE="profile",e.PROFILE_APPEND="profile_append",e.PROFILE_REMOVE="profile_remove",e.EXTERNAL_ID="external_id",e.DEREGISTER_EXTERNAL_ID="deregister_external_id",e.USER_DELETION_REQUEST="udr",e.VIEW_PAGE="view_page",e.VIEW_SCREEN="view_screen",e.ANONYMOUS_VIEW_PAGE="anonymous_view_page",e.PAGE_TAG_VISIT="page_tag_visit",e.ADD_TO_CART="add_to_cart",e.UPDATE_CART="update_cart",e.PURCHASE="purchase",e.VIEW_ITEM="view_item",e.SAVE_ITEM="save_item",e.PROMPT_SHOWN="prompt_shown",e.PROMPT_ACCEPTED="prompt_allow",e.PROMPT_DISMISSED="prompt_dismiss",e.PROMPT_NOT_SHOWN="prompt_not_shown",e.PERMISSION_SHOWN="permission_prompted",e.PERMISSION_ACCEPTED="permission_accepted",e.PERMISSION_DISMISSED="permission_dismissed",e.PERMISSION_DENIED="permission_denied",e.PERMISSION_CHANGED="permission_changed",e.IAM_IMPRESSION="iam_impression",e.IAM_CLICK="iam_click",e.IAM_SUBSCRIBE="iam_subscribe",e.IAM_CLOSE="iam_close",e.IAM_NOT_SHOWN="iam_not_shown",e.TOKEN_RECEIVED="subscribed",e.TOKEN_REFRESHED="subscription_change",e.UNSUBSCRIBED="unsubscribed",e.MANUAL_UNSUBSCRIBED="manual_unsubscribed",e.SOFT_UNSUBSCRIBE="soft_unsubscribe",e.SOFT_RESUBSCRIBE="soft_resubscribe",e.NOTIFICATION_IMPRESSION="notification_impression",e.NOTIFICATION_CLICK="notification_click",e.NOTIFICATION_CLOSE="notification_close",e.LIVE_ACTIVITY_REGISTER="la_register",e.LIVE_ACTIVITY_END="la_end",e.SESSION_START="session_start",e.SESSION_HEARTBEAT="session_heartbeat",e))(ae||{});const le=e=>["debug","sdk_impression","prompt_not_shown"].includes(e),ue=e=>{let t=null==e?"":e;if("string"!=typeof e)try{t=JSON.stringify(e)}catch(r){t=""}let s=5381,i=Uint8Array.from(Array.from(t).map((e=>e.charCodeAt(0))));for(let n of i)s=(s<<5)+s+n&4294967295;return s};function ce(e=32){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",s="";for(let i=0;iObject.assign(Object.create(null),e);function he(e){return e.replace(/([A-Z]+)/g,(e=>`_${e.toLowerCase()}`)).replace(/^_|_$/,"")}function _e(e){if(!e||Array.isArray(e)||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(_e);const t={};return Object.keys(e).sort().forEach((s=>{t[s]=_e(e[s])})),t}const ge=class{static _build(e,t,s){return N(this,null,(function*(){var i,r;const n=de({sendAttemptCount:0,event_id:ce(5),channel:x._tevChannel,provider:x._tevVapidProvider,action:e,domain_id:this._domainId,domain_key:this._domainKey,pushly_unique_user_id:this._anonymousId,token:this._token,meta:de({sdk:{name:x._libraryName,version:x._libraryVersion,library:x._libraryName,library_version:x._libraryVersion},event:{version:3}}),data:null!=t?t:{}});return s&&(n.jxms=s),(null==(i=this._loadConfig)?void 0:i.externalId)&&!n.data[ae.EXTERNAL_ID]&&(n.data[ae.EXTERNAL_ID]=null==(r=this._loadConfig)?void 0:r.externalId),n}))}static _getErrorEvent(e,t){return N(this,null,(function*(){return this._build(ae.ERROR,v({[x._tevFieldErrorCode]:e instanceof q?(s=e.code,s.replace(/^.|_+[a-z]/gi,(e=>e.replace(/_+/,"").toUpperCase()))):e.name,[x._tevFieldErrorDescription]:e instanceof q?e._name:e.name,[x._tevFieldErrorMessage]:e instanceof q?e._compositeMessage:e.message,[x._tevFieldErrorStack]:e instanceof q?e._stack:W(e.stack,[q._filterBuilderStackEntry]),page_url:location.href},null!=t?t:{}));var s}))}static _getProfileExternalIdEvent(e){return N(this,null,(function*(){return this._build(ae.PROFILE,{external_id:e})}))}static _getProfileLanguageEvent(e){return N(this,null,(function*(){return this._build(ae.PROFILE,{language:e})}))}static _getProfileTimeZoneEvent(e){return N(this,null,(function*(){return this._build(ae.PROFILE,{time_zone:e})}))}static _isEqual(e,t){return((e,t)=>ue(e)===ue(t))(this._getEventHashParts(e),this._getEventHashParts(t))}static _prepareSendEvent(e){e.sendAttemptCount+=1,this._ensureLateInitValues(e)}static _ensureLateInitValues(e){!e.pushly_unique_user_id&&this._anonymousId&&(e.pushly_unique_user_id=this._anonymousId),!e.domain_id&&this._domainId&&(e.domain_id=this._domainId),e.domain_id||e.domain_key||!this._domainKey||(e.domain_key=this._domainKey),e.domain_id&&e.domain_key&&delete e.domain_key,!e.token&&this._token&&(e.token=this._token)}static _clone(e){let t;if("structuredClone"in self)try{t=structuredClone(e)}catch(s){}if(!t){const s=e,{sendAttemptCount:i,event_id:r,data:n}=s,o=I(s,["sendAttemptCount","event_id","data"]);t=de(v({},o))}return t.sendAttemptCount=0,t.event_id=ce(5),t.data=de(e.data),t}static _getEventHashParts(e){var t,s;return de({a:e.action,di:null!=(t=e.domain_id)?t:"unknown",dk:null!=(s=e.domain_key)?s:"unknown",puuid:e.pushly_unique_user_id,t:e.token?Object.fromEntries(Object.keys(e.token).sort().entries()):"none",d:_e(e.data)})}};P(ge,"_domainKey"),P(ge,"_domainId"),P(ge,"_anonymousId"),P(ge,"_loadConfig"),P(ge,"_token"),ge._domainKey=null,ge._domainId=null,ge._anonymousId=null,ge._loadConfig=null,ge._token=null;let pe=ge;class me{constructor(e,i){O(this,t,void 0),O(this,s,void 0),T(this,t,e),T(this,s,null!=i?i:ie._getInstance("UserProfile"))}getAnonymousId(){return N(this,null,(function*(){return w(this,t).userStore._getAnonymousId()}))}getToken(){return N(this,null,(function*(){if(!w(this,t).notificationPermissionService)return null;return(yield w(this,t).notificationPermissionService._getCurrentPermissions()).token}))}setExternalId(e){return N(this,null,(function*(){if(!w(this,t).isLoaded)return void w(this,t)._registerOnLoadedCallback((()=>this.setExternalId(e)));const s=yield w(this,t).userStore._getExternalId();if(!s||e!==s){yield w(this,t).userStore._setExternalId(e);const s=yield pe._getProfileExternalIdEvent(e);w(this,t).eventManager._track(s)}}))}getExternalId(){return N(this,null,(function*(){return w(this,t).userStore._getExternalId()}))}unsetExternalId(){return N(this,null,(function*(){(()=>{N(this,null,(function*(){if(null!==this.getExternalId()){yield w(this,t).userStore._removeExternalId();const e=yield pe._build(ae.DEREGISTER_EXTERNAL_ID);w(this,t).eventManager._track(e)}}))})()}))}getSubscriberStatus(){return N(this,null,(function*(){return w(this,t).userStore._getSubscriberStatus()}))}getIsDeleted(){return N(this,null,(function*(){return w(this,t).userStore._getIsInDeletedState()}))}requestUserDeletion(){w(this,t)._executeWhenConfigured((()=>w(this,t)._handleUserDeletionRequest()))}set(e,i){const r="string"==typeof e?{[e]:i}:e;w(this,t)._executeWhenConfiguredIfEnabled((()=>{w(this,s).verbose(`Setting to profile: ${r}`),w(this,t).eventManager._track(ae.PROFILE,r)}))}append(e,i){w(this,t)._executeWhenConfiguredIfEnabled((()=>{w(this,s).verbose(`Appending to profile ${e}: ${i}`),w(this,t).eventManager._track(ae.PROFILE_APPEND,{[e]:i})}))}remove(e,i){w(this,t)._executeWhenConfiguredIfEnabled((()=>{w(this,s).verbose(`Removing from profile ${e}: ${i}`),w(this,t).eventManager._track(ae.PROFILE_REMOVE,{[e]:i})}))}trackActivity(e,s){w(this,t)._executeWhenConfiguredIfEnabled((()=>{const i={page_url:e};(null==s?void 0:s.length)&&(i.tags=s),w(this,t).eventManager._track(ae.VIEW_PAGE,i)}))}}t=new WeakMap,s=new WeakMap;var Se=(e=>(e.SUBSCRIBED="subscribed",e.DISMISSED="dismissed",e.DENIED="denied",e.NOT_DETERMINED="not_determined",e))(Se||{});const Ee={not_determined:0,dismissed:1,subscribed:2,denied:-1},fe=e=>{switch("string"==typeof e&&(e=e.toLowerCase()),e){case"subscribed":case Ee.subscribed:return"subscribed";case"dismissed":case Ee.dismissed:return"dismissed";case"blocked":case"denied":case Ee.denied:return"denied";default:return"not_determined"}},be=e=>"not_determined"===e?"not determined":e;class ve{constructor(e,t){O(this,i,void 0),O(this,r,void 0),T(this,i,e),T(this,r,null!=t?t:ie._getInstance("Notifications"))}showPermissionPrompt(e,t){let s,r={};"number"==typeof e?(s=e,r=null!=t?t:{}):r=null!=e?e:{},w(this,i)._executeWhenConfiguredIfEnabled((()=>{var e;null==(e=w(this,i).promptsController)||e._showPrompt(s,r)}))}getIsEligibleToPrompt(){return N(this,null,(function*(){const e=yield w(this,i).userStore._getIsInDeletedState(),t=yield w(this,i).userStore._getIsSubscribed(),s=yield w(this,i).userStore._getIsUserInSoftUnsubscribedState(),r=yield w(this,i).userStore._getSubscriberStatus();return w(this,i).isLoaded&&w(this,i).isEnabled&&!e&&!t&&r!=Se.DENIED&&r!=Se.DISMISSED&&!s}))}pause(){return N(this,null,(function*(){this._executeIfSubscribed((()=>N(this,null,(function*(){(yield w(this,i).userStore._getIsUserInSoftUnsubscribedState())?w(this,r).info("The user is already in soft unsubscribe status."):(w(this,i).userStore._setIsUserInSoftUnsubscribedState(),w(this,i).eventManager._track(ae.SOFT_UNSUBSCRIBE),w(this,r).info("The user's notifications have been paused."))}))))}))}resume(){return N(this,null,(function*(){this._executeIfSubscribed((()=>N(this,null,(function*(){(yield w(this,i).userStore._getIsUserInSoftUnsubscribedState())?(w(this,i).userStore._unsetIsUserInSoftUnsubscribedState(),w(this,i).eventManager._track(ae.SOFT_RESUBSCRIBE),w(this,r).info("The user's notifications have been resumed.")):w(this,r).info("The user is not in a soft unsubscribe status.")}))))}))}getIsPaused(){return N(this,null,(function*(){return w(this,i).userStore._getIsUserInSoftUnsubscribedState()}))}getIsSubscribed(){return N(this,null,(function*(){return w(this,i).userStore._getIsSubscribed()}))}_executeIfSubscribed(e){return N(this,null,(function*(){yield w(this,i)._executeWhenConfigured((()=>N(this,null,(function*(){if(yield this.getIsSubscribed())try{yield e()}catch(t){const e=H(t);w(this,r).error(e),w(this,i).eventManager._track(e)}else w(this,r).warn("User is not currently subscribed and can not use this method")}))))}))}}i=new WeakMap,r=new WeakMap;class ye extends x{static get _dynamicDomainKey(){var e,t,s;return null!=(s=null!=(t=ye._injectedDomainKey)?t:null==(e=ye._injectedDomainConfig)?void 0:e.domain_key)?s:ye._requestingScriptDomainKey}static get _requestingScriptDomainKey(){var e,t,s,i;try{const r=new URLSearchParams(null!=(s=null==(t=null==(e=document.currentScript)?void 0:e.getAttribute("src"))?void 0:t.split("?")[1])?s:"");return null!=(i=r.get("domain_key"))?i:r.get("domainKey")}catch(r){}return null}static get _udrUrlSearchParameter(){return"pushly_udr"}static get _swUseRootScopeFlag(){return"USE_ROOT_SW_SCOPE"}static get _swUsePathWithoutDomainKeyFlag(){return"SW_NO_DOMAIN_KEY_PARAM"}static get _swShouldReplaceExistingWorkerInPushlyScopeFlag(){return"REPLACE_EXISTING_WORKERS"}static get _swShouldUnregisterNonPushlyWorkersFlag(){return"UNREGISTER_ALL_NON_PUSHLY_WORKERS"}static get _domainFeatInformedContentFlag(){return"FEAT_INFORMED_CONTENT"}static get _domainFeatIntegrationsECommFlag(){return"FEAT_DOMAIN_INTEGRATIONS_ECOMM"}static get _domainFeatUseIsolatedCookiesFlag(){return"USE_ISOLATED_COOKIE_STORAGE_LOCATION"}static get _disableSessionTracking(){return"FEAT_SDK_WEB_DISABLE_SESSION_TRACKING"}static get _pnPromptsCacheTtlSeconds(){return 60}static get _defaultDismissedStatusExpirationSeconds(){return 604800}static get _injectedDomainKey(){try{return self._PN_IDK_&&"string"==typeof self._PN_IDK_?self._PN_IDK_:null}catch(e){return null}}static get _injectedDomainConfig(){try{return self._PN_IDC_&&"object"==typeof self._PN_IDC_&&!Array.isArray(self._PN_IDC_)&&"domain_key"in self._PN_IDC_?self._PN_IDC_:null}catch(e){return null}}static get _injectedPromptGroups(){try{return self._PN_IPG_&&Array.isArray(self._PN_IPG_)&&self._PN_IPG_.length&&self._PN_IPG_.every((e=>"prompts"in e))?self._PN_IPG_:null}catch(e){return null}}static get _tevSubscribedUrlKey(){return"subscribed_url"}static get _tevDataPageUrlKey(){return"page_url"}static get _tevDataPageTagsKey(){return"page_tags"}static get _tevDataPromptNotShownKey(){return"prompt_not_shown_reason"}}var Ie=(e=>(e.PRODUCT="product",e.EVENT="event",e))(Ie||{});function Pe(e,t){let s,i,r;try{s="item_type"in e?z(Ie,e.item_type):"event_id"in e?Ie.EVENT:"product_id"in e?Ie.PRODUCT:t,i="id"in e?e.id:"event_id"in e?String(e.event_id):"product_id"in e?String(e.product_id):"",r="quantity"in e?e.quantity:void 0}catch(o){throw new TypeError(`ECommItem could not be parsed: ${H(o).message}. ${JSON.stringify(e)}`)}if(!s)throw new TypeError(`ECommItem.item_type could not be parsed. ${JSON.stringify(e)}`);if("string"!=typeof i||!i)throw new TypeError(`ECommItem.id could not be parsed. ${JSON.stringify(e)}`);if(null!=r&&Number.isNaN(Number(r)))throw new TypeError(`ECommItem.quantity is not numeric. ${JSON.stringify(e)}`);const n={item_type:s,id:i,quantity:r};return null!=r?{item_type:n.item_type,id:n.id,quantity:n.quantity}:{item_type:n.item_type,id:n.id}}class De{constructor(e,t){O(this,n,void 0),O(this,o,void 0),T(this,n,e),T(this,o,null!=t?t:ie._getInstance("ECommModule"))}trackSavedItem(e){return N(this,null,(function*(){this._trackItemsWithoutQuantity([e],"trackSavedItem",ae.SAVE_ITEM,"saved items")}))}trackSavedItems(e){return N(this,null,(function*(){this._trackItemsWithoutQuantity(e,"trackSavedItems",ae.SAVE_ITEM,"saved items")}))}trackViewedItem(e){return N(this,null,(function*(){this._trackItemsWithoutQuantity([e],"trackViewedItem",ae.VIEW_ITEM,"viewed items")}))}trackViewedItems(e){return N(this,null,(function*(){this._trackItemsWithoutQuantity(e,"trackViewedItems",ae.VIEW_ITEM,"viewed items")}))}addToCart(e){return N(this,null,(function*(){w(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig("addToCart",(t=>{const s={[t.item_type]:e.map((e=>Pe(e,t.item_type)))};w(this,o).verbose(`Adding ${e.length} item${e.length>1?"s":""} to cart`),w(this,n).eventManager._track(ae.ADD_TO_CART,s)}))}))}))}updateCart(e){return N(this,null,(function*(){w(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig("updateCart",(t=>{const s={[t.item_type]:e.map((e=>Pe(e,t.item_type)))};w(this,o).verbose(`Updating cart with ${e.length} item${e.length>1?"s":""}.`),w(this,n).eventManager._track(ae.UPDATE_CART,s)}))}))}))}clearCart(){return N(this,null,(function*(){w(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig("clearCart",(e=>{const t={[e.item_type]:[]};w(this,o).verbose("Clearing cart"),w(this,n).eventManager._track(ae.UPDATE_CART,t)}))}))}))}trackPurchase(e,t,s){return N(this,null,(function*(){w(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig(`trackPurchase(${e?"items":""}${t?":purchaseId":""}${s?":priceValue":""})`,(i=>{if(void 0===e)return w(this,o).verbose("Tracking purchase"),void w(this,n).eventManager._track(ae.PURCHASE);const r={[i.item_type]:e.map((e=>Pe(e,i.item_type)))};t&&(r.purchase_id=t),s&&(r.price_value=s),w(this,o).verbose(`Tracking purchase of ${e.length} item${e.length>1?"s":""}${t?" Purchase ID: "+t:""}${s?" Total value: "+s:""}.`),w(this,n).eventManager._track(ae.PURCHASE,r)}))}))}))}_withECommConfig(e,t){return N(this,null,(function*(){w(this,n)._executeWhenConfigured((()=>N(this,null,(function*(){const s=yield w(this,n).domainConfigProvider._get();if(s.isErr())return w(this,o).warn(s.getErr()),void w(this,o).warn(`${e} Unable to load Domain Config`);const i=s.unwrap(),r=i.ecomm_config;r?"unknown"!==function(e){switch(e){case"product":return"products";case"event":return"events";default:return"unknown"}}(r.item_type)?i.flags.includes(ye._domainFeatIntegrationsECommFlag)?t(r):w(this,o).warn("E-Commerce support is not currently enabled for this domain"):w(this,o).warn(`E-Commerce configuration has unrecognized item type: ${r.item_type}`):w(this,o).warn("E-Commerce configuration is not defined for this domain")}))))}))}_trackItemsWithoutQuantity(e,t,s,i){const r=e.map((({id:e,item_type:t})=>({id:e,item_type:t})));w(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig(t,(t=>{const a={[t.item_type]:r.map((e=>Pe(e,t.item_type)))};w(this,o).verbose(`Adding ${e.length} item${e.length>1?"s":""} to ${i}`),w(this,n).eventManager._track(s,a)}))}))}}n=new WeakMap,o=new WeakMap;class we{constructor(e,t){O(this,a,void 0),O(this,l,void 0),T(this,a,e),T(this,l,null!=t?t:ie._getInstance("Prompts"))}dispatch(e){return N(this,null,(function*(){var t;e.prompt_action?yield null==(t=w(this,a).promptsController)?void 0:t._processDispatchMessage(e):w(this,l).debug("Received unknown Prompt message:",e)}))}}a=new WeakMap,l=new WeakMap;const Oe=["domainKey","sw","swScope","externalId","classNames","consentRequired","requireConsent","frameMessenger"];class Te{constructor(e,t=null){P(this,"ok"),P(this,"err",null),P(this,"toString",(()=>{if(this.isErr()){const e=this.getErr();return`Result.Err: ${e instanceof Error?e.message:e}`}return`Result.Ok: ${this.unwrapOrNull()}`})),null!==t?this.err=t:void 0!==e&&(this.ok=e)}static Ok(e){return new Te(e)}static Err(e){return new Te(void 0,e)}unwrap(){if(this.isOk())return this.ok;if(this.isErr())throw this.err;throw new Error("Unknown error")}unwrapOr(e){var t;return null!=(t=this.ok)?t:e}unwrapOrNull(){var e;return null!=(e=this.ok)?e:null}isOk(){return null===this.err&&void 0!==this.ok}isErr(){return null!==this.err}getErr(){return this.err}}function Ne(){const e=window.PushlySDK;return(t=e)&&"object"==typeof t&&"iid"in t&&"string"==typeof t.iid?e:null;var t}function Ce(e){return N(this,null,(function*(){return new Promise((t=>setTimeout(t,e)))}))}const ke=e=>new q(B.REQUEST_URL_INVALID,null,e),Ae=()=>new q(B.REQUEST_NO_RESULT),Re=(e,t)=>new q(B.REQUEST_DESERIALIZATION_FAILED,t,e),Le=e=>new q(B.REQUEST_FAILED,e);class Me{constructor(e,t,s=null,i={},r){var n,o;P(this,"_id"),P(this,"_method"),P(this,"_requestUrl"),P(this,"_data"),P(this,"_headers"),P(this,"_parameters"),P(this,"_logger"),P(this,"jitterMillis"),this._logger=null!=r?r:ie._getInstance("Request"),this._id=ce(5),this._method=e,this._requestUrl=t,this._data=s,this._headers={},this._parameters=null!=(n=i.parameters)?n:{},this.jitterMillis=null!=(o=i.jitterMillis)?o:null,i.isPriorityRequest&&this._setIsPriority(!0)}_getParameter(e){var t;return null!=(t=this._parameters[e])?t:null}_setParameter(e,t){this._parameters[e]=t}_removeParameter(e){delete this._parameters[e]}_getHeader(e){var t;return null!=(t=this._headers[e])?t:null}_setHeader(e,t){this._headers[e]=t}_removeHeader(e){delete this._headers[e]}_setIsPriority(e){e?this._headers[x._eventPriorityHeader]=x._eventPriorityHeaderImmFlag:delete this._headers[x._eventPriorityHeader]}_getJitterMillis(){var e;return null!=(e=this.jitterMillis)?e:null}_setJitterMillis(e){this.jitterMillis=e}get _url(){try{let e=new URL(this._requestUrl);return Object.keys(this._parameters).length&&Object.entries(this._parameters).forEach((([t,s])=>{e.searchParams.append(t,s)})),Te.Ok(e)}catch(e){return Te.Err(ke(this._requestUrl))}}get _requestOptions(){const e=this._url;return e.isErr()?e:Te.Ok([e.unwrap(),{method:this._method,headers:this._headers,body:this._data?JSON.stringify(this._data):void 0,keepalive:!0}])}_perform(){return N(this,null,(function*(){return new Promise((e=>{let t,s=0;const i=()=>`(${this._id}-${s})`,r=()=>{t=new Date,s+=1,this._logger.verbose(`${i()} Opening ${this._requestUrl}`)},n=()=>{const e=((new Date).getTime()-t.getTime())/1e3;this._logger.verbose(`${i()} Closed (${e.toFixed(4)}) ${this._requestUrl}`)},o=()=>!(s>=x._eventMaxSendAttempts)&&(n(),setTimeout((()=>a()),.2*s),!0),a=()=>N(this,null,(function*(){r();try{const[s,r]=this._requestOptions.unwrap();this.jitterMillis&&(yield Ce(this.jitterMillis));const a=yield fetch(s,r);if(!a.ok&&o())return;if(204===a.status)return n(),void e(Te.Ok({response:a}));const l=yield a.text();if(!l)return n(),void e(Te.Err(Ae()));try{n(),e(Te.Ok({data:JSON.parse(l),response:a}))}catch(t){this._logger.warn(`${i()} Unable to decode response: ${l}`),e(Te.Err(Re(l,H(t))))}}catch(s){if(!o()){n();const t=H(s);e(Te.Err(Le(t)))}}}));a()}))}))}}var Ue=(e=>(e.GET="GET",e.POST="POST",e))(Ue||{});const xe=e=>{const t="number"==typeof e?new Date(e):e,s=new Date;return t.getTime()-s.getTime()};class $e{constructor(e,t,s){P(this,"logger"),P(this,"cached",null),this.domainKey=e,this.settingsStore=t,this.logger=null!=s?s:ie._getInstance("DomainConfigProvider")}_get(){return N(this,null,(function*(){const e=yield this._getFromCache();return e?(this.logger.verbose("Hydrated from cache"),Te.Ok(e)):this._getFromRemote()}))}get _injectedDomainConfig(){return ye._injectedDomainConfig}_getFromCache(){return N(this,null,(function*(){const e=yield this.settingsStore._getDomainConfig();if(e){const t=1e3*ye._pnDomainConfigCacheTtlSeconds-Math.abs(xe(e.ts));if(t>0)return this.logger.verbose(`${(t/1e3).toFixed(2)}s until next fetch from remote`),this.cached=e,e.value}return null}))}_getCachedSync(){if(this._injectedDomainConfig)return this._injectedDomainConfig;if(this.cached){if(1e3*ye._pnPromptsCacheTtlSeconds-Math.abs(xe(this.cached.ts))>0)return this.cached.value;this.cached=null}return null}_getFromRemote(){return N(this,null,(function*(){let e=this._injectedDomainConfig;if(e)this.logger.debug("Using injected domain settings");else{const t=`${ye._cdnDomainSettingsUrl}/${this.domainKey}/web/config`,s=new Me(Ue.GET,t),i=yield s._perform();if(i.isErr())return i;const r=i.unwrap().data;if(!r)return Te.Err(new q(B.DOMAIN_CONFIGURATION_LOAD_FAILED));e=de(r),this.logger.verbose("Hydrated from remote")}return yield this.settingsStore._setDomainConfig(e).catch((e=>this.logger.error(e))),this.settingsStore._getDomainConfig().then((e=>this.cached=e)),Te.Ok(e)}))}}var Ke=(e=>(e.VAPID="VAPID",e.APNS="APNS",e))(Ke||{});let We=(P(u=class{static get _scope(){return this._isInSourcelessIFrame?top:this._isInWorkerGlobalScope?self:window}static get _location(){return this._scope.location}static get _navigator(){return this._scope.navigator}static get _document(){return this._scope.document}static get _isInWorkerGlobalScope(){return self&&"WorkerGlobalScope"in self}static get _isInSourcelessIFrame(){return!this._isInWorkerGlobalScope&&window&&"object"==typeof window&&!!top&&top!==window.self&&!!window.frameElement&&"about:blank"===window.frameElement.src}static get _devicePlacement(){let e;if(this._navigator.userAgentData)e=this._navigator.userAgentData.mobile?"mobile":"desktop";else try{e=this._scope.matchMedia("only screen and (max-device-width: 768px)").matches?"mobile":"desktop"}catch(t){e=[/Android/i,/webOS/i,/iPhone|iPad|iPod/i,/Blackberry/i,/Windows Phone/i].some((e=>e.test(this._navigator.userAgent)))?"mobile":"desktop"}return e}static get _isSafari(){const e=this._navigator,t="safari"in u._scope&&!e.userAgent.match(/crios/i)&&!e.userAgent.match(/fxios/i)&&!e.userAgent.match(/Opera|OPT\//),s="vendor"in e?!!e.vendor.match(/apple/i):"userAgentData"in e&&/macos/i.test(navigator.userAgentData.platform);return t&&s}static get _requires2Step(){var e,t;if(void 0!==this._requires2StepCache)return this._requires2StepCache;if(this._isSafari)return this._requires2StepCache=!0,this._requires2StepCache;const s=this._navigator,i=s.userAgentData;if(i&&Array.isArray(i.brands)&&i.brands.length>0){for(const t of i.brands){const s=(null!=(e=null==t?void 0:t.brand)?e:"").toLowerCase();if(s.includes("firefox")||s.includes("edge"))return this._requires2StepCache=!0,this._requires2StepCache}return this._requires2StepCache=!1,this._requires2StepCache}const r=null!=(t=s.userAgent.toLowerCase())?t:"";return r&&-1!==r.indexOf("firefox")||r&&-1!==r.indexOf(" edg/")||r&&-1!==r.indexOf(" microsoft edge")?(this._requires2StepCache=!0,this._requires2StepCache):(this._requires2StepCache=!1,this._requires2StepCache)}static get _isPushManagerInScope(){return"PushManager"in this._scope}static get _pushProvider(){return this._isInWorkerGlobalScope||!this._isSafari||this._isPushManagerInScope?Ke.VAPID:Ke.APNS}static get _isLocal(){return"localhost"===this._location.hostname||"127.0.0.1"===this._location.hostname}static get _isHttps(){return"https:"===this._location.protocol}static get _isArrayFullySupported(){return"Array"in this._scope&&"from"in Array&&"some"in[]}static _getIsUserAgentSupported(){try{if(!("userAgent"in this._navigator))return[!1,"self.userAgent not accessible"];const e=/bot|spider|crawl|xwarler|disqus|hatena|okhttp|headless|flipboard|linkcheck|coccoc|kddi|ichiro|libwww|wget|apache-http|miniflux|digg|bingpreview|sleuth|pcore|pingdom|snacktory|ning|opengraph|woorank|validator|python|steamchat|whatsapp|slurp|feedbin|appengine|php-curl|meta(insp|-ext)|internet-measure|gb\.gy|findlinks|heritrix|ec2link|facebook(ext|cat)|analyzer|ichigo|europarchive|curl|tiny\stiny|feedfetch|mediapartner|google(other|-(inspect|ext)|\sfav)/im;if(e.test(this._navigator.userAgent))return[!1,"self.navigator.userAgent is recognizedBot"];if("appVersion"in this._navigator&&e.test(this._navigator.appVersion))return[!1,"self.navigator.appVersion is recognizedBot"];if("appCodeName"in this._navigator&&e.test(this._navigator.appCodeName))return[!1,"self.navigator.appCodeName is recognizedBot"];if("product"in this._navigator&&e.test(this._navigator.product))return[!1,"self.navigator.product is recognizedBot"];if("vendor"in this._navigator&&e.test(this._navigator.vendor))return[!1,"self.navigator.vendor is recognizedBot"];return/fb(ios|an)|instagram|twitter|pinterest|micromessenger/i.test(this._navigator.userAgent)?[!1,"self.navigator.userAgent is not supported"]:[!0]}catch(e){return[!1,H(e).message]}}static _getIsEnvBaseSupported(){try{if(!this._isLocal&&!this._isHttps)return[!1,"self.location.protocol is not secure context (http:)"];if(!("location"in this._scope))return[!1,"self.location not accessible"];if(!("navigator"in this._scope))return[!1,"self.navigator not accessible"];if(!("Notification"in this._scope))return[!1,"self.Notification not accessible"];if(!this._isArrayFullySupported)return[!1,"required Array functionality not accessible"];if(!this._location.host)return[!1,"self.location.host is undefined"];if(!this._location.hostname)return[!1,"self.location.hostname is undefined"];try{if(!this._location.hostname.split("").length)return[!1,"self.location.hostname is empty"]}catch(e){return[!1,"self.location.hostname is not a valid String"]}const[t,s]=this._getIsUserAgentSupported();if(!t)return[!1,s];if(!this._isPushManagerInScope){const e=/iphone|ipad/i;return e.test(this._navigator.userAgent)?[!1,"self.navigator.userAgent is iDevice"]:"platform"in this._navigator&&e.test(this._navigator.platform)?[!1,"self.navigator.platform is iDevice"]:[!1,"self.PushManager is not accessible"]}if(!("PushSubscription"in this._scope))return[!1,"self.PushSubscription is not accessible"];const i=this._scope.PushSubscription;if(!(null==i?void 0:i.prototype.hasOwnProperty("getKey")))return[!1,"self.PushSubscription.prototype.getKey is not accessible"];if(!("ServiceWorker"in this._scope))return[!1,"self.ServiceWorker is not accessible"];if(!("serviceWorker"in this._navigator))return[!1,"self.navigator.serviceWorker is not accessible"];if(!("ServiceWorkerRegistration"in this._scope))return[!1,"self.ServiceWorkerRegistration is not accessible"];const r=this._scope.ServiceWorkerRegistration;if(!(null==r?void 0:r.prototype.hasOwnProperty("showNotification")))return[!1,"self.ServiceWorkerRegistration.prototype.showNotification is not accessible"]}catch(t){return[!1,H(t).message]}return[!0]}},"_requires2StepCache"),u);function Fe(e){var t,s;const i=null!=(t=e.whitelist_domains)?t:[],r=null!=(s=e.sdk_event_only_domains)?s:[],n=e.flags.includes(x._sdkHasEventsOnlyDomainsFlag),o=i.some(Ve),a=r.some(Ve);return n&&o&&a}function Ve(e){const t=We._location,s=`${t.protocol}//${t.hostname}`,i=`${t.protocol}//${t.host}`,r=t.href;/^\*/.test(e)&&(e=`.${e}`);const n=new RegExp(`^(http[s]?://)?${e}$`,"i");return n.test(s)||n.test(i)||n.test(r)}class Be extends We{static get _isDevMode(){return"development"===x._env}static _getIsWebPushSupported(){return N(this,null,(function*(){try{const[t,s]=this._getIsEnvBaseSupported();if(!t)return[!1,s];if(this._pushProvider===Ke.APNS)return[!1,"APNS subscriptions are not supported"];if(!this._navigator.cookieEnabled)return[!1,"self.navigator.cookieEnabled is FALSE"];try{yield this._navigator.serviceWorker.getRegistration()}catch(e){return[!1,"call to self.navigator.serviceWorker.getRegistration() failed"]}}catch(e){return[!1,H(e).message]}return[!0]}))}static get _isSafariPushCapable(){return this._isSafari&&"object"==typeof this._scope.safari&&"object"==typeof this._scope.safari.pushNotification}static isAnimationApiSupported(){try{return!!this._document.getAnimations()&&!!this._scope.navigator.userAgentData}catch(e){return!1}}}class Ge{constructor(e,t,s){this.delegate=e,this.domain=t,this.logger=s}static get _defaultPermissions(){return{permission:"default",token:null}}}class He extends Ge{constructor(e,t,s,i){super(t,s,null!=i?i:ie._getInstance("WebPushRegistrationService")),this.workerService=e}get _permissionsApi(){return Be._navigator.permissions}get _notificationApi(){return Be._scope.Notification}_getToken(){return N(this,null,(function*(){return(yield this._getCurrentPermissions()).token}))}_getCurrentPermissions(){return N(this,null,(function*(){let e=Ge._defaultPermissions;try{const t=yield this._permissionsApi.query({name:"notifications"});e.permission="prompt"===t.state?"default":t.state}catch(t){this._notificationApi&&(e.permission=this._notificationApi.permission)}if("granted"===e.permission)try{const t=yield this.workerService._getSubscription();t&&(e.token=t.toJSON())}catch(s){this.logger.warn("Unable to read current subscription.",H(s).message)}return e}))}_requestNotificationPermission(){return N(this,null,(function*(){const e=yield this._getCurrentPermissions();if("denied"===e.permission||"granted"===e.permission&&e.token)return this.logger.debug(`Permissions already ${e.permission}`),e;"granted"===e.permission&&this.logger.info("Subscription not found. Attempting to resubscribe.");try{return this._requestWebPushPermissions()}catch(t){return this.logger.debug("RNP",t),this._getCurrentPermissions()}}))}_requestWebPushPermissions(){return N(this,null,(function*(){var e,t;const s=yield this._getCurrentPermissions();switch("default"===s.permission&&(null==(t=null==(e=this.delegate)?void 0:e._onPushPermissionRequested)||t.call(e),this.logger.info("Requesting permission")),s.permission=yield this._notificationApi.requestPermission(),s.permission){case"granted":yield this._handlePermissionGranted();break;case"denied":yield this._handlePermissionDenied();break;case"default":yield this._handlePermissionDismissed()}return s}))}_handlePermissionGranted(){return N(this,null,(function*(){var e,t,s,i,r,n;this.logger.verbose("Handling permission granted status"),null==(t=null==(e=this.delegate)?void 0:e._onPushPermissionGranted)||t.call(e);const o=yield this.workerService._subscribe();if(o.isOk()&&o.unwrap()){const e=o.unwrap();e?null==(i=null==(s=this.delegate)?void 0:s._onPushSubscriptionSucceeded)||i.call(s,e.toJSON()):this.logger.warn("Subscription request returned null.")}else{const e=o.getErr();this.logger.error("Unable to perform subscription",e),null==(n=null==(r=this.delegate)?void 0:r._onPushSubscriptionFailed)||n.call(r,e)}}))}_handlePermissionDenied(){return N(this,null,(function*(){var e,t;null==(t=null==(e=this.delegate)?void 0:e._onPushPermissionDenied)||t.call(e)}))}_handlePermissionDismissed(){return N(this,null,(function*(){var e,t;null==(t=null==(e=this.delegate)?void 0:e._onPushPermissionDismissed)||t.call(e)}))}}var je=(e=>(e.GRANTED="granted",e.DENIED="denied",e.DISMISSED="dismissed",e.DEFAULT="default",e))(je||{});function qe(e){switch(e){case"granted":return"granted";case"denied":return"denied";default:return"default"}}var Ye=(e=>(e.WEB_PUSH_UNSUPPORTED="web_push_unsupported",e.HOST_NOT_WHITELISTED="host_not_whitelisted",e.SW_INSTALL_FAILED="sw_install_failed",e.PROMPTS_LOAD_FAILED="load_failed",e.NO_ELIGIBLE_PROMPTS="no_eligible_prompts",e.USER_PERMISSION_DENIED="user_permission_denied",e.USER_PERMISSION_DISMISSED="user_permission_dismissed",e.USER_PERMISSION_GRANTED="user_permission_granted",e.PROMPT_INELIGIBLE_FCAP="prompt_ineligible_fcap",e.USER_DELETED="user_deleted",e))(Ye||{});class Qe{constructor(e,t,s,i,r,n){P(this,"registrationService"),P(this,"additionalEventData",{}),P(this,"additionalEventContext",{}),P(this,"logger"),this.domain=e,this.workerService=t,this.eventManager=s,this.userStore=i,this.lifecycleCallbacks=r,this.logger=null!=n?n:ie._getInstance("NotificationPermissionService"),this.registrationService=new He(this.workerService,this,this.domain)}static _getWebPushSupport(){return N(this,null,(function*(){const[e,t]=yield Be._getIsWebPushSupported();return e?Te.Ok(!0):Te.Err(new q(B.WEB_PUSH_NOT_SUPPORTED,null,t))}))}get _provider(){return Be._pushProvider}get _currentHref(){return Be._location.href}_init(){return N(this,null,(function*(){return this.domain.vapid_public_key?Te.Ok(!0):Te.Err(new q(B.WEB_PUSH_CONFIGURATION_MISSING))}))}_getCurrentPermissions(){return N(this,null,(function*(){const e=yield this.registrationService._getCurrentPermissions();return v({provider:this._provider},e)}))}_synchronize(){return N(this,null,(function*(){var e,t;if(Fe(this.domain))return this.logger.debug("[Event Only Mode] Skipping notification permission check"),null;if((yield Qe._getWebPushSupport()).isErr())return this.logger.warn("Permission synchronization failed - WebPush is not supported"),null;this._provider===Ke.VAPID&&(yield this.workerService._ready(200)),this.logger.debug("Checking current notification permissions");const s=yield this._getCurrentPermissions(),i=yield this.userStore._getSubscriberStatus();if(s.token&&(pe._token=s.token),"default"===s.permission&&i===Se.NOT_DETERMINED||"granted"===s.permission&&i===Se.SUBSCRIBED&&s.token||"denied"===s.permission&&i===Se.DENIED)this.logger.info("Current notification permissions:",be(i));else if("denied"===s.permission&&i===Se.DISMISSED||"denied"===s.permission&&i===Se.NOT_DETERMINED)this.logger.debug("Updating subscriber status to",be(Se.DENIED)),yield this.userStore._setSubscriberStatus(Se.DENIED);else if("granted"===s.permission&&i===Se.DENIED||"granted"===s.permission&&i===Se.DISMISSED||"granted"===s.permission&&i===Se.NOT_DETERMINED||"granted"===s.permission&&!s.token){i!==Se.SUBSCRIBED||s.token?this.logger.verbose(`Granted permissions mismatch found - current: ${s.permission}, cached: ${be(i)}`):this.logger.verbose("Token not found for granted permissions");const e=yield this._attemptSilentSubscription();i!==Se.SUBSCRIBED&&e&&(this.logger.debug("Updating subscriber status to",be(Se.SUBSCRIBED)),yield this.userStore._setSubscriberStatus(Se.SUBSCRIBED))}else"default"===s.permission&&i===Se.DISMISSED?this.logger.info(`User has recently ${be(Se.DISMISSED)} permissions`):"default"===s.permission&&i===Se.DENIED?(this.logger.debug("Updating subscriber status to",be(Se.NOT_DETERMINED)),yield this.userStore._setSubscriberStatus(Se.NOT_DETERMINED)):"denied"===s.permission&&i===Se.SUBSCRIBED?(yield this.userStore._setSubscriberStatus(Se.DENIED),yield this._revokePermission()):"default"===s.permission&&i===Se.SUBSCRIBED?(this.logger.debug("Updating subscriber status to",be(Se.NOT_DETERMINED)),yield this.userStore._setSubscriberStatus(Se.NOT_DETERMINED),yield this._revokePermission()):this.logger.warn("Unhandled permission and subscription status combination:",{provider:s.provider,permission:s.permission,token:s.token,subscriptionStatus:i});const r=yield this._getCurrentPermissions();return"granted"!==r.permission?pe._token=null:r.token?(pe._token=r.token,this.logger.info("Current token:",r.token)):this.logger.warn("Unable to resolve current token"),r.permission===s.permission&&r.token===s.token||null==(t=null==(e=this.lifecycleCallbacks)?void 0:e.onPushSDKDidReceivePermissionStatusChange)||t.call(e,qe(r.permission)),r}))}_requestPermission(e){return N(this,null,(function*(){var e,t,s;const i=yield this._getCurrentPermissions();if("denied"===i.permission)return this.logger.info("Permission already denied"),i;if("granted"===i.permission)return this.logger.info("Permission already granted"),i;const r=yield null==(e=this.registrationService)?void 0:e._requestNotificationPermission(),n=y(v({},r),{provider:this._provider});return n.permission===i.permission&&n.token===i.token||null==(s=null==(t=this.lifecycleCallbacks)?void 0:t.onPushSDKDidReceivePermissionStatusChange)||s.call(t,qe(n.permission)),n}))}_revokePermission(){return N(this,null,(function*(){(yield this.workerService._unsubscribe())&&this.eventManager._track(ae.MANUAL_UNSUBSCRIBED)}))}_attemptSilentSubscription(){return N(this,null,(function*(){this.logger.verbose("Attempting silent subscription");const e=yield this.workerService._subscribe();if(e.isErr())return this.logger.warn(e.getErr()),this.eventManager._track(e.getErr()),!1;let t=null;if(e.isOk()){const s=e.unwrap();t=s?s.toJSON():null}return t?(this.logger.debug("Silent subscription succeeded:",t),pe._token=t,this.eventManager._track(yield this._getBaseSubscriptionEvent()),!0):(this.logger.debug("Silent subscription failed"),!1)}))}_getIsEligibleToPrompt(){return N(this,null,(function*(){const e=yield this.userStore._getIsInDeletedState(),t=yield this.userStore._getIsSubscribed(),s=yield this.userStore._getIsUserInSoftUnsubscribedState(),i=yield this.userStore._getSubscriberStatus();return e?Te.Err(Ye.USER_DELETED):t?Te.Err(Ye.USER_PERMISSION_GRANTED):s||i===Se.DENIED?Te.Err(Ye.USER_PERMISSION_DENIED):i===Se.DISMISSED?Te.Err(Ye.USER_PERMISSION_DISMISSED):Te.Ok(!0)}))}_setPermissionEventContext(e){this.additionalEventContext=e}_resetPermissionEventContext(){this.additionalEventContext={}}_setAdditionalPermissionEventData(e){this.additionalEventData=e}_onPushPermissionRequested(){return N(this,null,(function*(){var e,t;this.eventManager._track(ae.PERMISSION_SHOWN,v({},this.additionalEventData)),null==(t=null==(e=this.lifecycleCallbacks)?void 0:e.onPushSDKDidRequestNotificationPermissions)||t.call(e)}))}_onPushPermissionDenied(){return N(this,null,(function*(){var e,t;yield this.userStore._setSubscriberStatus(Se.DENIED),null==(t=null==(e=this.lifecycleCallbacks)?void 0:e.onPushSDKDidReceivePermissionResponse)||t.call(e,je.DENIED),this.eventManager._track(ae.PERMISSION_DENIED,v({},this.additionalEventData)),this._resetPermissionEventContext()}))}_onPushPermissionDismissed(){return N(this,null,(function*(){var e,t,s;const i=null!=(e=this.additionalEventContext.dismissalExpirationSeconds)?e:ye._defaultDismissedStatusExpirationSeconds;0===i?(this.logger.debug("Setting subscriber status to NOT_DETERMINED"),yield this.userStore._setSubscriberStatus(Se.NOT_DETERMINED)):(this.logger.debug(`Setting subscriber status to DISMISSED for ${i}s`),yield this.userStore._setSubscriberStatusDismissed(i)),null==(s=null==(t=this.lifecycleCallbacks)?void 0:t.onPushSDKDidReceivePermissionResponse)||s.call(t,je.DISMISSED),this.eventManager._track(ae.PERMISSION_DISMISSED,v({},this.additionalEventData)),this._resetPermissionEventContext()}))}_onPushPermissionGranted(){return N(this,null,(function*(){var e,t;yield this.userStore._setSubscriberStatus(Se.SUBSCRIBED),null==(t=null==(e=this.lifecycleCallbacks)?void 0:e.onPushSDKDidReceivePermissionResponse)||t.call(e,je.GRANTED),this.eventManager._track(ae.PERMISSION_ACCEPTED,v({},this.additionalEventData))}))}_onPushSubscriptionSucceeded(e){return N(this,null,(function*(){var t,s;pe._token=e,null==(s=null==(t=this.lifecycleCallbacks)?void 0:t.onPushSDKDidRegisterForRemoteNotificationsWithDeviceToken)||s.call(t,e);const i=yield this._getBaseSubscriptionEvent();i.data=v(v({},this.additionalEventData),i.data),this.eventManager._track(i),this._resetPermissionEventContext()}))}_getBaseSubscriptionEvent(){return N(this,null,(function*(){return pe._build(ae.TOKEN_RECEIVED,{[ye._tevDataPageUrlKey]:this._currentHref,[ye._tevSubscribedUrlKey]:this._currentHref})}))}_onPushSubscriptionFailed(e){return N(this,null,(function*(){var t,s;pe._token=null,this.logger.info(`event:${ae.ERROR}`,e),null==(s=null==(t=this.lifecycleCallbacks)?void 0:t.onPushSDKDidFailToRegisterForRemoteNotificationsWithError)||s.call(t,new q(B.WEB_PUSH_SUBSCRIPTION_FAILED,e)),e&&this.eventManager._track(e),this._resetPermissionEventContext()}))}}const ze=e=>{let t="";try{if(t=window.atob(e),"string"==typeof t)return t}catch(a){}t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";if(e=String(e).replace(/[\t\n\f\r ]+/g,""),!/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/.test(e))throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");e+="==".slice(2-(3&e.length));let i,r,n,o=0;for(;o>16&255):64===n?String.fromCharCode(i>>16&255,i>>8&255):String.fromCharCode(i>>16&255,i>>8&255,255&i);return t},Xe=e=>{const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=ze(t),i=new Uint8Array(s.length);for(let r=0;r{let t;try{"TextEncoder"in self&&"function"==typeof self.TextEncoder&&"encode"in self.TextEncoder.prototype?(s=(new self.TextEncoder).encode(e),t=window.btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(s)))).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")):(t=window.btoa(e),"string"!=typeof t&&(t=void 0))}catch(i){console.warn("Unable to encode base64 string",i)}var s;return null!=t?t:e};function Je(e,t){return Promise.race(["function"==typeof t?t():Promise.resolve(t),new Promise((t=>{setTimeout((()=>t()),e)}))])}var et=(e=>(e[e.ERROR=1]="ERROR",e))(et||{});const tt=class{static _setEventManager(e){this.eventManager=e}static _dispatch(e,t){try{if(!this.eventManager)return void this.logger.verbose("Received",t);if(1===e)this.logger.verbose("Received",t)}catch(s){this.logger.warn(H(s))}}};P(tt,"eventManager"),P(tt,"logger"),tt.logger=ie._getInstance("Dispatch"),P(tt,"EventType",et);let st=tt;const it=(e=100)=>Math.floor(Math.random()*e),rt=(e,t=!1)=>{const s=e?H(e):void 0;return q._from(s,null,B.PUSH_WORKER_REGISTRATION_EXCEPTION,t)},nt=e=>{const t=e?H(e):void 0;return q._from(t,null,B.PUSH_WORKER_NOT_FOUND_EXCEPTION)},ot=(e,t=!1)=>{const s=e?H(e):void 0;return q._from(s,null,B.PUSH_WORKER_SUBSCRIPTION_EXCEPTION,t)};class at{constructor(e,t,s){P(this,"logger"),this.pushSdkConfig=e,this.domain=t,this.logger=null!=s?s:ie._getInstance("PushWorkerService")}get _worker(){return Be._navigator.serviceWorker}get _location(){return Be._location}_ready(e){return N(this,null,(function*(){return Je(null!=e?e:50,this._worker.ready)}))}_getRegistration(){return N(this,null,(function*(){var e;try{const t=yield this._worker.getRegistrations();if(!t||!t.length)return null;let s=null;const[i,r]=this._getRegistrationOptions();for(let n of t){yield this._ready(50);const t=(null==(e=n.active)?void 0:e.scriptURL)||"",o=e=>e.replace(/\/+$/,""),a=o(n.scope)===(r.scope?o(r.scope):void 0),l=t.includes(i.split("?")[0]),u=this.domain.flags.includes(ye._swShouldUnregisterNonPushlyWorkersFlag);if(a&&l){if(s=n,!u)break}else if(a||!u){if(a&&!l&&!this.domain.flags.includes(ye._swShouldReplaceExistingWorkerInPushlyScopeFlag)){this.logger.warn(`Implementation Error. An existing, non-push, service worker was found at scope: ${r.scope}.`);break}}else yield n.unregister(),this.logger.info(`Removed worker ${t} at scope ${n.scope}`)}return s}catch(t){const e=H(t);st._dispatch(st.EventType.ERROR,e),this.logger.error(e)}return null}))}_register(){return N(this,null,(function*(){let e=yield this._getRegistration();if(e)return e;const[t,s]=this._getRegistrationOptions();this.logger.info(`Installing new registration: ${t}`);try{e=yield this._worker.register(t,s)}catch(i){throw yield this._sanitizeRegistrationError(H(i),t)}return yield Je(500,(()=>N(this,null,(function*(){const t=new Date,s=()=>new Promise((i=>{if(null==e?void 0:e.active)return this.logger.verbose("New registration is ready",((new Date).getTime()-t.getTime())/1e3+"s"),i();setTimeout(s,10)}));return s()})))),e}))}_getSubscription(){return N(this,null,(function*(){const e=yield this._getRegistration();if(!e)return null;try{return e.pushManager.getSubscription()}catch(t){const e=H(t);st._dispatch(st.EventType.ERROR,e),this.logger.error(e)}return null}))}_subscribe(){return N(this,null,(function*(){const e=yield this._getSubscription();if(e)return this.logger.debug("Existing subscription found"),Te.Ok(e);let t=yield this._getRegistration();if(!t)try{t=yield this._register()}catch(i){return Te.Err(rt(i))}this.logger.info("Subscribing");let s=Te.Ok(null);for(let r=0;r++<10;){try{yield this._ready();const e=yield t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Xe(this.domain.vapid_public_key)});if(e){s=Te.Ok(e);break}}catch(i){const e=this._sanitizeSubscriptionError(H(i));if(10===r){s=Te.Err(e);break}this.logger.warn(e)}this.logger.debug("Retrying subscription"),yield Ce(it(500))}return s}))}_unsubscribe(){return N(this,null,(function*(){try{const e=yield this._getSubscription();return e&&(yield e.unsubscribe()),!0}catch(e){const t=H(e);st._dispatch(st.EventType.ERROR,t),this.logger.error(t.message)}return!1}))}_getRegistrationOptions(){const e=this._location,t=`${e.protocol}//${e.hostname}${e.port?`:${e.port}`:""}`,s=this.pushSdkConfig.sw,i=this.pushSdkConfig.swScope,r=e=>e.replace(/^https?:\/\/[^/]+/i,"").replace(/^\//,"");let n=s?r(s):null;n&&!n.includes(t)&&(n=`/${n}`);let o=i?r(i):null;o&&!o.includes(t)&&(o=`/${o}`);let a=n||"/pushly-sdk-worker.js";const l=a.substr(0,a.lastIndexOf("/")+1)||"/",u=this.domain.flags.includes(ye._swUseRootScopeFlag);let c=l;o?c=o:u&&(c="/");let d=c.includes(t)?c:`${t.replace(/\/$/,"")}${c}`;d=`${d.replace(/\/$/,"")}/`;return!this.domain.flags.includes(ye._swUsePathWithoutDomainKeyFlag)&&(a=`${a}${a.includes("?")?"&":"?"}domain_key=${this.pushSdkConfig.domainKey}`),[a,{updateViaCache:"none",scope:d}]}_tryFetchResourceStatus(e){return N(this,null,(function*(){try{return(yield fetch(e)).status}catch(t){return 0}}))}_sanitizeRegistrationError(e,t){return N(this,null,(function*(){if(q.KNOWN_NAMES.includes(e.name)||[/SSL certificate/i,/Failed to access storage/i,/Operation has been aborted/i,/unknown error occurred when fetching the script/i,/403/].some((t=>t.test(e.message))))return rt(e,!0);if(/404/.test(e.message)||404===(yield this._tryFetchResourceStatus(t)))throw nt(e);return rt(e)}))}_sanitizeSubscriptionError(e){const t=q.KNOWN_NAMES.includes(e.name)||[/push service error/i,/could not retrieve the public key/i].some((t=>t.test(e.message)));return ot(e,t)}}class lt{constructor(e,t,s,i){P(this,"_name"),P(this,"_task"),P(this,"_intervalMilliseconds"),P(this,"_options"),P(this,"_timer"),P(this,"_isStarted"),P(this,"_isPaused"),P(this,"_startTime"),P(this,"_stopTime"),P(this,"_pausedStartTime"),P(this,"_totalPausedTime"),P(this,"_expectedTime"),P(this,"_timerDidIncrementListeners"),this._name=e,this._task=t,this._intervalMilliseconds=1e3*(null!=s?s:1),this._options=null!=i?i:{},this._isStarted=!1,this._isPaused=!1,this._startTime=0,this._stopTime=0,this._pausedStartTime=0,this._totalPausedTime=0,this._expectedTime=0,this._timerDidIncrementListeners=new Set,!1!==(null==i?void 0:i.autoStart)&&this._start()}get repeats(){var e;return!1!==(null==(e=this._options)?void 0:e.repeats)}get runtimeMilliseconds(){if(!this._startTime)return 0;const e=this._stopTime||Date.now();let t=e-this._startTime-this._totalPausedTime;return this._isPaused&&(t-=e-this._pausedStartTime),t}get runtimeSeconds(){return Math.floor(this.runtimeMilliseconds/1e3)}get isStarted(){return this._isStarted}get isPaused(){return this._isPaused}_addTimerDidIncrementListener(e){this._timerDidIncrementListeners.add(e)}_removeTimerDidIncrementListener(e){this._timerDidIncrementListeners.delete(e)}_start(){this.isStarted||(this._isStarted=!0,this._startTime=Date.now(),this._stopTime=0,this._expectedTime=this._startTime,this._options.runImmediatelyOnStart&&this._executeTask(),this._run())}_stop(){this.isStarted&&(clearTimeout(this._timer),this._stopTime=Date.now(),this._isStarted=!1,this._timer=void 0)}_pause(){this.isStarted&&!this.isPaused&&(clearTimeout(this._timer),this._pausedStartTime=Date.now(),this._isPaused=!0,this._timer=void 0)}_unpause(){if(!this.isStarted||!this.isPaused)return;this._isPaused=!1;const e=Date.now()-this._pausedStartTime;this._totalPausedTime+=e,this._expectedTime+=e,this._run()}_run(){if(!this.isStarted||this.isPaused)return;const e=Date.now()-this._expectedTime;this._expectedTime+=this._intervalMilliseconds;const t=Math.max(0,this._intervalMilliseconds-e);this._timer=setTimeout((()=>{this._executeTask(),this._timerDidIncrementListeners.forEach((e=>{e.onIncrement(this.runtimeSeconds)})),this.repeats?this._run():this._stop()}),t)}_executeTask(){"function"==typeof this._task?this._task(this):this._task._run(this)}}const ut=class e{constructor(e,t,s,i,r,n){P(this,"previousSubscriberState",null),this.domainConfig=e,this.eventManager=t,this.userStore=s,this.sessionStore=i,this.pageChangeListener=r,this.logger=n,this.evaluateInitialSubscriberStatus()}static _init(t,s,i,r,n,o){return null!=o||(o=ie._getInstance("PageViewProcessor")),new lt("pvp_timer",new e(t,s,i,r,n,o),this.PAGE_VIEW_INTERVAL_SECONDS,{autoStart:!1,runImmediatelyOnStart:!0})}evaluateInitialSubscriberStatus(){return N(this,null,(function*(){const e=yield this.userStore._getSubscriberStatus();null!=this.previousSubscriberState||(this.previousSubscriberState=e)}))}_run(){return N(this,null,(function*(){var e;try{const t=this._currentLocation.href,s=yield this.userStore._getLastPageViewed(),i=yield this.userStore._getSubscriberStatus(),r=i!==this.previousSubscriberState&&i===Se.SUBSCRIBED;this.previousSubscriberState=i,s&&s===t&&!r||(r||(yield this.userStore._setLastPageViewed(t),this.logger.verbose("Incrementing page views"),yield this.sessionStore._incrementSessionPageViewCount()),null==(e=this.pageChangeListener)||e.onPageChanged(),i===Se.SUBSCRIBED?(this.logger.verbose("Preparing page view event"),yield this._track(ae.VIEW_PAGE,t)):this.domainConfig.flags.includes(ye._domainFeatInformedContentFlag)?(this.logger.verbose("Preparing anonymous page view event"),yield this._track(ae.ANONYMOUS_VIEW_PAGE,t)):this.logger.debug("Page View tracking is not enabled"))}catch(t){const e=H(t);this.eventManager._track(e),this.logger.warn(e)}}))}get _currentLocation(){return We._location}_track(e,t){return N(this,null,(function*(){const s={[ye._tevDataPageUrlKey]:t};this.eventManager._track(e,s)}))}};P(ut,"PAGE_VIEW_INTERVAL_SECONDS",1);let ct=ut;class dt{constructor(e,t,s){P(this,"logger"),P(this,"cached",null),this.domainKey=e,this.settingsStore=t,this.logger=null!=s?s:ie._getInstance("PromptsProvider")}_get(){return N(this,null,(function*(){const e=yield this._getFromCache();return e?(this.logger.verbose("Hydrated from cache"),Te.Ok(e)):this._getFromRemote()}))}get _injectedPromptGroups(){return ye._injectedPromptGroups}_getFromCache(){return N(this,null,(function*(){const e=yield this.settingsStore._getCachedPrompts();if(e){const t=1e3*ye._pnPromptsCacheTtlSeconds-Math.abs(xe(e.ts));if(t>0)return this.logger.verbose(`${(t/1e3).toFixed(2)}s until next fetch from remote`),this.cached=e,e.value;this.cached=null}return null}))}_getCachedSync(){if(this._injectedPromptGroups)return this._injectedPromptGroups;if(this.cached){if(1e3*ye._pnPromptsCacheTtlSeconds-Math.abs(xe(this.cached.ts))>0)return this.cached.value;this.cached=null}return null}_getFromRemote(){return N(this,null,(function*(){let e=this._injectedPromptGroups;if(e)this.logger.verbose("Using injected prompts");else{const t=`${ye._cdnDomainSettingsUrl}/${this.domainKey}/web/prompts`,s=new Me(Ue.GET,t),i=yield s._perform();if(i.isErr())return i;const r=i.unwrap().data;if(!r)return Te.Err(new q(B.PROMPTS_LOAD_FAILED));e=r.map((e=>de(e))),this.logger.verbose("Hydrated from remote")}return yield this.settingsStore._setCachedPrompts(e),Te.Ok(e)}))}}var ht=(e=>(e.SLIDE="SLIDE",e.PUBLISHER_CUSTOM="PUBLISHER_CUSTOM",e.NATIVE="NATIVE",e))(ht||{}),_t=(e=>(e.SECONDS="seconds",e.MINUTES="minutes",e.HOURS="hours",e.DAYS="days",e.MONTHS="months",e))(_t||{}),gt=(e=>(e.TOP="top",e.BOTTOM="bottom",e))(gt||{}),pt=(e=>(e.SESSION_START="SESSION_START",e.SESSION_TIME_ON_SITE="SESSION_TIME_ON_SITE",e.SESSION_TIME_ON_PAGE="SESSION_TIME_ON_PAGE",e.SESSION_PAGE_VIEWS="SESSION_PAGE_VIEWS",e))(pt||{});function mt(e){if(e){if("session_page_views"in e.visitor)return{type:"SESSION_PAGE_VIEWS",minPageViews:e.visitor.session_page_views};if("session_time_on_site_seconds"in e.visitor||"time_on_page_seconds"in e.visitor)return{type:"session_time_on_site_seconds"in e.visitor?"SESSION_TIME_ON_SITE":"SESSION_TIME_ON_PAGE",timeInterval:{intervalSeconds:"session_time_on_site_seconds"in e.visitor?e.visitor.session_time_on_site_seconds:e.visitor.time_on_page_seconds,displayMetric:_t.SECONDS}}}return{type:"SESSION_START"}}function St(e){var t;return e.style!==ht.PUBLISHER_CUSTOM&&(null==(t=e.behavior.is_auto_show)||t)}var Et=(e=>(e.CUT="CUT",e.FADE="FADE",e.ZOOM_IN="ZOOM_IN",e.ZOOM_OUT="ZOOM_OUT",e.SLIDE_UP="SLIDE_UP",e.SLIDE_DOWN="SLIDE_DOWN",e.SLIDE_RIGHT="SLIDE_RIGHT",e.SLIDE_LEFT="SLIDE_LEFT",e))(Et||{}),ft=(e=>(e.ENTRY="entry",e.EXIT="exit",e))(ft||{});function bt(e){return`matrix(${e.scaleX}, ${e.skewY}, ${e.skewX}, ${e.scaleY}, ${e.translateX}, ${e.translateY})`}class vt{constructor(e,t){var s;P(this,"currentOrientation"),this.prompt=e,this.logger=t,(null==(s=this._screen)?void 0:s.orientation)&&(this.currentOrientation=this._screen.orientation.type,this._screen.orientation.addEventListener("change",this._onOrientationChange.bind(this)))}static get ANIMATION_PREFIX(){return"pnax"}get _screen(){return"screen"in Be._scope?Be._scope.screen:null}get _document(){return Be._document}get _promptPackageId(){return`push-sdk-prompt-${this.prompt.id}`}get _promptPackageElement(){const e=this._document.getElementById(this._promptPackageId);return e||(this.logger.error("Unable to find injected prompt element"),null)}get _promptElement(){const e=this._promptPackageElement;if(!e)return null;const t=e.querySelector(".push-sdk-prompt-container");return t||(this.logger.error("Unable to find prompt element"),null)}get _currentAnimationTransformConfig(){const e=this._promptElement,t=e?function(e){const t=e.match(new RegExp("matrix\\((?-?[0-9.]+),\\s?(?-?[0-9.]+),\\s?(?-?[0-9.]+),\\s?(?-?[0-9.]+),\\s?(?-?[0-9.]+),\\s?(?-?[0-9.]+)\\)"));try{return{scaleX:parseInt(t.groups.scaleX),scaleY:parseInt(t.groups.scaleY),skewX:parseInt(t.groups.skewX),skewY:parseInt(t.groups.skewY),translateX:parseInt(t.groups.translateX),translateY:parseInt(t.groups.translateY)}}catch(s){return{scaleX:1,scaleY:1,skewX:0,skewY:0,translateX:0,translateY:0}}}(getComputedStyle(e).transform):{scaleX:1,scaleY:1,skewX:0,skewY:0,translateX:0,translateY:0};return{curr:t,start:Object.assign(Object.create(null),t),end:Object.assign(Object.create(null),t)}}get _entryAnimationConfig(){var e,t,s;return null!=(s=null==(t=null==(e=this.prompt.behavior)?void 0:e.display_animations)?void 0:t.enter)?s:{enabled:!0,animations:[Et.FADE],duration_milliseconds:420}}get _exitAnimationConfig(){var e,t,s;return null!=(s=null==(t=null==(e=this.prompt.behavior)?void 0:e.display_animations)?void 0:t.exit)?s:{enabled:!0,animations:[Et.FADE],duration_milliseconds:420}}_generateAnimationId(){return`${vt.ANIMATION_PREFIX}_${this.prompt.id}_${ce(5)}`}_animateIn(e,t){this._applyAnimation(ft.ENTRY,e,t)}_animateOut(e,t){this._applyAnimation(ft.EXIT,e,t)}_onOrientationChange(){var e;if(!(null==(e=this._screen)?void 0:e.orientation))return;const t=this.currentOrientation,s=this._screen.orientation.type;this.currentOrientation=this._screen.orientation.type,this._handleOrientationChange(s,t)}_getAnimationSteps(e,t,s){const i={from:{},to:{}},r=this._currentAnimationTransformConfig,n=new Set;t.animations.includes(Et.FADE)&&(n.add("opacity"),i.from.opacity=e===ft.ENTRY?0:1,i.to.opacity=e===ft.ENTRY?1:0);t.animations.includes(Et.ZOOM_IN)&&(n.add("transform"),e===ft.ENTRY?(r.start.scaleX=0,r.start.scaleY=0):(r.end.scaleX=2,r.end.scaleY=2)),t.animations.includes(Et.ZOOM_OUT)&&(n.add("transform"),e===ft.ENTRY?(r.start.scaleX=2,r.start.scaleY=2):(r.end.scaleX=0,r.end.scaleY=0));const o=s.height/2,a=s.width/2;return t.animations.includes(Et.SLIDE_DOWN)&&(n.add("transform"),e===ft.ENTRY?r.start.translateY-=o:r.end.translateY+=o),t.animations.includes(Et.SLIDE_UP)&&(n.add("transform"),e===ft.ENTRY?r.start.translateY+=o:r.end.translateY-=o),t.animations.includes(Et.SLIDE_RIGHT)&&(n.add("transform"),e===ft.ENTRY?r.start.translateX-=a:r.end.translateX+=a),t.animations.includes(Et.SLIDE_LEFT)&&(n.add("transform"),e===ft.ENTRY?r.start.translateX+=a:r.end.translateX-=a),n.size&&(i.from.willChange=Array.from(n).join(","),i.to.willChange=Array.from(n).join(",")),i.from.transform=bt(r.start),i.to.transform=bt(r.end),i}}class yt extends vt{constructor(e,t){super(e,null!=t?t:ie._getInstance("CSSAnimationCoordinator")),P(this,"lastConfig")}_clearAnimationClassNames(e,t){const s=new RegExp(`^${vt.ANIMATION_PREFIX}_`);Array.from(e.classList).forEach((i=>{i!==t&&s.test(i)&&e.classList.remove(i)}))}_handleOrientationChange(e,t){this._promptElement&&this.lastConfig&&e!==t&&this._clearAnimationClassNames(this._promptElement)}_applyAnimation(e,t,s){const i=this._promptElement;if(!i)return;if("function"==typeof t&&(t=t()),this.lastConfig=t,null!=t||(t=this._exitAnimationConfig),!t.enabled)return void this.logger.debug(`${e} animation disabled for Prompt ${this.prompt.id}`);const r=this._generateAnimationId(),n=this._getAnimationSteps(e,t,i.getBoundingClientRect()),o=this._document.createElement("style");o.id=`${r}_style`,o.setAttribute(`data-${vt.ANIMATION_PREFIX}`,"true"),o.innerText=[[`@keyframes ${r} {`,`from { opacity: ${n.from.opacity}; transform: ${n.from.transform} }`,`to { opacity: ${n.to.opacity}; transform: ${n.to.transform} }`,"}"].join(" "),[`.push-sdk-prompt-container.${r} {`,`animation-name: ${r};`,`animation-duration: ${t.duration_milliseconds/1e3}s;`,"animation-fill-mode: forwards;","}"].join(" ")].join(" "),this._promptPackageElement.prepend(o),i.classList.add(r),this._clearAnimationClassNames(i,r);const a=Array.from(this._promptPackageElement.getElementsByTagName("style"));for(const l of a)l.id!==o.id&&l.dataset[vt.ANIMATION_PREFIX]&&l.remove();i.addEventListener("animationend",(()=>{try{null==s||s()}catch(e){}}))}}class It{constructor(e,t,s,i){P(this,"logger"),P(this,"animationCoordinator"),this.prompt=e,this.group=t,this.delegate=s,this.logger=null!=i?i:ie._getInstance("PromptView"),this.animationCoordinator=new yt(e)}get document(){return Be._document}get isMobile(){return"mobile"===Be._devicePlacement}get position(){var e,t;return this.isMobile?null!=(e=this.prompt.theme.position.mobile)?e:gt.TOP:null!=(t=this.prompt.theme.position.desktop)?t:gt.TOP}get promptElementId(){return`push-sdk-prompt-${this.prompt.id}`}get promptElement(){return this.document.getElementById(this.promptElementId)}_display(){if(this.promptElement)return void this.logger.warn(`Prompt ${this.prompt.id} is already displaying`);const e=this.document.createElement("div");if(e.innerHTML=this.prompt.template_html,!e.firstChild)return void this.logger.warn("Invalid Prompt template detected");const t=e.firstChild;Be._document.body.append(t),this.animationCoordinator._animateIn({enabled:!0,animations:[Et.FADE,this.position===gt.TOP?Et.SLIDE_DOWN:Et.SLIDE_UP],duration_milliseconds:420}),this.logger.verbose(`Displaying Prompt ${this.prompt.id}`),this.delegate._onPromptDidShow(this.prompt)}_hide(){const e=this.promptElement;e?(this.logger.verbose(`Hiding ${this.prompt.id}`),this.delegate._onPromptDidHide(this.prompt),this.animationCoordinator._animateOut({enabled:!0,animations:[Et.FADE,this.position===gt.TOP?Et.SLIDE_UP:Et.SLIDE_DOWN],duration_milliseconds:420},(()=>{e.remove()}))):this.logger.warn(`Prompt ${this.prompt.id} is already hidden`)}}var Pt=(e=>(e.ALLOW="allow",e.DISMISS="dismiss",e))(Pt||{}),Dt=(e=>(e.NOT_AVAILABLE="not_available",e.OTHER_PROMPT_SHOWING="other_prompt_showing",e.ALREADY_SHOWING="already_showing",e.USER_INELIGIBLE="user_eligible",e))(Dt||{});const wt=Symbol("lazy_empty_value");function Ot(e,t,s){if(!s||void 0===s.get)throw`@lazy ${t} must be a getter`;if(s.set)throw`@lazy ${t} must not have an associated setter`;const i=`_lazy_${t}`,r=s.get;Object.defineProperty(e,i,{enumerable:!1,configurable:!1,writable:!0,value:wt}),s.get=function(){return this[i]===wt&&(this[i]=r.call(this)),this[i]}}var Tt=Object.defineProperty,Nt=Object.getOwnPropertyDescriptor,Ct=(e,t,s,i)=>{for(var r,n=i>1?void 0:i?Nt(t,s):t,o=e.length-1;o>=0;o--)(r=e[o])&&(n=(i?r(t,s,n):r(n))||n);return i&&n&&Tt(t,s,n),n};const kt="pushly-prompt-visible";class At{constructor(e,t,s,i,r,n,o,a){P(this,"_promptElements",null),P(this,"logger"),this.prompt=e,this.group=t,this.isEligible=s,this.pushSdkConfig=i,this.userStore=r,this.eventManager=n,this.delegate=o,this.logger=null!=a?a:ie._getInstance("CustomPromptView"),this._locateAndConfigure()}get _document(){return Be._document}get _defaultElementStub(){return this._document.createElement("div")}get _promptConfig(){let e=!1;const t=()=>{e||(e=!0,this.logger.warn("Custom prompt element has not been configured yet"),setTimeout((()=>{e=!1}),500))},s={actions:{allow:null,dismiss:null}};return Object.defineProperty(s,"element",{get:()=>{var e;return(null==(e=this._promptElements)?void 0:e.element)?this._promptElements.element:(t(),this._defaultElementStub)}}),s}_locateAndConfigure(){let e=null;const t=()=>N(this,null,(function*(){var s,i;try{clearTimeout(e);const r=this._document.getElementsByClassName("pushly-prompt-custom");if(!r.length)return void(e=setTimeout(t,500));const n=r[0],o={element:n,actions:{allow:null!=(s=n.getElementsByClassName("pushly-prompt-buttons-allow")[0])?s:null,dismiss:null!=(i=n.getElementsByClassName("pushly-prompt-buttons-dismiss")[0])?i:null}};o.actions.allow?o.actions.allow.addEventListener("click",this._allow.bind(this)):this.logger.warn("Prompt allow button cannot be located"),o.actions.dismiss?o.actions.dismiss.addEventListener("click",this._dismiss.bind(this)):this.logger.warn("Prompt dismiss button cannot be located"),this._promptElements=o,this.logger.info("Custom prompt located and configured"),this._setSupportedClassName(),yield this._setInitialSubscriptionClassName(),this.isEligible?this._setEligibleClassNames():this._setIneligibleClassNames()}catch(r){const e=H(r);this.logger.warn(e),this.eventManager._track(e)}}));t().then()}get _classNames(){const e=this.pushSdkConfig.classNames||{};return e.webPushUnsupported=e.webPushUnsupported||"pushly-web-push-unsupported",e.webPushSupported=e.webPushSupported||"pushly-web-push-supported",e.subscriptionNone=e.subscriptionNone||"pushly-subscription-none",e.subscriptionSubscribed=e.subscriptionSubscribed||"pushly-subscription-subscribed",e.subscriptionUnsubscribed=e.subscriptionUnsubscribed||"pushly-subscription-unsubscribed",e.subscriptionDenied=e.subscriptionDenied||"pushly-subscription-denied",e.subscriptionDismissed=e.subscriptionDismissed||"pushly-subscription-dismissed",e.promptIneligible=e.promptIneligible||"pushly-prompt-ineligible",e.promptEligible=e.promptEligible||"pushly-prompt-eligible",e}_display(){this.delegate._onPromptDidShow(this.prompt)}_hide(){this.delegate._onPromptDidHide(this.prompt)}_handlePermissionsResponse({permission:e}){switch(e){case"granted":this._setPromptCompositeSubscribedClassNames();break;case"denied":this._setSubscriptionDeniedClassNames();break;case"default":this._setSubscriptionDismissedClassNames()}}_allow(){return N(this,null,(function*(){yield this.delegate._processDispatchMessage({prompt_action:{id:this.prompt.id,type:Pt.ALLOW,is_custom_prompt:!0}})}))}_dismiss(){return N(this,null,(function*(){this._setSubscriptionDismissedClassNames(),yield this.delegate._processDispatchMessage({prompt_action:{id:this.prompt.id,type:Pt.DISMISS,is_custom_prompt:!0}})}))}_setInitialSubscriptionClassName(){return N(this,null,(function*(){const e=yield this.userStore._getSubscriberStatus();e===Se.DENIED?this._setDeniedClassNames():e===Se.DISMISSED?this._setDismissedClassNames():e===Se.SUBSCRIBED?this._setSubscribedClassNames():this._setNoSubscriptionClassNames()}))}_setPromptCompositeSubscribedClassNames(){this._setIneligibleClassNames(),this._setSubscribedClassNames(),this._promptConfig.element.classList.remove(kt)}_setSubscriptionDismissedClassNames(){this._setIneligibleClassNames(),this._setDismissedClassNames(),this._promptConfig.element.classList.remove(kt)}_setSubscriptionDeniedClassNames(){this._setIneligibleClassNames(),this._setDeniedClassNames(),this._promptConfig.element.classList.remove(kt)}_setUnsupportedClassName(){const{element:e}=this._promptConfig;e.classList.add(this._classNames.webPushUnsupported),e.classList.remove(this._classNames.webPushSupported)}_setSupportedClassName(){const{element:e}=this._promptConfig;e.classList.add(this._classNames.webPushSupported),e.classList.remove(this._classNames.webPushUnsupported)}_setEligibleClassNames(){const{element:e}=this._promptConfig;e.classList.remove(this._classNames.promptIneligible),e.classList.add(this._classNames.promptEligible)}_setIneligibleClassNames(){const{element:e}=this._promptConfig;e.classList.remove(this._classNames.promptEligible),e.classList.add(this._classNames.promptIneligible)}_setNoSubscriptionClassNames(){const{element:e}=this._promptConfig;e.classList.add(this._classNames.subscriptionNone),e.classList.remove(this._classNames.subscriptionSubscribed,this._classNames.subscriptionDismissed,this._classNames.subscriptionDenied,this._classNames.subscriptionUnsubscribed)}_setSubscribedClassNames(){const{element:e}=this._promptConfig;e.classList.add(this._classNames.subscriptionSubscribed),e.classList.remove(this._classNames.subscriptionNone,this._classNames.subscriptionDismissed,this._classNames.subscriptionDenied,this._classNames.subscriptionUnsubscribed)}_setDismissedClassNames(){const{element:e}=this._promptConfig;e.classList.add(this._classNames.subscriptionDismissed),e.classList.remove(this._classNames.subscriptionNone,this._classNames.subscriptionSubscribed,this._classNames.subscriptionDenied,this._classNames.subscriptionUnsubscribed)}_setDeniedClassNames(){const{element:e}=this._promptConfig;e.classList.add(this._classNames.subscriptionDenied),e.classList.remove(this._classNames.subscriptionNone,this._classNames.subscriptionSubscribed,this._classNames.subscriptionDismissed,this._classNames.subscriptionUnsubscribed)}}Ct([Ot],At.prototype,"_document",1),Ct([Ot],At.prototype,"_defaultElementStub",1),Ct([Ot],At.prototype,"_promptConfig",1),Ct([Ot],At.prototype,"_classNames",1);var Rt=Object.defineProperty,Lt=Object.getOwnPropertyDescriptor,Mt=(e,t,s,i)=>{for(var r,n=i>1?void 0:i?Lt(t,s):t,o=e.length-1;o>=0;o--)(r=e[o])&&(n=(i?r(t,s,n):r(n))||n);return i&&n&&Rt(t,s,n),n};class Ut{constructor(e,t,s,i,r,n,o,a,l,u,c){P(this,"logger"),P(this,"isDisplayEvaluationReady",!1),P(this,"isPromptLoadingCompleted",!1),P(this,"timeInSessionTimer"),P(this,"manualShowRequestIsActive",!1),P(this,"promptViewInitializedCallbacks",[]),P(this,"allPrompts",[]),P(this,"matchedPrompt"),P(this,"activeView"),P(this,"lastPageViewed",null),this.pushSdkConfig=e,this.domain=t,this.promptsProvider=s,this.notificationPermissionService=i,this.userStore=r,this.settingsStore=n,this.sessionManager=o,this.eventManager=a,this.debugController=l,this.promptLifecycleCallbacks=u,this.lastPageViewed=this._currentHref,this.timeInSessionTimer=new lt("prompts_tis_timer",this._handleSessionTimerDidAdvance.bind(this),1),this.logger=null!=c?c:ie._getInstance("PromptsController"),this._load()}_load(){this._loadPrompts()}get _devicePlacement(){return Be._devicePlacement}get _isTwoStepPromptsRequired(){return Be._requires2Step}get _currentHref(){return Be._location.href}get _document(){return Be._document}get _currentPageMetaKeywords(){const e=["meta[name='keywords']","meta[name='parsely-tags']","meta[name='sailthru.tags']"];try{return Array.from(new Set(Array.from(this._document.querySelectorAll(e.join(","))).filter((e=>e instanceof HTMLMetaElement&&!!e.content)).flatMap((e=>e.content.split(","))).map((e=>e.toString().trim().toLowerCase())).filter((e=>e))))}catch(t){}return[]}get _isReady(){return this.isPromptLoadingCompleted&&this.isDisplayEvaluationReady}setPromptViewInitializedCallbacks(e){this.activeView?e(this.activeView):this.promptViewInitializedCallbacks.push(e)}_setIsWebPushSupported(e){var t;e.isErr()&&this.debugController._debugPromptNotShown(Ye.WEB_PUSH_UNSUPPORTED,null!=(t=e.getErr().details)?t:"unknown"),this.setPromptViewInitializedCallbacks((t=>{t instanceof At&&(e?t._setSupportedClassName():t._setUnsupportedClassName())}))}_startDisplayEvaluations(){return N(this,null,(function*(){this.isDisplayEvaluationReady=!0,this._isReady&&!this.matchedPrompt&&(yield this._startMatchedPromptSelection()),this.timeInSessionTimer._start()}))}get _isEnabled(){return this.timeInSessionTimer.isStarted&&!this.timeInSessionTimer.isPaused}_enable(){this.logger.verbose("Enabling session timer"),this.timeInSessionTimer._unpause()}_disable(){this.logger.verbose("Disabling session timer"),this.timeInSessionTimer._pause()}_loadPrompts(){return N(this,null,(function*(){this.logger.verbose("Loading prompts");const e=yield this.promptsProvider._get();if(e.isErr())return this.logger.warn("No prompts available",e.getErr()),void this.debugController._debugPromptNotShown(Ye.PROMPTS_LOAD_FAILED);const t=e.unwrap();if(!t.length)return this.logger.warn("No prompts available"),void this.debugController._debugPromptNotShown(Ye.NO_ELIGIBLE_PROMPTS);this.allPrompts=t.flatMap((e=>e.prompts.map((t=>({prompt:t,group:e}))))),yield this._handlePromptsLoaded()}))}_handlePromptsLoaded(){return N(this,null,(function*(){this.logger.verbose("Prompts loaded"),this.isPromptLoadingCompleted=!0,this._isReady&&(yield this._startMatchedPromptSelection())}))}_handleSessionTimerDidAdvance(){return N(this,null,(function*(){if(!this._isReady)return;let e=this.matchedPrompt;e||this._currentHref===this.lastPageViewed||(this.lastPageViewed=this._currentHref,yield this._startMatchedPromptSelection(),this._enable()),e&&(this.activeView||!St(e.prompt)&&!this.manualShowRequestIsActive?this._disable():yield this._attemptToShowPrompt(e))}))}_setLastMatchedPrompt(e){return N(this,null,(function*(){var t,s;if((null==(t=this.matchedPrompt)?void 0:t.prompt.id)===e.prompt.id)return;const i=null!=(s=e.prompt.name)?s:e.group.name;this.logger.verbose(`Setting matched Prompt: ${e.prompt.id} (${e.prompt.style}) ${i}`),this.matchedPrompt=yield this._buildMatchedPrompt(e),this.settingsStore._setLastMatchedPromptId(e.prompt.id).then(),this.notificationPermissionService._setAdditionalPermissionEventData({prompt_id:e.prompt.id})}))}_clearLastMatchedPrompt(){return N(this,null,(function*(){this.matchedPrompt=void 0,yield this.settingsStore._setLastMatchedPromptId(null)}))}_showPrompt(e,t){return N(this,null,(function*(){var s,i,r,n;this.manualShowRequestIsActive=!0;let o=null;if(void 0===e)this.logger.verbose("Show prompt invoked"),this.matchedPrompt||(yield this._startMatchedPromptSelection()),o=null!=(s=this.matchedPrompt)?s:null;else if(this.logger.verbose(`Show prompt invoked for ${e}`),(null==(i=this.matchedPrompt)?void 0:i.prompt.id)===e)o=this.matchedPrompt;else{const t=this.allPrompts.find((({prompt:t})=>t.id===e));t&&(o=yield this._buildMatchedPrompt(t))}if(!o)return this.logger.warn(`Prompt${void 0===e?"":` ${e}`} not found`),void(null==(n=null==(r=this.promptLifecycleCallbacks)?void 0:r.onPushSDKFailedToShowPrompt)||n.call(r,null!=e?e:null,Dt.NOT_AVAILABLE));const a=yield this._hasMetGlobalAndUserConditions(o.prompt,t);if(o.prompt.style===ht.PUBLISHER_CUSTOM){const e=o.displayCoordinator;a?e._setEligibleClassNames():e._setIneligibleClassNames()}a&&(this._isEnabled||this._enable(),yield this._attemptToShowPrompt(o))}))}_attemptToShowPrompt(e){return N(this,null,(function*(){(e.prompt.style===ht.PUBLISHER_CUSTOM||(yield this._evaluatePromptConditions(e.prompt)))&&(yield this._showMatchedPrompt(e))}))}_showMatchedPrompt(e){return N(this,null,(function*(){this._disable();const t=e.displayCoordinator?e:yield this._buildMatchedPrompt(e),s=t.displayCoordinator;this.activeView=s,yield this.settingsStore._incrementViewedOccurrencesForPromptId(t.prompt.id),t.prompt.style!==ht.NATIVE?s._display():(this.notificationPermissionService._setPermissionEventContext({dismissalExpirationSeconds:this._extractPromptDismissalExpirationValue(t.prompt)}),yield this.notificationPermissionService._requestPermission())}))}_processDispatchMessage(e){return N(this,null,(function*(){var t,s,i,r,n;let o=this.activeView;if(!o&&e.prompt_action.is_custom_prompt&&(null==(t=this.matchedPrompt)?void 0:t.prompt.id)===e.prompt_action.id&&(o=this.matchedPrompt.displayCoordinator),!o||!e.prompt_action.id||e.prompt_action.id!==o.prompt.id)return void this.logger.debug("Prompt not available to receive message",e);o._hide();const a=this._extractPromptDismissalExpirationValue(o.prompt);switch(this.notificationPermissionService._setPermissionEventContext({dismissalExpirationSeconds:a}),e.prompt_action.type){case Pt.ALLOW:{this.logger.debug("Received Prompt Allow"),this.eventManager._track(ae.PROMPT_ACCEPTED,{prompt_id:e.prompt_action.id}),null==(i=null==(s=this.promptLifecycleCallbacks)?void 0:s.onPushSDKDidReceivePromptResponse)||i.call(s,o.prompt.id,!0);const t=yield this.notificationPermissionService._requestPermission();o instanceof At&&o._handlePermissionsResponse(t);break}case Pt.DISMISS:this.logger.debug("Received Prompt Dismiss"),this.eventManager._track(ae.PROMPT_DISMISSED,{prompt_id:e.prompt_action.id}),0===a?(this.logger.debug("Setting subscriber status to NOT_DETERMINED"),yield this.userStore._setSubscriberStatus(Se.NOT_DETERMINED)):(this.logger.debug(`Setting subscriber status to DISMISSED for ${a}s`),yield this.userStore._setSubscriberStatusDismissed(a)),this.notificationPermissionService._resetPermissionEventContext(),null==(n=null==(r=this.promptLifecycleCallbacks)?void 0:r.onPushSDKDidReceivePromptResponse)||n.call(r,o.prompt.id,!1);break;default:this.logger.warn("Received unknown prompt message: ",e),this.debugController._debugUnknownPromptMessage(e)}}))}_onPromptDidShow(e){return N(this,null,(function*(){var t,s;this.eventManager._track(ae.PROMPT_SHOWN,{prompt_id:e.id}),null==(s=null==(t=this.promptLifecycleCallbacks)?void 0:t.onPushSDKDidShowPrompt)||s.call(t,e.id)}))}_onPromptDidHide(e){return N(this,null,(function*(){var t;e.style!==ht.PUBLISHER_CUSTOM&&e.id===(null==(t=this.activeView)?void 0:t.prompt.id)?this.activeView=void 0:this.logger.verbose("Hidden prompt does not match active prompt")}))}_startMatchedPromptSelection(){return N(this,null,(function*(){var e,t,s,i;let r;if(this.logger.verbose("Starting matched prompt selection"),this.matchedPrompt)r=this.allPrompts.find((({prompt:e})=>e.id===this.matchedPrompt.prompt.id));else{const e=yield this.settingsStore._getLastMatchedPromptId();e&&(r=this.allPrompts.find((({prompt:t})=>t.id===e)))}if(r){const e=this._evaluatePromptGroupConditions(r.group);!e.isErr()&&e.unwrapOrNull()||(r=void 0)}if(!r){const e=this.allPrompts.sort((({group:e},{group:t})=>-(e.priority-t.priority)));this._isTwoStepPromptsRequired&&this.logger.info("Browser requires 2-step prompt experience. Filtering prompts.");const t=e.reduce(((e,t)=>{const s=t.group.prompts.filter((e=>!this._isTwoStepPromptsRequired||e.style!==ht.NATIVE));return s.length?e.push([t.group,s]):this.logger.verbose(`Removing PromptGroup ${t.group.id} - no available prompts.`,t),e}),[]);for(const[s,i]of t){const e=this._evaluatePromptGroupConditions(s);if(e.isErr()){this.logger.debug(`Prompt not shown due to ${e.getErr()}`);break}e.unwrapOrNull()&&(r={group:s,prompt:1===i.length?i[0]:this._pickWeightedRandomPrompt(i)})}if(r&&void 0!==r.group.behavior.display_to_pct){const e=r.group.behavior.display_to_pct;if(e<100){Math.floor(100*Math.random())>e&&(r=void 0)}}}if(r&&(yield this._hasMetGlobalAndUserConditions(r.prompt))){if(this.logger.debug("Eligible prompt found",r),null==(t=null==(e=this.promptLifecycleCallbacks)?void 0:e.onPushSDKUserIsEligibleToPrompt)||t.call(e),yield this._setLastMatchedPrompt(r),!St(r.prompt))return;(n=r.prompt).style!==ht.PUBLISHER_CUSTOM&&"SESSION_START"===mt(n.conditions).type?yield this._attemptToShowPrompt(r):this.logger.verbose("Eligible prompt display delayed due to conditions",r.prompt.conditions)}else this.logger.info("No matched prompts available"),this._disable(),yield this._clearLastMatchedPrompt(),null==(i=null==(s=this.promptLifecycleCallbacks)?void 0:s.onPushSDKUserIsIneligibleToPrompt)||i.call(s);var n}))}_hasMetGlobalAndUserConditions(e,t){return N(this,null,(function*(){if(null==t?void 0:t.skipEligibilityCheck)return e.style===ht.PUBLISHER_CUSTOM||(yield this.userStore._getSubscriberStatus())!==Se.DENIED;const s=yield this.notificationPermissionService._getIsEligibleToPrompt();if(s.isErr()){const e=s.getErr();return(e===Ye.USER_PERMISSION_DENIED||e===Ye.USER_PERMISSION_DISMISSED||e===Ye.USER_PERMISSION_GRANTED)&&(this.logger.debug(`Prompt not shown due to: ${e}`),this.debugController._debugPromptNotShown(e)),!1}const i=yield this._evaluateGlobalConditions(e);return!i.isErr()||(this.logger.debug(`Prompt not shown due to: ${i.getErr()}`),!1)}))}_extractPromptDismissalExpirationValue(e){const t=e.behavior.post_dismiss_redisplay;return t.enabled?t.fcap.interval_seconds:ye._defaultDismissedStatusExpirationSeconds}_pickWeightedRandomPrompt(e){const t=e.reduce(((e,t)=>e.concat(new Array(t.weight).fill(t))),[]);return t[Math.floor(Math.random()*t.length)]}_buildMatchedPrompt(e){return N(this,null,(function*(){return y(v({},e),{displayCoordinator:"displayCoordinator"in e?e.displayCoordinator:e.prompt.style===ht.PUBLISHER_CUSTOM?yield this._buildCustomPromptView(e):this._buildPromptView(e)})}))}_buildPromptView(e){if(e.displayCoordinator instanceof It)return e.displayCoordinator;const t=new It(e.prompt,e.group,this);return this.promptViewInitializedCallbacks.forEach((e=>e(t))),t}_buildCustomPromptView(e){return N(this,null,(function*(){if(e.displayCoordinator instanceof At)return e.displayCoordinator;const t=new At(e.prompt,e.group,yield this._hasMetGlobalAndUserConditions(e.prompt),this.pushSdkConfig,this.userStore,this.eventManager,this);return this.promptViewInitializedCallbacks.forEach((e=>e(t))),t}))}_evaluateGlobalConditions(e){return N(this,null,(function*(){var t,s,i,r,n;const o=e.id;if(this.activeView)return void 0!==o&&this.activeView.prompt.id===o?(null==(s=null==(t=this.promptLifecycleCallbacks)?void 0:t.onPushSDKFailedToShowPrompt)||s.call(t,o,Dt.ALREADY_SHOWING),Te.Err(`Prompt ${o} is already showing`)):(null==(r=null==(i=this.promptLifecycleCallbacks)?void 0:i.onPushSDKFailedToShowPrompt)||r.call(i,null,Dt.OTHER_PROMPT_SHOWING),Te.Err(`Another prompt, ${this.activeView.prompt.id}, is already showing.`));const a=null==(n=this.domain.frequency_caps)?void 0:n.prompts;if(a){const e=yield this._evaluateDomainPromptFCap(o,a);if(e.isErr())return this.debugController._debugPromptNotShown(Ye.PROMPT_INELIGIBLE_FCAP),e}return Te.Ok(!0)}))}_evaluateDomainPromptFCap(e,t){return N(this,null,(function*(){var s,i;yield this.settingsStore._dropViewedPromptOccurrencesNotInInterval(t.interval_seconds);return(yield this.settingsStore._getViewedPromptOccurrencesCount())>=t.occurrences?(null==(i=null==(s=this.promptLifecycleCallbacks)?void 0:s.onPushSDKFailedToShowPrompt)||i.call(s,e,Dt.USER_INELIGIBLE),Te.Err(Ye.PROMPT_INELIGIBLE_FCAP)):Te.Ok(!0)}))}_evaluatePromptGroupConditions(e){var t,s;if(null==(t=e.conditions)?void 0:t.display){const t=this._evaluatePromptGroupDisplayConditions(e.conditions.display);if(!t.unwrapOrNull())return t}return(null==(s=e.conditions)?void 0:s.page)?this._evaluatePromptGroupPageConditions(e.conditions.page):Te.Ok(!0)}_evaluatePromptGroupDisplayConditions(e){switch(e[this._devicePlacement]){case"enabled":return Te.Ok(!0);case"pass":return Te.Ok(!1);case"disabled":return Te.Err(`platform_disabled_${this._devicePlacement}`)}}_evaluatePromptGroupPageConditions(e){const t=e=>{const t=e.replace(/\?/g,"\\?").replace(/\+|%20/g,"(?:\\+|%20)");return new RegExp(t,"i").test(this._currentHref)};if(Array.isArray(e.excluded_page_urls)&&e.excluded_page_urls.length>0&&e.excluded_page_urls.some(t))return Te.Ok(!1);if(Array.isArray(e.keywords)&&e.keywords.length>0){if(!this._currentPageMetaKeywords.length)return Te.Ok(!1);if(!e.keywords.map((e=>e.trim().toLowerCase())).some((e=>this._currentPageMetaKeywords.includes(e))))return Te.Ok(!1)}return Array.isArray(e.page_urls)&&e.page_urls.length>0?Te.Ok(e.page_urls.some(t)):Te.Ok(!0)}_evaluatePromptConditions(e){return N(this,null,(function*(){const t=mt(e.conditions);return function(e){return["SESSION_TIME_ON_SITE","SESSION_TIME_ON_PAGE"].includes(e.type)}(t)?this._evaluatePromptSessionTimeIntervalCondition(t):!function(e){return"SESSION_PAGE_VIEWS"===e.type}(t)||this._evaluatePromptPageViewsCondition(t)}))}_evaluatePromptPageViewsCondition(e){return N(this,null,(function*(){var t;this.logger.info(`Prompt condition: Page views [at least ${e.minPageViews} pages]`);return(yield this.sessionManager.transient.store._getSessionPageViewCount())>=(null!=(t=e.minPageViews)?t:0)}))}_evaluatePromptSessionTimeIntervalCondition(e){return N(this,null,(function*(){var t,s;switch(e.type){case pt.SESSION_TIME_ON_SITE:this.logger.info(`Prompt condition: Time on site [at least ${e.timeInterval.intervalSeconds} seconds]`);return(yield this.sessionManager.transient.store._getSessionRuntimeSeconds())>=(null!=(t=e.timeInterval.intervalSeconds)?t:0);case pt.SESSION_TIME_ON_PAGE:{this.logger.info(`Prompt condition: Time on page [at least ${e.timeInterval.intervalSeconds} seconds]`);const t=yield this.sessionManager.transient.store._getCurrentPageViewStart();if(!t)return!1;return Math.abs(xe(t.getTime()))/1e3>=(null!=(s=e.timeInterval.intervalSeconds)?s:0)}}}))}}Mt([Ot],Ut.prototype,"_devicePlacement",1),Mt([Ot],Ut.prototype,"_isTwoStepPromptsRequired",1);var xt=(e=>(e.sub="sub",e.sdk="sdk",e.WORKER="w",e))(xt||{}),$t=(e=>(e.IDB="idb",e.COOKIE="cookie",e.LEGACY_COOKIE="legacy_cookie",e.MEM="mem",e.SESSION="session",e))($t||{});class Kt{constructor(e,t,s){P(this,"_storageType"),P(this,"_storeName"),P(this,"_logger"),this._storageType=e,this._storeName=t,this._logger=null!=s?s:ie._getInstance(`${e}${t?`:${t}`:""}`)}get _isInWorkerGlobalScope(){return We._isInWorkerGlobalScope}_getLastUpdatedAt(){return N(this,null,(function*(){const e=yield this._getData(x._pnStorageTypeLuaKey);return e.isErr()?new Date(0):new Date(e.unwrap().ts)}))}_setLastUpdatedAt(e){return N(this,null,(function*(){const t=new Date(e),s=yield this._setData(x._pnStorageTypeLuaKey,t.getTime());return s.isErr()?s:Te.Ok(t)}))}}const Wt=()=>new q(B.STORAGE_NOT_AVAILABLE,null," - Cookie"),Ft=e=>new q(B.STORAGE_KEY_EMPTY,null,e),Vt=e=>new q(B.STORAGE_FAILED_TO_OPEN,e," - Cookie"),Bt=class e extends Kt{constructor(t,s=ie._getInstance("CookieStore")){super($t.COOKIE,t,s),P(this,"_preDomainConfigTempData"),e._domainKey=ye._dynamicDomainKey,e._domain=ye._injectedDomainConfig}static _setDomainKey(e){this._domainKey=e}static _setDomain(e){this._domain=e}get domainKey(){var t,s;return null!=(s=null==(t=e._domain)?void 0:t.domain_key)?s:e._domainKey}get allowedDomains(){var t;return null==(t=e._domain)?void 0:t.whitelist_domains}get isInIsolationMode(){var t;return!!(null==(t=e._domain)?void 0:t.flags.includes(ye._domainFeatUseIsolatedCookiesFlag))&&!!this.isolationKey}get isolationKey(){var e;return null==(e=this.domainKey)?void 0:e.slice(-8)}get _isAvailable(){return!Be._isInWorkerGlobalScope&&"string"==typeof this._documentCookie}get _isUsingLegacyCookies(){return null===this._storeName}get _documentCookie(){return Be._document.cookie}set _documentCookie(e){Be._document.cookie=e}_getData(e){return N(this,null,(function*(){return this._getDataSync(e)}))}_setData(e,t){return N(this,null,(function*(){return this._setDataSync(e,t)}))}_removeData(e){return N(this,null,(function*(){return this._removeDataSync(e)}))}_getDataSync(e){var t,s,i;if(!this._isAvailable)return Te.Err(Wt());const r=this._openCookie();if(r.isErr())return r;const n=r.unwrap();let o;return o=this._isUsingLegacyCookies?n[this._buildName(e)]:e===ye._pnStorageTypeLuaKey?null!=(t=n[ye._pnStorageTypeLuaKey])?t:null:null==(s=n[this._storeName])?void 0:s[e],null==o&&e!==ye._pnStorageTypeLuaKey?Te.Err(Ft(e)):Te.Ok({value:o,ts:null!=(i=n[ye._pnStorageTypeLuaKey])?i:0,sourceType:this._storageType})}_setDataSync(e,t){var s;const i=this._openCookie();if(i.isErr())return i;const r=i.unwrap();let n,o;return this._isUsingLegacyCookies?(n=e,o=t):(e===ye._pnStorageTypeLuaKey?r[e]=t:(null!=r[s=this._storeName]||(r[s]={}),r[this._storeName][e]=t),n=ye._pnCookieStorageKey,o=r),this._persist(n,o,void 0,e===ye._pnStorageTypeLuaKey),Te.Ok(t)}_removeDataSync(e){const t=this._openCookie();if(t.isErr())return t;const s=t.unwrap();let i,r,n;return this._isUsingLegacyCookies?(i=e,r=null,n=-1):s[this._storeName]&&(delete s[this._storeName][e],i=ye._pnCookieStorageKey,r=s),i&&this._persist(i,r,n),Te.Ok(null)}_openCookie(){var e;let t={};try{const i=ye._pnCookieStorageKeyRegex,r=ye._pnCookieStorageLegacyKeyPrefixRegex,n=this._isUsingLegacyCookies?"":"{}",o=this._documentCookie.split(";").map((e=>e.trim()));let a=this._isUsingLegacyCookies?Object.fromEntries(o.filter((e=>r.test(e))).map((e=>e.split(/=/)))):null!=(e=o.find((e=>i.test(e))))?e:"";if(this._isUsingLegacyCookies||(!a&&this._preDomainConfigTempData?a=this._preDomainConfigTempData:this._preDomainConfigTempData=void 0),a&&"string"==typeof a){const e=a.split(/=/);let i=2===e.length?""===e[1]?n:e[1]:n;if(!this._isUsingLegacyCookies)try{i=(e=>{let t;try{"TextDecoder"in self&&"function"==typeof self.TextDecoder&&"decode"in self.TextDecoder.prototype&&(t=(new self.TextDecoder).decode(Xe(e)))}catch(s){console.warn("Unable to decode base64 string",s)}return void 0===t&&(t=ze(e)),t})(i)}catch(s){}const r=JSON.parse(i);r&&"object"==typeof r&&!Array.isArray(r)&&(t=r)}else t=a&&"object"==typeof a&&!Array.isArray(a)?a:{}}catch(i){const e=Vt(H(i));return this._logger.warn("Unable to open cookie",e.message),Te.Err(e)}return Te.Ok(t)}_persist(t,s,i,r){try{const o=null===this._storeName;o||!s||"object"!=typeof s||Array.isArray(s)||!0===r||(s[ye._pnStorageTypeLuaKey]=(new Date).getTime());let a=s;if("string"!=typeof s&&(a=JSON.stringify(s)),!o)try{a=Ze(a)}catch(n){}const l=`${this._buildName(t)}=${a}`;if(!e._domain)return void(this._preDomainConfigTempData=l);const u=new Date;u.setTime(u.getTime()+86400*(null!=i?i:ye._pnCookieStorageMaxDays)*1e3);const c=null===a?"-1":u.toUTCString(),d=this._getDomain();this._documentCookie=`${l};expires=${c};path=/;domain=${d};SameSite=Strict`}catch(o){this._logger.error(H(o))}}_buildName(e){return this.isInIsolationMode?`${e}_${this.isolationKey}`:e}_getDomain(){var e;let t=Be._location.hostname;if(!this.isInIsolationMode){if(1==(null==(e=this.allowedDomains)?void 0:e.length))t=this.allowedDomains[0];else{const e=(()=>{const e=Be._document;let t,s,i="_sw_tld_check=cookie",r=Be._location.hostname.split(".");for(t=r.length-2;t>=0;t--)if(s=r.slice(t).join("."),e.cookie=i+";domain=."+s+";SameSite=strict;",e.cookie.indexOf(i)>-1)return e.cookie=i.split("=")[0]+"=;domain=."+s+";SameSite=strict;expires=Thu, 01 Jan 1970 00:00:01 GMT;",s})();e&&(t=e)}t||(t=Be._location.hostname,"localhost"!==t&&(t=`.${t.split(".").splice(-2).join(".")}`))}return t}};P(Bt,"_domainKey"),P(Bt,"_domain");let Gt=Bt;class Ht{constructor(e,t){this.debugController=e,this.logger=t}get(e,t={}){return new Proxy(t,{get:(t,s,i)=>{var r;return s in t?t[s]:he(String(s))in t?t[he(String(s))]:void(["toJSON","children"].includes(String(s))||(this.logger.warn(`Unknown key: context.${e}.${String(s)}`),null==(r=this.debugController)||r._debugUnknownContextKey(`context.${e}.${String(s)}`)))}})}}const jt=class e{constructor(t,s,i,r,n){var o;P(this,"heartbeatInterval"),P(this,"inactivityTimeout"),P(this,"_logger"),P(this,"sessionStartThrottle",((e,t)=>{let s=!1;return function(){s||(e(),s=!0,setTimeout((function(){s=!1}),t))}})((()=>N(this,null,(function*(){return yield this._checkAndStartSession()}))),100)),this.eventManager=t,this.userStore=s,this.sessionStore=i;const a=null==(o=null==r?void 0:r.threshold)?void 0:o.intervalSeconds;this._logger=null!=n?n:ie._getInstance("HeartbeatManager"),this.heartbeatInterval=null,this.inactivityTimeout=1e3*(a||e.DEFAULT_INACTIVITY_TIMEOUT_SECONDS),this._initializeEventListeners()}get _window(){return Be._scope}get _document(){return Be._document}onSubscriptionChanged(e){return N(this,null,(function*(){e?yield this._checkAndStartSession():this._stopHeartbeat()}))}_initializeEventListeners(){this._document.addEventListener("visibilitychange",(()=>this._handleVisibilityChange(!this._document.hidden))),window.addEventListener("focus",this._handleFocus.bind(this)),window.addEventListener("blur",this._handleBlur.bind(this));["mousedown","keydown","mousemove","scroll","touchstart"].forEach((e=>{this._document.addEventListener(e,this._handleUserActivity.bind(this))}))}_handleVisibilityChange(e){e?this.sessionStartThrottle():this._stopHeartbeat()}_handleFocus(){this.sessionStartThrottle()}_handleBlur(){this._stopHeartbeat()}_handleUserActivity(){return N(this,null,(function*(){const e=yield this.userStore._getIsSubscribed();this._document.hasFocus()&&e&&(yield this._checkAndStartSession())}))}_checkAndStartSession(){return N(this,null,(function*(){if(!(yield this.userStore._getIsSubscribed()))return;const t=yield this.getDateString(),s=yield this.sessionStore._getLastActivity(),i=Date.now()-((null==s?void 0:s.getTime())||0),r=yield this.sessionStore._getHeartbeatSessionDate(),n=null!=r?yield this.getDateString(r):null;i>=this.inactivityTimeout||t!==n?(yield this._startNewSession(),yield Ce(e.HEARTBEAT_INTERVAL_TIME),yield this._startHeartbeat()):yield this._startHeartbeat()}))}_startNewSession(){return N(this,null,(function*(){yield this.sessionStore._setHeartbeatSessionDate(new Date),yield this.sessionStore._setLastActivity(new Date),this.eventManager._track(ae.SESSION_START),this._logger.verbose("Starting new heartbeat session")}))}_startHeartbeat(){return N(this,null,(function*(){if(this.heartbeatInterval)return;const t=yield this.userStore._getIsSubscribed();this._logger.verbose("Starting heartbeat session"),this.heartbeatInterval=setInterval((()=>{this._document.hasFocus()&&t?(this.eventManager._track(ae.SESSION_HEARTBEAT),this.sessionStore._setLastActivity(new Date),this._logger.verbose("Sending session heartbeat event")):this._stopHeartbeat()}),e.HEARTBEAT_INTERVAL_TIME)}))}_stopHeartbeat(){this.heartbeatInterval&&(this._logger.verbose("Stopping heartbeat session"),clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}getDateString(){return N(this,arguments,(function*(e=new Date){const t=yield this.userStore._getTimeZone();return e.toLocaleDateString("en-US",{timeZone:t||void 0})}))}};P(jt,"DEFAULT_INACTIVITY_TIMEOUT_SECONDS",1800),P(jt,"HEARTBEAT_INTERVAL_TIME",6e4);let qt=jt;class Yt{constructor(e,t,s,i,r,n,o){P(this,"iid",ce(5)),P(this,"domainConfigProvider"),P(this,"notificationPermissionService",null),P(this,"promptsController",null),P(this,"_logger"),P(this,"isLoading"),P(this,"_isLoaded"),P(this,"_isExited"),P(this,"_isEnabled"),P(this,"_domainKey"),P(this,"_loadConfig"),P(this,"pageViewProcessor"),P(this,"_pushSdkLifecycleCallbacks"),P(this,"_permissionLifecycleCallbacks"),P(this,"_appMessageLifecycleCallbacks"),P(this,"promptLifecycleCallbacks"),P(this,"_onLoadedCallbacks"),P(this,"_postConfigActionsQueue"),P(this,"legacyEventCallbacks"),P(this,"_heartbeatManager"),this.eventManager=e,this.settingsStore=t,this.userStore=s,this.sessionManager=i,this.debugController=r,this.sessionStore=n,this.settingsStore=t,this.userStore=s,this._logger=null!=o?o:ie._getInstance(),this.isLoading=!1,this._isLoaded=!1,this._isExited=!1,this._isEnabled=!0,this.legacyEventCallbacks={},this._sendImpressionEvent()}get _currentPageSearchParams(){return new URLSearchParams(Be._location.search)}_executeWhenConfigured(e){return N(this,null,(function*(){return this._isLoaded?Promise.resolve(e()).catch((e=>{const t=H(e);this._logger.error(t),this.eventManager._track(t)})).then((e=>null!=e?e:null)):(null!=this._postConfigActionsQueue||(this._postConfigActionsQueue=[]),this._postConfigActionsQueue.push(e),null)}))}_executeWhenConfiguredIfEnabled(e){return N(this,null,(function*(){return this._executeWhenConfigured((()=>this._isEnabled?e():null))}))}get loadConfig(){return this._loadConfig}get isLoaded(){return this._isLoaded}get isExited(){return this._isExited}get isEnabled(){return this._isEnabled}get _legacyContext(){var e,t,s;const i=new Ht(this.debugController,this._logger),r=null!=(s=null!=(t=ye._injectedDomainConfig)?t:null==(e=this.domainConfigProvider)?void 0:e._getCachedSync())?s:{},n=this.userStore._getAnonymousIdSync(),o={puuid:n,externalId:this.userStore._getExternalIdSync(),subscriberState:"none",isSubscribed:!1,getId:()=>n};try{const e=this.userStore._getSubscriberStatusSync();o.isSubscribed=e===Se.SUBSCRIBED,e!==Se.NOT_DETERMINED&&(o.subscriberState=e)}catch(a){}return{domainKey:this.loadConfig.domainKey,env:i.get("env"),app:i.get("app"),domain:i.get("domain",v({},r)),user:i.get("user",o)}}get _currentLocation(){return Be._location}_registerPushSdkLifecycleCallbacks(e){this._pushSdkLifecycleCallbacks=e}_registerPermissionLifecycleCallbacks(e){this._permissionLifecycleCallbacks=e}_registerAppMessageLifecycleCallbacks(e){this._appMessageLifecycleCallbacks=e}_registerPromptLifecycleCallbacks(e){this.promptLifecycleCallbacks=e}_registerLegacyEventCallback(e,t,s){var i;null!=(i=this.legacyEventCallbacks)[e]||(i[e]={});const r=ce(8);this.legacyEventCallbacks[e][r]=s?(...s)=>{delete this.legacyEventCallbacks[e][r],t(...s)}:t}_registerOnLoadedCallback(e){null!=this._onLoadedCallbacks||(this._onLoadedCallbacks=[]),this._onLoadedCallbacks.push(e)}_setConfiguration(e){return N(this,null,(function*(){const t=function(e){const t=Ne();return void 0!==(null==t?void 0:t.iid)&&t.iid!==e.iid?Te.Err(new q(B.DUPLICATE_SDK_DETECTED)):e.isLoaded?Te.Err(new q(B.SDK_ALREADY_LOADED)):Te.Ok(!0)}(this);if(t.isErr())switch(t.getErr().code){case B.DUPLICATE_SDK_DETECTED:this._logger.warn("Unable to initialize PushSDK"),this._handleExit(t.getErr());break;case B.SDK_ALREADY_LOADED:this._logger.warn("SDK already loaded")}else if(this.isLoading)this._logger.warn("Initialization already started");else{this.isLoading=!0,Gt._setDomainKey(e.domainKey),this.sessionManager._start(),this._loadConfig=e,pe._loadConfig=e,function(e){return Object.keys(e).some((e=>!Oe.includes(e)))}(e)&&this.debugController._debugUnknownConfigurationKeys(e),this._domainKey=e.domainKey,this.domainConfigProvider=new $e(e.domainKey,this.settingsStore);try{yield this._load()}catch(s){const e=H(s);this._logger.error(e),this.eventManager._track(e)}}}))}_handleExit(e){return N(this,null,(function*(){var t,s;if(this._isExited)return void this._logger.debug("SDK has already exited.");let i="SDK Exited";e&&(i+=`: ${"string"==typeof e?e:e._compositeMessage}`),this._logger.warn(i),this._isLoaded=!0,this._isExited=!0,this._isEnabled=!1,null==(t=this.promptsController)||t._disable(),this.sessionManager._stop(),null==(s=this.pageViewProcessor)||s._stop();try{const[e,t]=yield Promise.all([this.userStore._getSubscriberStatus(),this.userStore._getIsInDeletedState()]);this.onPushSDKDidExitWithSubscriberStatus(e,t)}catch(r){this._logger.error(H(r))}}))}_load(){return N(this,null,(function*(){yield this._logInitializingState();const e=yield this.domainConfigProvider._get();if(e.isErr()){const t=e.getErr();return void(yield this._handleExit(t.code===B.DOMAIN_CONFIGURATION_LOAD_FAILED?t:new q(B.DOMAIN_CONFIGURATION_LOAD_FAILED,e.getErr())))}const t=e.unwrap();Gt._setDomain(t),pe._domainKey=this._domainKey,yield this._handleDomainConfigInitialLoadCompleted(t)}))}_logInitializingState(){return N(this,null,(function*(){this._logger.debug(`Initializing SDK v${ye._libraryVersion} (${ye._isProd?"P":"D"}-${this.iid})`),this._logger.info(`Loading key: ${this._domainKey}`)}))}_logUserInfo(){return N(this,null,(function*(){let e=yield this.userStore._getAnonymousId();e&&this._logger.info(`Anonymous ID: ${e}`);let t=yield this.userStore._getExternalId();t&&this._logger.info(`External ID: ${t}`)}))}_logCurrentSubscriptionStatus(){return N(this,null,(function*(){const[e,t]=yield Promise.all([this.userStore._getSubscriberStatus(),this.userStore._getSubscriberStatusDismissedExpiration()]);let s=`Current subscription status: ${be(e)}`;e===Se.DISMISSED&&null!==t&&(s+=` - expires in ${Math.round((t-(new Date).getTime())/1e3)}s`),this._logger.info(s)}))}_handleDomainConfigInitialLoadCompleted(e){return N(this,null,(function*(){if(!this._validateHostAvailability(e))return console.warn("%c[PushlySDK: WARNING]\n%cRefusing to run due to domain not present in allow list; This can be configured via the platform or by reaching out to your account manager.","font-size:1.25em;font-weight:600;font-style:italic;color:#4DBCA2;","font-size:1.25em;"),this.debugController._debugPromptNotShown(Ye.HOST_NOT_WHITELISTED),void(yield this._handleExit(new q(B.HOST_NOT_ALLOWED)));yield this._dispatchLegacyEventCallbacks(ne.LOADED),this.loadConfig.externalId&&(yield this.userStore._setExternalId(this.loadConfig.externalId));const t=new at(this.loadConfig,e);if(Fe(e))this._logger.debug("[Event Only Mode] Skipping notification & prompt services");else{this._logger.debug("Starting notification services"),this.notificationPermissionService=new Qe(e,t,this.eventManager,this.userStore,this),this.promptsController=new Ut(this.loadConfig,e,new dt(e.domain_key,this.settingsStore),this.notificationPermissionService,this.userStore,this.settingsStore,this.sessionManager,this.eventManager,this.debugController,this),e.flags.includes(ye._domainFeatIntegrationsECommFlag)||(this._heartbeatManager=new qt(this.eventManager,this.userStore,this.sessionStore,e.session));let i=null;const r=yield Qe._getWebPushSupport();if(r.isErr())i=r.getErr(),this.onPushSDKDidNotDetectWebPushSupport(i);else{this.onPushSDKDidDetectWebPushSupport(),yield this._logUserInfo(),yield this.userStore._synchronizeData(),yield this._logCurrentSubscriptionStatus();try{yield this.userStore._getAnonymousId().then((e=>{pe._anonymousId=e})).catch()}catch(s){}const e=yield this.notificationPermissionService._init();if(e.isErr()){const t=e.getErr();t instanceof q&&t._isExitException?(i=t,t.code===B.PUSH_WORKER_REGISTRATION_EXCEPTION&&this.debugController._debugPromptNotShown(Ye.SW_INSTALL_FAILED)):this._logger.warn(t.message)}}if(this.promptsController._setIsWebPushSupported(r),i)return void(yield this._handleExit(i));yield this.notificationPermissionService._synchronize()}this.pageViewProcessor=ct._init(e,this.eventManager,this.userStore,this.sessionManager.transient.store,{onPageChanged:()=>N(this,null,(function*(){yield t._getRegistration()}))}),function(e){return e.flags.includes(x._sdkHasForceDebugLogsEnabledFlag)}(e)&&(this._logger.debug("Forcing DEBUG logs"),this._logger.logLevel=C.VERBOSE),this._evaluateUserLocaleAndTimeZoneSettings().then(),yield this._setIsLoaded(e)}))}_evaluateUserLocaleAndTimeZoneSettings(){return N(this,null,(function*(){try{const[e,t,s,i]=yield Promise.all([this.userStore._getLocale(),Intl.DateTimeFormat().resolvedOptions().locale,this.userStore._getTimeZone(),Intl.DateTimeFormat().resolvedOptions().timeZone]),r=[];(!e||t&&e!==t)&&r.push(this.userStore._setLocale(t).then((()=>pe._getProfileLanguageEvent(t))).then((e=>this.eventManager._track(e)))),(!s||i&&s!==i)&&r.push(this.userStore._setTimeZone(i).then((()=>pe._getProfileTimeZoneEvent(i))).then((e=>this.eventManager._track(e)))),yield Promise.all(r).catch((e=>this._logger.error(e)))}catch(e){const t=H(e);this._logger.error(t)}}))}_getUserDetails(){return N(this,null,(function*(){var e,t,s;const i=yield this.userStore._getAnonymousId(),r=yield this.userStore._getSubscriberStatus(),n=yield this.userStore._getExternalId(),o=yield this._getBrowserPermissions();return{userId:i,subscriberStatus:r,externalId:n,browserPermission:null!=(e=null==o?void 0:o.permission)?e:null,endpoint:null!=(s=null==(t=null==o?void 0:o.token)?void 0:t.endpoint)?s:null}}))}_getBrowserPermissions(){return N(this,null,(function*(){return this.notificationPermissionService?yield this.notificationPermissionService._getCurrentPermissions():null}))}_toggleDebugPanel(e=!0){return N(this,null,(function*(){try{return e?this.debugController._showDebugPanel(yield this._getUserDetails()):this.debugController._hideDebugPanel()}catch(t){this.eventManager._track(H(t))}}))}_handleUserDeletionRequest(){return N(this,null,(function*(){(yield this.userStore._getIsInDeletedState())?this._logger.warn("User has already requested to be deleted."):(this._logger.verbose("Requesting user deletion"),yield this.eventManager._trackAsync(ae.USER_DELETION_REQUEST),yield this.userStore._setIsInDeletedState(!0),yield this._handleExit("User requested deletion."))}))}_validateHostAvailability(e){let t=!1,s=e.whitelist_domains;if(s)if(Array.isArray(s)&&0!==s.length){const e=this._currentLocation,i=["localhost","127.0.0.1"],r=`${e.protocol}//${e.hostname}`,n=`${e.protocol}//${e.host}`,o=e.href;t=[...s,...i].some((e=>{/^\*/.test(e)&&(e=`.${e}`);const t=new RegExp(`^(http[s]?://)?${e}$`,"i");return t.test(r)||t.test(n)||t.test(o)}))}else t=!0;else t=!0;return t}_setIsLoaded(e){return N(this,null,(function*(){var t,s;if(this._isLoaded)return;this.isLoading=!1,this._isLoaded=!0,this._executePostConfigActions().catch((e=>this._logger.error(e)));if(yield this._evaluateUserDeletedState())return;this.debugController._shouldShowDebugPanel()&&(yield this.debugController._showDebugPanel(yield this._getUserDetails())),(null==(t=this._onLoadedCallbacks)?void 0:t.length)&&(yield Promise.all(this._onLoadedCallbacks.map((e=>Promise.resolve(e()).catch((e=>{this._logger.error(e)})))))),this._logger.debug("SDK load completed"),this._isEnabled||this._logger.debug("SDK has been disabled");const i=yield this.userStore._getSubscriberStatus();this.pageViewProcessor?this.pageViewProcessor._start():this._logger.warn("Page View timer not available"),null==(s=this.promptsController)||s._startDisplayEvaluations(),this.onPushSDKDidFinishLoading(e,i)}))}_executePostConfigActions(){return N(this,null,(function*(){var e;const t=[...null!=(e=this._postConfigActionsQueue)?e:[]];if(this._postConfigActionsQueue=[],t.length)return Promise.all(t.map((e=>Promise.resolve(e()).catch((e=>this._logger.error(e)))))).then()}))}_evaluateUserDeletedState(){return N(this,null,(function*(){let e=yield this.userStore._getIsInDeletedState();return!e&&this._currentPageSearchParams.has(ye._udrUrlSearchParameter)?(yield this._handleUserDeletionRequest(),e=!0):e&&(yield this._handleExit("User is deleted.")),e}))}_dispatchLegacyEventCallbacks(e,...t){return N(this,null,(function*(){var s;const i=Object.values(null!=(s=this.legacyEventCallbacks[e])?s:{});i.length?(yield Promise.all(i.map((s=>Promise.resolve(s(...t)).catch((t=>{this._logger.error(`Error encountered in on_${e} handler:`,H(t).message)}))))),this._logger.verbose(`Completed ${i.length} on_${e} handler(s)`)):this._logger.verbose(`No on_${e} handlers found`)}))}_sendImpressionEvent(){(()=>N(this,null,(function*(){(yield this.userStore._getIsInDeletedState())||this.debugController._debug(ae.SDK_IMPRESSION)})))().then()}onPushSDKDidDetectWebPushSupport(){var e,t;null==(t=null==(e=this._pushSdkLifecycleCallbacks)?void 0:e.onPushSDKDidDetectWebPushSupport)||t.call(e),this._dispatchLegacyEventCallbacks(ne.WEB_PUSH_SUPPORTED)}onPushSDKDidNotDetectWebPushSupport(e){var t,s;null==(s=null==(t=this._pushSdkLifecycleCallbacks)?void 0:t.onPushSDKDidNotDetectWebPushSupport)||s.call(t),this._dispatchLegacyEventCallbacks(ne.WEB_PUSH_UNSUPPORTED,null==e?void 0:e.message,this.loadConfig,Be)}onPushSDKDidFinishLoading(e,t){var s,i;null==(i=null==(s=this._pushSdkLifecycleCallbacks)?void 0:s.onPushSDKDidFinishLoading)||i.call(s,e,t),this._dispatchLegacyEventCallbacks(ne.READY,this._legacyContext)}onPushSDKDidExitWithSubscriberStatus(e,t,s){var i,r;null==(r=null==(i=this._pushSdkLifecycleCallbacks)?void 0:i.onPushSDKDidExitWithSubscriberStatus)||r.call(i,e,t)}onPushSDKUserIsEligibleToPrompt(){return N(this,null,(function*(){var e,t;null==(t=null==(e=this.promptLifecycleCallbacks)?void 0:e.onPushSDKUserIsEligibleToPrompt)||t.call(e),this._dispatchLegacyEventCallbacks(ne.PROMPT_ELIGIBLE,{})}))}onPushSDKUserIsIneligibleToPrompt(){return N(this,null,(function*(){var e,t;null==(t=null==(e=this.promptLifecycleCallbacks)?void 0:e.onPushSDKUserIsIneligibleToPrompt)||t.call(e),this._dispatchLegacyEventCallbacks(ne.PROMPT_INELIGIBLE,{})}))}onPushSDKDidShowPrompt(e){return N(this,null,(function*(){var t,s;null==(s=null==(t=this.promptLifecycleCallbacks)?void 0:t.onPushSDKDidShowPrompt)||s.call(t,e);const i=yield this._getLegacyPromptEventPayload(e);this._dispatchLegacyEventCallbacks(ne.PROMPT_SHOWN,i)}))}onPushSDKFailedToShowPrompt(e,t){return N(this,null,(function*(){var s,i;null==(i=null==(s=this.promptLifecycleCallbacks)?void 0:s.onPushSDKFailedToShowPrompt)||i.call(s,e,t)}))}onPushSDKDidReceivePromptResponse(e,t){return N(this,null,(function*(){var s,i;null==(i=null==(s=this.promptLifecycleCallbacks)?void 0:s.onPushSDKDidReceivePromptResponse)||i.call(s,e,t);const r=yield this._getLegacyPromptEventPayload(e);t?this._dispatchLegacyEventCallbacks(ne.PROMPT_ALLOWED,r):this._dispatchLegacyEventCallbacks(ne.PROMPT_DISMISSED,r)}))}_getLegacyPromptEventPayload(e){return N(this,null,(function*(){return{prompt:{id:e},subscribed:yield this.userStore._getIsSubscribed()}}))}onPushSDKDidRequestNotificationPermissions(){return N(this,null,(function*(){var e,t;null==(t=null==(e=this._permissionLifecycleCallbacks)?void 0:e.onPushSDKDidRequestNotificationPermissions)||t.call(e),this._dispatchLegacyEventCallbacks(ne.PERMISSION_SHOWN,{}),this._dispatchLegacyEventCallbacks(ne.LEGACY_PERMISSION_SHOWN,{})}))}onPushSDKDidReceivePermissionResponse(e){return N(this,null,(function*(){var t,s;switch(null==(s=null==(t=this._permissionLifecycleCallbacks)?void 0:t.onPushSDKDidReceivePermissionResponse)||s.call(t,e),e){case je.GRANTED:this._dispatchLegacyEventCallbacks(ne.PERMISSION_ALLOWED,{}),this._dispatchLegacyEventCallbacks(ne.LEGACY_PERMISSION_ALLOWED,{});break;case je.DENIED:this._dispatchLegacyEventCallbacks(ne.PERMISSION_DENIED,{});break;case je.DISMISSED:this._dispatchLegacyEventCallbacks(ne.PERMISSION_DISMISSED,{})}}))}onPushSDKDidReceivePermissionResponseWithError(e,t){return N(this,null,(function*(){var s,i;null==(i=null==(s=this._permissionLifecycleCallbacks)?void 0:s.onPushSDKDidReceivePermissionResponseWithError)||i.call(s,e,t)}))}onPushSDKDidRegisterForRemoteNotificationsWithDeviceToken(e){return N(this,null,(function*(){var t,s;null==(s=null==(t=this._permissionLifecycleCallbacks)?void 0:t.onPushSDKDidRegisterForRemoteNotificationsWithDeviceToken)||s.call(t,e)}))}onPushSDKDidFailToRegisterForRemoteNotificationsWithError(e){return N(this,null,(function*(){var t,s;null==(s=null==(t=this._permissionLifecycleCallbacks)?void 0:t.onPushSDKDidFailToRegisterForRemoteNotificationsWithError)||s.call(t,e)}))}onPushSDKDidReceivePermissionStatusChange(e){return N(this,null,(function*(){var t,s,i,r,n;switch(null==(t=this._heartbeatManager)||t.onSubscriptionChanged(e==je.GRANTED),null==(i=null==(s=this._permissionLifecycleCallbacks)?void 0:s.onPushSDKDidReceivePermissionStatusChange)||i.call(s,e),e){case je.GRANTED:case je.DENIED:null==(r=this.promptsController)||r._disable();break;case je.DISMISSED:null==(n=this.promptsController)||n._enable()}}))}}const Qt=()=>new q(B.STORAGE_NOT_AVAILABLE,null," - IndexedDB"),zt=()=>new q(B.IDB_INVALID_STORE_NAME),Xt=()=>new q(B.IDB_BLOCKED);class Zt extends Kt{constructor(e,t=ie._getInstance("IdbStore")){super($t.IDB,e,t)}get _isAvailable(){return We._getIsEnvBaseSupported()[0]&&!!this._storeName&&!!this._indexedDB}get _indexedDB(){return We._scope.indexedDB}get _isSafari(){return We._isSafari}_getData(e){return N(this,null,(function*(){return this._executeTransaction("read",e)}))}_setData(e,t){return N(this,null,(function*(){return this._executeTransaction("write",[e,t],(()=>{e!==x._pnStorageTypeLuaKey&&this._updateLua()}))}))}_removeData(e){return N(this,null,(function*(){return this._executeTransaction("delete",e)}))}_openDatabase(){return N(this,null,(function*(){return new Promise((e=>{if(!this._indexedDB)return void e(Te.Err(Qt()));if(!this._storeName)return void e(Te.Err(zt()));const t=this._indexedDB.open("pn_store",1);t.onerror=s=>{e(Te.Err(t.error||new Error(s)))},t.onsuccess=t=>{this._handleOnOpenSuccess(t.target.result,(t=>{e(Te.Ok(t))}))},t.onupgradeneeded=e=>{this._handleOnUpgradeNeeded(e.target.result)},t.onblocked=()=>{e(Te.Err(Xt()))}}))}))}_handleOnOpenSuccess(e,t){e.onversionchange=()=>{this._handleOnVersionChange(e)},this._isSafari&&this._selfHeal(e),t(e)}_handleOnUpgradeNeeded(e){e.objectStoreNames.contains(xt.sub)||e.createObjectStore(xt.sub,{keyPath:"k"}),e.objectStoreNames.contains(xt.sdk)||e.createObjectStore(xt.sdk,{keyPath:"k"}),e.objectStoreNames.contains(xt.WORKER)||e.createObjectStore(xt.WORKER,{keyPath:"k"})}_handleOnVersionChange(e){e.close()}_executeTransaction(e,t,s){return N(this,null,(function*(){const i=yield this._openDatabase();if(i.isErr())return i;const r=i.unwrap();return new Promise((i=>{const n=this._storeName,o="read"===e?"readonly":"readwrite",a=r.transaction(n,o),l=(new Date).getTime(),u=a.objectStore(n),c="write"===e?t[0]:t;let d;switch(e){case"read":d=u.get(c);break;case"write":d=u.put({k:c,value:t[1],ts:c===x._pnStorageTypeLuaKey?t[1]:l});break;case"delete":d=u.delete(c)}a.onabort=e=>{i(Te.Err(d.error||new Error(e)))},a.oncomplete=()=>{var r,n,o,a;let l;switch(e){case"read":l=Te.Ok({value:null!=(n=null==(r=d.result)?void 0:r.value)?n:null,ts:null!=(a=null==(o=d.result)?void 0:o.ts)?a:0,sourceType:this._storageType});break;case"write":l=Te.Ok(t[1]);break;case"delete":l=Te.Ok(null)}i(l),null==s||s(l)}}))}))}_updateLua(){this._executeTransaction("write",[x._pnStorageTypeLuaKey,(new Date).getTime()]).then((e=>{var t;e.isErr()&&this._logger.verbose(`Unable to set lua for ${this._storeName}`,null==(t=e.getErr())?void 0:t.message)}))}_selfHeal(e){Object.keys(xt).every((t=>e.objectStoreNames.contains(t)))||this._handleOnUpgradeNeeded(e)}}const Jt=()=>new q(B.STORAGE_NS_REQUIRED,null,"Mem");class es extends Kt{constructor(e,t=ie._getInstance("MemStore")){super($t.MEM,e,t),P(this,"_db"),this._db={}}get _isAvailable(){return null!==this._storeName}_getData(e){return N(this,null,(function*(){var t,s,i;if(!this._storeName)return Te.Err(Jt());const r=null==(t=this._db[this._storeName])?void 0:t[e];return Te.Ok({value:null!=(s=null==r?void 0:r.value)?s:null,ts:null!=(i=null==r?void 0:r.ts)?i:0,sourceType:this._storageType})}))}_setData(e,t){return N(this,null,(function*(){var s,i;return this._storeName?(null!=(s=this._db)[i=this._storeName]||(s[i]={}),this._db[this._storeName][e]={value:t,ts:(new Date).getTime()},Te.Ok(t)):Te.Err(Jt())}))}_removeData(e){return N(this,null,(function*(){var t;return this._storeName?(void 0!==(null==(t=this._db[this._storeName])?void 0:t[e])&&delete this._db[this._storeName][e],Te.Ok(null)):Te.Err(Jt())}))}}const ts=()=>new q(B.STORAGE_NOT_AVAILABLE,null," - Session"),ss=e=>new q(B.STORAGE_KEY_EMPTY,null,e),is=e=>new q(B.STORAGE_FAILED_TO_OPEN,e," - Session");class rs extends Kt{constructor(e,t=ie._getInstance("SessionStore")){super($t.SESSION,e,t)}get _isAvailable(){return!!this._storeName&&!this._isInWorkerGlobalScope&&this.storageAvailable()}get _store(){return Be._scope.sessionStorage}_getData(e){return N(this,null,(function*(){if(!this._isAvailable)return Te.Err(ts());const t=this._openStore();if(t.isErr())return t;const s=t.unwrap()[e]||null;return null==s&&e!==x._pnStorageTypeLuaKey?Te.Err(ss(e)):Te.Ok(s)}))}_setData(e,t){return N(this,null,(function*(){if(!this._isAvailable)return Te.Err(ts());const s=this._openStore();if(s.isErr())return s;const i=s.unwrap();return i[e]=e===x._pnStorageTypeLuaKey?t:{value:t,ts:(new Date).getTime()},this._persist(i),Te.Ok(t)}))}_removeData(e){return N(this,null,(function*(){const t=this._openStore();if(t.isErr())return t;const s=t.unwrap();return s[this._storeName]&&e in s[this._storeName]&&(delete s[this._storeName][e],this._persist(s)),Te.Ok(null)}))}_openStore(){var e;let t={};if(!this._storeName)return Te.Err(is(new Error("Store cannot be accessed without a store name set")));try{const s=null!=(e=this._store.getItem(this._storeName))?e:"{}",i=JSON.parse(s);i&&"object"==typeof i&&!Array.isArray(i)&&(t=i)}catch(s){const e=is(H(s));return this._logger.warn(e.message),Te.Err(e)}return Te.Ok(t)}_persist(e){try{e&&"object"==typeof e&&!Array.isArray(e)&&(e[x._pnStorageTypeLuaKey]=(new Date).getTime()),this._store.setItem(this._storeName,JSON.stringify(e))}catch(t){this._logger.error(H(t))}}storageAvailable(){let e;try{e=this._store;const t=x._pnSessionStorageKey+"_test_";return e.setItem(t,t),e.removeItem(t),!0}catch(t){return t instanceof DOMException&&"QuotaExceededError"===t.name&&!!e&&0!==e.length}}}const ns=e=>new Error(`No available stores found for ${e.join(", ")}`),os=e=>new q(B.STORAGE_KEY_EMPTY,null,e);class as{constructor(e,t,s=ie._getInstance("StorageManager")){P(this,"_storeName"),P(this,"_logger"),P(this,"_stores"),P(this,"_preferredStores"),this._storeName=e,this._preferredStores=t,this._logger=s,this._stores=Object.fromEntries(this._preferredStores.map((t=>{switch(t){case $t.IDB:return[$t.IDB,new Zt(e)];case $t.COOKIE:return[$t.COOKIE,new Gt(e)];case $t.LEGACY_COOKIE:return[$t.LEGACY_COOKIE,new Gt(null)];case $t.MEM:return[$t.MEM,new es(e)];case $t.SESSION:return[$t.SESSION,new rs(e)]}})))}_getAvailableStores(e){const t=null!=e?e:this._preferredStores,s=t.filter((e=>!!this._stores[e]&&this._stores[e]._isAvailable));return 0===s.length?Te.Err(ns(t)):Te.Ok(s.map((e=>this._stores[e])))}_getData(e,t){return N(this,null,(function*(){const s=yield this._getTimestampedData(e,t);return s.isErr()?s:Te.Ok(s.unwrap().value)}))}_getDataSync(e,t){const s=this._getTimestampedDataSync(e,t);return s.isErr()?s:Te.Ok(s.unwrap().value)}_getTimestampedData(e,t){return N(this,null,(function*(){const s=yield this._mGetTimestampedData(e,t),i=Object.values(s).filter((e=>e.isOk()&&null!==e.unwrap().value)).map((e=>e.unwrap()));return i.length?(i.length>1&&i.sort(((e,t)=>t.ts-e.ts)),Te.Ok(i[0])):Te.Err(os(e))}))}_getTimestampedDataSync(e,t){const s=this._mGetTimestampedDataSync(e,t),i=Object.values(s).filter((e=>e.isOk()&&null!==e.unwrap().value)).map((e=>e.unwrap()));return i.length?Te.Ok(i[0]):Te.Err(os(e))}_mGetTimestampedData(e,t){return N(this,null,(function*(){var s;const i={},r=null!=(s=null==t?void 0:t.preferredStores)?s:this._preferredStores;return(yield Promise.all(r.map((t=>{var s;return(null==(s=this._stores[t])?void 0:s._isAvailable)?this._stores[t]._getData(e).then((e=>[t,e])):[t,Te.Ok({value:null,ts:0})]})))).forEach((([e,t])=>{i[e]=t})),i}))}_mGetTimestampedDataSync(e,t){var s;const i={};return(null!=(s=null==t?void 0:t.preferredStores)?s:this._preferredStores).filter((e=>this._stores[e]&&"_getDataSync"in this._stores[e])).map((e=>this._stores[e])).map((t=>(null==t?void 0:t._isAvailable)?[t._storageType,t._getDataSync(e)]:[t._storageType,Te.Ok({value:null,ts:0})])).forEach((([e,t])=>{i[e]=t})),i}_setData(e,t,s){return N(this,null,(function*(){var i;const r=null!=(i=null==s?void 0:s.preferredStores)?i:this._preferredStores,n=yield Promise.all(r.map((s=>{var i;return(null==(i=this._stores[s])?void 0:i._isAvailable)?this._stores[s]._setData(e,t).then((t=>(t.isErr()&&this._logger.warn(`Unable to set [${s}:error] ${e}`,t.getErr().message),t))):Promise.resolve(null).then((t=>(this._logger.warn(`Unable to set [${s}:not_available] ${e}`),t)))})));return this._parseSetterResponse(n,r,t)}))}_setDataSync(e,t,s){var i;const r=null!=(i=null==s?void 0:s.preferredStores)?i:this._preferredStores,n=r.filter((e=>this._stores[e]&&"_getDataSync"in this._stores[e])).map((e=>this._stores[e])).map((s=>{if(null==s?void 0:s._isAvailable){const i=s._setDataSync(e,t);return i.isErr()&&this._logger.warn(`Unable to set [${s}:error] ${e}`,i.getErr().message),i}return this._logger.warn(`Unable to set [${s}:not_available] ${e}`),null}));return this._parseSetterResponse(n,r,t)}_removeData(e,t){return N(this,null,(function*(){var s;const i=null!=(s=null==t?void 0:t.preferredStores)?s:this._preferredStores,r=yield Promise.all(i.map((t=>{var s;return(null==(s=this._stores[t])?void 0:s._isAvailable)?this._stores[t]._removeData(e):null})));return this._parseSetterResponse(r,i,null)}))}_parseSetterResponse(e,t,s){if(e.every((e=>null===e||e.isErr()))){const s=e.find((e=>null==e?void 0:e.getErr()));return s?(st._dispatch(st.EventType.ERROR,s.getErr()),this._logger.warn(s.getErr().message),s):Te.Err(ns(t))}return e.forEach((e=>{(null==e?void 0:e.isErr())&&st._dispatch(st.EventType.ERROR,e.getErr())})),Te.Ok(s)}}var ls=(e=>(e.anonymousId="id",e.locale="ll",e.timeZone="tz",e.token="t",e.externalId="xid",e.isSubscribed="s",e.subscriberStatus="ss",e.DISMISSED_STATUS_EXPIRATION="dse",e.isInDeletedState="udr",e.LAST_PAGE_VIEWED="lpgv",e.IS_USER_IN_SOFT_UNSUBSCRIBE_STATE="sunsub",e))(ls||{});const us={id:"pushly.user_puuid",t:"_pntx",xid:"_pnxd",ss:"_pnss",udr:"_pnudr",dse:"_pnpdm"};var cs=(e=>(e.logLevel="log",e.eventsCache="ev",e.domainConfig="d",e.PROMPTS_CACHE="p",e.PROMPTS_OCCURRENCES_MAP="pocm",e.PROMPTS_LAST_VIEWED="plv",e))(cs||{}),ds=(e=>(e.SESSION_START="sxst",e.SESSION_RUNTIME="sxrt",e.SESSION_PAGE_VIEWS="sxpv",e.SESSION_PAGE_VIEW_START="sxpvs",e.SESSION_READY_PROMPT="sxrp",e.SESSION_LAST_ACTIVITY="ula",e.SESSION_HEARTBEAT_SESSION="hbs",e))(ds||{});function hs(e,t,s){const i=Array.from(e.entries()).reduce(t,null!=s?s:[]);return void 0!==s&&typeof e!=typeof s?i:new Map(i)}const _s=[$t.IDB,$t.MEM],gs=[$t.SESSION,$t.MEM];class ps extends as{constructor(e){super(xt.sdk,[$t.MEM,$t.IDB,$t.SESSION],null!=e?e:ie._getInstance("SettingsStore"))}_getDomainConfig(){return N(this,null,(function*(){return(yield this._getTimestampedData(cs.domainConfig,{preferredStores:_s})).unwrapOrNull()}))}_setDomainConfig(e){return N(this,null,(function*(){return(yield this._setData(cs.domainConfig,e,{preferredStores:_s})).unwrapOrNull()}))}_getCachedEvents(){return N(this,null,(function*(){return(yield this._getData(cs.eventsCache,{preferredStores:_s})).unwrapOr([])}))}_setCachedEvents(e){return N(this,null,(function*(){return(yield this._setData(cs.eventsCache,e,{preferredStores:_s})).unwrapOr([])}))}_getCachedPrompts(){return N(this,null,(function*(){return(yield this._getTimestampedData(cs.PROMPTS_CACHE,{preferredStores:gs})).unwrapOrNull()}))}_setCachedPrompts(e){return N(this,null,(function*(){return(yield this._setData(cs.PROMPTS_CACHE,e,{preferredStores:gs})).unwrapOrNull()}))}_getViewedPromptOccurrencesCount(){return N(this,null,(function*(){return hs(yield this._getViewedPromptOccurrencesMap(),((e,[,t])=>e+t.length),0)}))}_getViewedPromptOccurrencesMap(){return N(this,null,(function*(){return(yield this._getData(cs.PROMPTS_OCCURRENCES_MAP,{preferredStores:_s})).unwrapOr(new Map)}))}_dropViewedPromptOccurrencesNotInInterval(e){return N(this,null,(function*(){const t=hs(yield this._getViewedPromptOccurrencesMap(),((t,[s,i])=>{const r=i.filter((t=>Math.abs(xe(t))<=e));return r.length>0&&t.push([s,r]),t}));yield this._setData(cs.PROMPTS_OCCURRENCES_MAP,t)}))}_incrementViewedOccurrencesForPromptId(e){return N(this,null,(function*(){var t;const s=yield this._getViewedPromptOccurrencesMap();s.set(e,[(new Date).getTime(),...null!=(t=s.get(e))?t:[]]),yield this._setData(cs.PROMPTS_OCCURRENCES_MAP,s)}))}_getLastViewedPromptId(){return N(this,null,(function*(){return(yield this._getData(cs.PROMPTS_LAST_VIEWED,{preferredStores:_s})).unwrapOrNull()}))}_setLastViewedPromptId(e){return N(this,null,(function*(){return(yield this._setData(cs.PROMPTS_LAST_VIEWED,e,{preferredStores:_s})).unwrapOrNull()}))}_setLastMatchedPromptId(e){return N(this,null,(function*(){return(null===e?yield this._removeData(ds.SESSION_READY_PROMPT,{preferredStores:gs}):yield this._setData(ds.SESSION_READY_PROMPT,e,{preferredStores:gs})).unwrapOrNull()}))}_getLastMatchedPromptId(){return N(this,null,(function*(){return(yield this._getData(ds.SESSION_READY_PROMPT,{preferredStores:gs})).unwrapOrNull()}))}}const ms=[$t.COOKIE,$t.IDB,$t.MEM],Ss=[$t.IDB,$t.MEM],Es=[$t.SESSION,$t.MEM];class fs extends as{constructor(e,t=ie._getInstance("UserStore")){super(xt.sub,[$t.MEM,$t.IDB,$t.COOKIE,$t.SESSION],t),P(this,"_legacyStorage"),this._legacyStorage=e}_synchronizeData(){return N(this,null,(function*(){yield(()=>N(this,null,(function*(){const e=this._getAvailableStores([$t.IDB,$t.COOKIE]).unwrapOr([]);if(e.length<=1)return void this._logger.verbose("[Sync] No available stores to synchronize");const t=yield Promise.all(e.map((e=>e._getLastUpdatedAt().then((t=>({store:e,lua:t}))))));if(new Set(t.map((e=>e.lua.getTime()))).size<=1)return void this._logger.verbose("[Sync] Stores are already synchronized");t.length>1&&t.sort(((e,t)=>e.lua.getTime()t.lua.getTime()?-1:0));const[s,...i]=t;this._logger.verbose(`[Sync] Starting synchronization from ${s.store._storageType}`);const r=[ls.anonymousId,ls.subscriberStatus,ls.isInDeletedState,ls.DISMISSED_STATUS_EXPIRATION];yield Promise.all(r.map((e=>s.store._getData(e).then((t=>N(this,null,(function*(){if(t.isErr())return void(t.getErr().message!==os(e).message&&this._logger.verbose(`[Sync] Unable to read ${e} value from ${s.store._storageType}. ${t.getErr().message}`));let r=null===t.unwrap().value?i.map((t=>t.store._removeData(e).then((s=>[t.store._storageType,e,s])))):i.map((s=>s.store._setData(e,t.unwrap().value).then((t=>[s.store._storageType,e,t]))));yield Promise.all(r).then((e=>e.forEach((([e,t,s])=>{s.isErr()?this._logger.verbose(`[Sync] Unable to synchronize ${t} value to ${e}. ${s.getErr().message}`):this._logger.verbose(`[Sync] Synchronized ${t} value to ${e}`)}))))}))))))),yield Promise.all(i.map((e=>e.store._setLastUpdatedAt(s.lua).then((t=>{t.isErr()&&this._logger.verbose(`[Sync] Unable to synchronize lua value for ${e.store._storageType}. ${t.getErr().message}`)}))))),this._logger.verbose(`[Sync] Completed synchronization from ${s.store._storageType}`)})))(),yield this._evaluateSubscriberDismissedState()}))}_evaluateSubscriberDismissedState(){return N(this,null,(function*(){const e=yield this._getSubscriberStatus(),t=yield this._getSubscriberStatusDismissedExpiration();e===Se.DISMISSED&&(null===t||(new Date).getTime()>=t)?(this._logger.info("Removing subscriber dismissed state"),yield Promise.all([this._removeData(ls.DISMISSED_STATUS_EXPIRATION),this._setSubscriberStatus(Se.NOT_DETERMINED)])):e!==Se.DISMISSED&&null!==t&&(this._logger.verbose("Removing subscriber dismissed expiration key"),yield this._removeData(ls.DISMISSED_STATUS_EXPIRATION))}))}_getAnonymousId(){return N(this,null,(function*(){let e=(yield this._getData(ls.anonymousId,{preferredStores:ms})).unwrapOrNull();if(!e){const t=this._legacyStorage._getAnonymousId(),s=yield this._setData(ls.anonymousId,null!=t?t:ce(),{preferredStores:ms});s.isOk()&&(e=s.unwrap(),this._removeLegacyKey(us[ls.anonymousId]))}return e}))}_getAnonymousIdSync(){let e=this._getDataSync(ls.anonymousId,{preferredStores:[$t.COOKIE]}).unwrapOrNull();if(!e){const t=this._legacyStorage._getAnonymousId(),s=this._setDataSync(ls.anonymousId,null!=t?t:ce(),{preferredStores:[$t.COOKIE]});s.isOk()&&(e=s.unwrap())}return e}_getLocale(){return N(this,null,(function*(){return(yield this._getData(ls.locale,{preferredStores:Ss})).unwrapOrNull()}))}_setLocale(e){return N(this,null,(function*(){return(yield this._setData(ls.locale,e,{preferredStores:Ss})).unwrapOrNull()}))}_getTimeZone(){return N(this,null,(function*(){return(yield this._getData(ls.timeZone,{preferredStores:Ss})).unwrapOrNull()}))}_setTimeZone(e){return N(this,null,(function*(){return(yield this._setData(ls.timeZone,e,{preferredStores:Ss})).unwrapOrNull()}))}_getExternalId(){return N(this,null,(function*(){let e=(yield this._getData(ls.externalId,{preferredStores:Ss})).unwrapOrNull();if(!e){const t=this._legacyStorage._getExternalId();if(t){(yield this._setData(ls.externalId,t,{preferredStores:Ss})).isOk()&&(e=t,this._removeLegacyKey(us[ls.externalId]))}}return e}))}_getExternalIdSync(){let e=this._getDataSync(ls.externalId,{preferredStores:[$t.COOKIE]}).unwrapOrNull();if(!e){const t=this._legacyStorage._getExternalId();if(t){this._setDataSync(ls.externalId,t,{preferredStores:[$t.COOKIE]}).isOk()&&(e=t)}}return e}_setExternalId(e){return N(this,null,(function*(){return(yield this._setData(ls.externalId,e,{preferredStores:Ss})).isOk()}))}_removeExternalId(){return N(this,null,(function*(){return(yield this._removeData(ls.externalId,{preferredStores:Ss})).isOk()}))}_getIsSubscribed(){return N(this,null,(function*(){return(yield this._getSubscriberStatus())===Se.SUBSCRIBED}))}_getSubscriberStatus(){return N(this,null,(function*(){const e=yield this._getData(ls.subscriberStatus,{preferredStores:ms});let t=Se.NOT_DETERMINED;const s=e.unwrapOrNull();if(null===s){const e=this._legacyStorage._getSubscriberStatus(),s=yield this._setData(ls.subscriberStatus,Ee[null!=e?e:t],{preferredStores:ms});s.isOk()&&(t=fe(s.unwrap())),e&&this._removeLegacyKey(us[ls.subscriberStatus])}else t=fe(s);return t}))}_getIsUserInSoftUnsubscribedState(){return N(this,null,(function*(){return!!(yield this._getData(ls.IS_USER_IN_SOFT_UNSUBSCRIBE_STATE,{preferredStores:ms})).unwrapOrNull()}))}_setIsUserInSoftUnsubscribedState(){return N(this,null,(function*(){yield this._setData(ls.IS_USER_IN_SOFT_UNSUBSCRIBE_STATE,1,{preferredStores:ms})}))}_unsetIsUserInSoftUnsubscribedState(){return N(this,null,(function*(){yield this._removeData(ls.IS_USER_IN_SOFT_UNSUBSCRIBE_STATE,{preferredStores:ms})}))}_getSubscriberStatusSync(){const e=this._getDataSync(ls.subscriberStatus,{preferredStores:[$t.COOKIE]});let t=Se.NOT_DETERMINED;const s=e.unwrapOrNull();if(null===s){const e=this._legacyStorage._getSubscriberStatus(),s=this._setDataSync(ls.subscriberStatus,Ee[null!=e?e:t],{preferredStores:[$t.COOKIE]});s.isOk()&&(t=fe(s.unwrap()))}else t=fe(s);return t}_setSubscriberStatus(e){return N(this,null,(function*(){return(yield this._setData(ls.subscriberStatus,Ee[e],{preferredStores:ms})).isOk()}))}_setSubscriberStatusDismissed(e){return N(this,null,(function*(){if(!(yield this._setSubscriberStatus(Se.DISMISSED)))return this._logger.warn("Unable to set subscriber dismissed status. Skipping dismissed expiration."),!1;const t=yield this._setData(ls.DISMISSED_STATUS_EXPIRATION,(new Date).getTime()+1e3*e,{preferredStores:ms});return t.isOk()||this._logger.warn("Unable to set subscriber dismissed expiration.",t.getErr()),t.isOk()}))}_getSubscriberStatusDismissedExpiration(){return N(this,null,(function*(){let e=(yield this._getData(ls.DISMISSED_STATUS_EXPIRATION,{preferredStores:ms})).unwrapOrNull();if(!e){const t=yield this._legacyStorage._getDismissedStatusExpiration();t&&(e=t,yield this._setData(ls.DISMISSED_STATUS_EXPIRATION,t,{preferredStores:ms}))}return e}))}_getIsInDeletedState(){return N(this,null,(function*(){let e=!1;const t=(yield this._getData(ls.isInDeletedState,{preferredStores:ms})).unwrapOrNull();if(null!==t)e=!!t;else{const t=this._legacyStorage._getIsInDeletedState(),s=(null!=t?t:e)?1:0,i=yield this._setData(ls.isInDeletedState,s,{preferredStores:ms});i.isOk()&&(e=!!i.unwrap(),this._removeLegacyKey(us[ls.isInDeletedState]))}return e}))}_setIsInDeletedState(e){return N(this,null,(function*(){return(yield this._setData(ls.isInDeletedState,e?1:0,{preferredStores:ms})).isOk()}))}_getLastPageViewed(){return N(this,null,(function*(){return(yield this._getData(ls.LAST_PAGE_VIEWED,{preferredStores:Es})).unwrapOrNull()}))}_setLastPageViewed(e){return N(this,null,(function*(){return(yield this._setData(ls.LAST_PAGE_VIEWED,e,{preferredStores:Es})).isOk()}))}_removeLegacyKey(e){this._logger.debug(`!! Legacy key removal DISABLED !! key: ${e}`)}}class bs extends as{constructor(e){super(null,[$t.LEGACY_COOKIE],null!=e?e:ie._getInstance("LegacyStoreManager"))}_getAnonymousId(){return this._getDataSync(us[ls.anonymousId]).unwrapOrNull()}_getExternalId(){return this._getDataSync(us[ls.externalId]).unwrapOrNull()}_getSubscriberStatus(){let e=null;const t=this._getDataSync(us[ls.subscriberStatus]).unwrapOrNull();return t&&(e=fe(t)),e}_getIsInDeletedState(){return this._getDataSync(us[ls.isInDeletedState]).unwrapOrNull()}_getDismissedStatusExpiration(){return N(this,null,(function*(){return(yield this._getData(us[ls.DISMISSED_STATUS_EXPIRATION])).unwrapOrNull()}))}}class vs{constructor(e,t){P(this,"_userProfileMod"),this.settingsStore=e,this.userStore=t}get _isBaseEnvSupported(){return Be._getIsEnvBaseSupported()[0]}setUserProfileModule(e){this._userProfileMod=e}_canSend(){return N(this,null,(function*(){return this.userStore._getIsInDeletedState().then((e=>!e))}))}_getAnonymousId(){return N(this,null,(function*(){return this.userStore._getAnonymousId()}))}_getIsSubscribed(){return N(this,null,(function*(){return this.userStore._getIsSubscribed()}))}_getToken(){return N(this,null,(function*(){return this._isBaseEnvSupported&&this._userProfileMod?this._userProfileMod.getToken():null}))}_getDomainId(){return N(this,null,(function*(){var e,t,s,i;let r=null!=(t=null==(e=ye._injectedDomainConfig)?void 0:e.id)?t:null;if(!r){const e=yield this.settingsStore._getDomainConfig();r=null!=(i=null==(s=null==e?void 0:e.value)?void 0:s.id)?i:null}return r}))}_getCachedEvents(){return N(this,null,(function*(){return this.settingsStore._getCachedEvents()}))}_setCachedEvents(e){return N(this,null,(function*(){return this.settingsStore._setCachedEvents(e)}))}}class ys{constructor(e){P(this,"timer"),this.store=e,this.timer=new lt("session_timer",this._handleSessionTimerDidAdvance.bind(this),1,{autoStart:!1})}_start(){this.timer.isStarted?this.timer._unpause():this.timer._start()}_stop(){this.timer._pause()}_handleSessionTimerDidAdvance(){return N(this,null,(function*(){const e=yield this.store._getSessionRuntimeSeconds();yield this.store._setSessionRuntimeSeconds(e+1)}))}}class Is{constructor(e){P(this,"transient"),this.transient=new ys(e)}_start(){this.transient._start()}_stop(){this.transient._stop()}}class Ps extends as{constructor(e){super(xt.sdk,[$t.SESSION,$t.MEM],null!=e?e:ie._getInstance("SessionStore"))}_setSessionStart(e){return N(this,null,(function*(){return(yield this._setData(ds.SESSION_START,e)).unwrapOrNull()}))}_getSessionStart(){return N(this,null,(function*(){const e=(yield this._getData(ds.SESSION_START)).unwrapOrNull();return e?new Date(e):null}))}_getCurrentPageViewStart(){return N(this,null,(function*(){const e=(yield this._getData(ds.SESSION_PAGE_VIEW_START)).unwrapOrNull();return e?new Date(e):null}))}_getSessionPageViewCount(){return N(this,null,(function*(){return(yield this._getData(ds.SESSION_PAGE_VIEWS)).unwrapOr(0)}))}_getSessionRuntimeSeconds(){return N(this,null,(function*(){return(yield this._getData(ds.SESSION_RUNTIME)).unwrapOr(0)}))}_setSessionRuntimeSeconds(e){return N(this,null,(function*(){return(yield this._setData(ds.SESSION_RUNTIME,e)).unwrapOrNull()}))}_incrementSessionPageViewCount(){return N(this,null,(function*(){const e=yield this._getSessionPageViewCount();yield Promise.all([this._setData(ds.SESSION_PAGE_VIEWS,e+1),this._setData(ds.SESSION_PAGE_VIEW_START,(new Date).getTime())])}))}_setLastActivity(e){return N(this,null,(function*(){return(yield this._setData(ds.SESSION_LAST_ACTIVITY,e.getTime())).isOk()}))}_getLastActivity(){return N(this,null,(function*(){const e=(yield this._getData(ds.SESSION_LAST_ACTIVITY)).unwrapOrNull();return e?new Date(e):null}))}_setHeartbeatSessionDate(e){return N(this,null,(function*(){return(yield this._setData(ds.SESSION_HEARTBEAT_SESSION,e.getTime())).isOk()}))}_getHeartbeatSessionDate(){return N(this,null,(function*(){const e=(yield this._getData(ds.SESSION_HEARTBEAT_SESSION)).unwrapOrNull();return e?new Date(e):null}))}}class Ds{constructor(e,t){P(this,"debugPanelElement"),this.settingsStore=e,this.eventManager=t}_getIsEventsEnabled(){return N(this,null,(function*(){let e=[];const t=ye._injectedDomainConfig;if(t)e=t.flags;else{const t=yield this.settingsStore._getDomainConfig();(null==t?void 0:t.value.flags)&&(e=t.value.flags)}return e.includes(ye._sdkDebugEventsEnabledFlag)}))}_shouldShowDebugPanel(){return this._currLocation&&/(^|[?&#])(push(ly)?_debug(73485)?)=1(?=[&#]|$)/i.test(this._currLocation.href)}get _currLocation(){return We._location}get _document(){return We._document}get _clipboard(){return We._navigator.clipboard}get _userAgent(){return We._navigator.userAgent}_hideDebugPanel(){return N(this,null,(function*(){if(this.debugPanelElement)try{this._document.body.removeChild(this.debugPanelElement)}catch(e){}}))}_showDebugPanel(e){return N(this,arguments,(function*({userId:e,subscriberStatus:t,endpoint:s,externalId:i,browserPermission:r}){var n,o,a,l;const u=this._document,c=`Pushly ID: ${e}, Subscriber State: ${t}, External ID: ${i}, Endpoint: ${s}, Browser Permissions: ${r}, UserAgent: ${this._userAgent}`.trim(),d=`pushly_debug_handle_${ce(12)}`,h=`pushly_debug_close_${ce(12)}`,_=`pushly_debug_copy_${ce(12)}`,g=`pushly_debug_shadow_${ce(12)}`,p=null!=(n=this.debugPanelElement)?n:u.createElement("div");var m;p.classList.add("sw-user-debug-drawer-wrapper"),p.innerHTML=`\n\n
\n
\n \n Push SDK\n \n
\n
\n
\n Pushly ID\n
\n \n\n
\n External ID\n
\n \n\n
\n Subscription State\n
\n \n ${m=t,m.charAt(0).toUpperCase()+m.slice(1)}\n \n\n
\n \n \n
\n
\n
\n`.trim().replace(/(<[^>]*?>)|[\r\n]+|[\s]{2,}/g,"$1").trim();const S=()=>N(this,null,(function*(){p.classList.contains("open")?p.classList.remove("open"):p.classList.add("open")})),E=null==(o=p.getElementsByClassName("sw-user-debug-drawer-handle"))?void 0:o[0];E&&E.id===d&&E.addEventListener("click",S);const f=null==(a=p.getElementsByClassName("close"))?void 0:a[0];f&&f.id===h&&f.addEventListener("click",S);const b=()=>{let e=!1;try{this._clipboard.writeText(c),e=!0}catch(t){try{const t=u.createElement("input");u.body.appendChild(t),t.id=g,t.classList.add("sw-user-debug-shadow"),t.type="textarea",t.defaultValue=c,t.classList.add("copying"),t.select(),e=u.execCommand("copy"),t.classList.remove("copying")}catch(s){}}e&&(v.classList.add("success"),v.innerHTML="Copied ".trim(),setTimeout((()=>{v.classList.remove("success"),v.innerHTML="Copy"}),1e3))},v=null==(l=p.getElementsByClassName("copy"))?void 0:l[0];v&&v.id===_&&v.addEventListener("click",b),this.debugPanelElement||(u.body.appendChild(p),this.debugPanelElement=p)}))}_debug(e,t={},s=!1){(()=>N(this,null,(function*(){le(e)&&(s||(yield this._getIsEventsEnabled()))&&this.eventManager._track(e,t)})))().then()}_debugPromptNotShown(e,t){const s={[ye._tevDataPromptNotShownKey]:e};return t&&(s[ye._tevFieldErrorMessage]=t),this._debug(ae.PROMPT_NOT_SHOWN,s)}_debugUnknownAsyncBrowserCommand(e){return this.eventManager._track(new q(B.UNKNOWN_ASYNC_COMMAND,null,String(e[0])),{async_command:e})}_debugUnknownConfigurationKeys(e){return this.eventManager._track(new q(B.UNKNOWN_CONFIG_KEYS),{push_sdk_config:e})}_debugUnknownContextKey(e){return this.eventManager._track(new q(B.UNKNOWN_CONTEXT_KEY,null,e),{context_key:e})}_debugUnknownPromptMessage(e){return this.eventManager._track(new q(B.UNKNOWN_PROMPT_MESSAGE),{prompt_message:e})}}class ws{constructor(e={},t){P(this,"_logger"),P(this,"_eventQueue"),P(this,"_trackedEventQueueTimer"),P(this,"_isEventQueueFlushing"),this.asyncProvider=e,this._logger=null!=t?t:ie._getInstance("EventManager"),this._eventQueue=[],this._isEventQueueFlushing=!1,this._setup()}_setup(){this._hydrateEventQueue().then((()=>this._startEventQueueTimer()))}_canSend(){return N(this,null,(function*(){var e,t,s;return null!=(s=null==(t=(e=this.asyncProvider)._canSend)?void 0:t.call(e))?s:Promise.resolve(!0)}))}_isSubscribed(){return N(this,null,(function*(){return!!this.asyncProvider._getIsSubscribed&&(yield this.asyncProvider._getIsSubscribed())}))}_track(e,t={}){this._trackAsync(e,t).then()}_trackAsync(e){return N(this,arguments,(function*(e,t={}){try{let s;if(e instanceof Error){if(q._isSuppressed(e))return;s=yield pe._getErrorEvent(e),s.data.logs=this._logger._getLogs(!0).splice(-10).reverse(),t&&(s.data[x._tevFieldErrorContext]=t)}else s="string"==typeof e?yield pe._build(e,t):e;return yield this._trackEvent(s)}catch(s){this._logger.error(s)}}))}_trackEvent(e){return N(this,null,(function*(){if(this._eventQueue.length>=x._eventQueueMaxSize&&(this._eventQueue=this._eventQueue.slice(0,x._eventQueueMaxSize-1),yield this._persistEventQueue()),this._eventQueue.find((t=>t.event_id===e.event_id)))return void this._logger.debug(`Event ${e.event_id} has already been added to the queue`);if(this._eventQueue.find((t=>pe._isEqual(t,e))))return void this._logger.debug(`Event ${e.event_id} is a duplicate event`);if(!(yield this._isSubscribed())&&(t=e.action,["purchase","update_cart","add_to_cart","view_item"].includes(t)))return void this._logger.debug(`Ignoring event ${e.event_id} (${e.action}) - user is not subscribed.`);var t;if(!(yield this._canSend())||!(e=>["debug","sdk_impression","prompt_not_shown","error","subscribed","manual_unsubscribed","unsubscribed","udr","notification_impression","notification_click","notification_close","soft_unsubscribe","soft_resubscribe","la_register","la_end","iam_click","iam_subscribe","iam_impression","iam_close","session_start","session_heartbeat"].includes(e)||le(e))(e.action))return this._logger.debug(`Queueing event ${e.event_id} (${e.action})`),this._eventQueue.push(e),void(yield this._persistEventQueue());this._logger.debug(`Processing event ${e.event_id} (${e.action})`);const s=yield this._process([e],(e=>["subscribed"].includes(e)?x._kApiAllowUrl:x._kApiEventsUrl)(e.action));s.isErr()&&(this._logger.verbose(`Requeueing event ${e.event_id} (${e.action})`),this._eventQueue.unshift(e))}))}_hydrateEventQueue(){return N(this,null,(function*(){if(!this.asyncProvider._getCachedEvents)return void this._logger.verbose("Cache evaluator not set");const e=yield this.asyncProvider._getCachedEvents();if(!e.length)return void this._logger.verbose("Cache is empty");const t=e.filter((e=>-1===this._eventQueue.findIndex((t=>t.event_id===e.event_id))));this._eventQueue.push(...t),t.length&&(this._logger.verbose(`Rehydrated ${t.length} event(s) from cache`),yield this._persistEventQueue())}))}_startEventQueueTimer(){this._trackedEventQueueTimer?this._logger.verbose("Queue timer already initialized"):this._trackedEventQueueTimer=setTimeout((()=>{this._flushEventQueue().then((()=>{this._trackedEventQueueTimer=null,this._startEventQueueTimer()}))}),x._eventQueueFlushIntervalMS)}_flushEventQueue(){return N(this,null,(function*(){if(!this._eventQueue.length||this._isEventQueueFlushing||!(yield this._canSend()))return;yield this._cleanupEventQueue();const e=yield this._getNextBatch();if(!e.length)return void this._setEventQueueFlushingState(!1);(yield this._process(e,x._kApiEventsUrl)).isErr()&&this._eventQueue.push(...e)}))}_process(e,t){return N(this,null,(function*(){let s;yield this._preloadTrackedEventUtilProperties(),e.forEach((e=>{pe._prepareSendEvent(e)}));const i=e.map((e=>{const t=e,{sendAttemptCount:i,jxms:r,data:n}=t,o=I(t,["sendAttemptCount","jxms","data"]);return s=r,Object.assign((e=>{const t={};for(const s of Object.keys(e))void 0!==e[s]&&null!==e[s]&&(t[s]=e[s]);return t})(o),{data:n})}));let r;this._logger.verbose("Dispatching event processing");try{let n=1==i.length?i[0]:i;this._logger.verbose(`Building request data: ${n}`),r=new Me(Ue.POST,t,n,{jitterMillis:s}),this._logger.debug(`Prepared ${e.length} event(s):`,n)}catch(n){const e=H(n);return this._logger.error(`Unable to prepare events: ${e.message}`),Te.Err(e)}if(r){const e=yield r._perform();return e.isErr()?(this._logger.error("Send failed;",e.getErr().message),e):(this._logger.verbose("Send successful"),Te.Ok(!0))}return this._logger.verbose("No request to process"),Te.Ok(!1)}))}_getNextBatch(){return N(this,null,(function*(){if(!(this._eventQueue.length>x._eventQueueFlushTriggerSize?x._eventQueueFlushTriggerSize:this._eventQueue.length))return[];const e=[],t=yield this._isSubscribed(),s=this._eventQueue.filter((s=>{let i=t||(r=s.action,!["external_id","deregister_external_id","permission_changed","profile","profile_append","profile_remove","page_tag_visit","purchase","update_cart","add_to_cart","view_item","notification_impression","notification_click","notification_close","soft_unsubscribe","soft_resubscribe","manual_unsubscribed","unsubscribed","session_heartbeat","session_start"].includes(r));var r;return i&&e.push(s),!i}));return e.length&&(this._eventQueue=s,yield this._persistEventQueue()),e}))}_cleanupEventQueue(){return N(this,null,(function*(){if(!this._eventQueue.length)return;const e=this._eventQueue.filter((e=>e.sendAttemptCount{e.token instanceof PushSubscription&&(e.token=e.token.toJSON())})),this.asyncProvider._setCachedEvents(this._eventQueue).catch((e=>this._logger.critical(e))).then()}))}_preloadTrackedEventUtilProperties(){return N(this,null,(function*(){var e,t,s,i,r,n,o,a,l;yield Promise.all([pe._domainId?null:null==(s=null==(t=(e=this.asyncProvider)._getDomainId)?void 0:t.call(e))?void 0:s.then((e=>{pe._domainId=e})),pe._anonymousId?null:null==(n=null==(r=(i=this.asyncProvider)._getAnonymousId)?void 0:r.call(i))?void 0:n.then((e=>{pe._anonymousId=e})),pe._token?null:null==(l=null==(a=(o=this.asyncProvider)._getToken)?void 0:a.call(o))?void 0:l.then((e=>{e&&(pe._token=e)}))]).catch()}))}}class Os extends ws{_trackEvent(e){return N(this,null,(function*(){return this._ensurePageUrlProperty(e),(t=Os.prototype,s=this,i="_trackEvent",f(m(t),i,s)).call(this,e);var t,s,i}))}_ensurePageUrlProperty(e){var t;(t=e.action,[ae.PROMPT_SHOWN,ae.PROMPT_ACCEPTED,ae.PROMPT_DISMISSED,ae.PROMPT_NOT_SHOWN,ae.PERMISSION_SHOWN,ae.PERMISSION_ACCEPTED,ae.PERMISSION_DISMISSED,ae.PERMISSION_DENIED,ae.PERMISSION_CHANGED].includes(t))&&(e.data[ye._tevDataPageUrlKey]||(e.data[ye._tevDataPageUrlKey]=Be._location.href))}}function Ts(e){return e.every((e=>"quantity"in e&&"number"==typeof e.quantity))}function Ns(e){return e.map((({item_type:e,id:t})=>({item_type:e,id:t})))}c=new WeakMap,d=new WeakMap;let Cs=class e{constructor(e,t,s,i,r,n){P(this,"UserProfile"),P(this,"EComm"),P(this,"PushNotifications"),P(this,"Prompts"),O(this,c,void 0),O(this,d,void 0),T(this,c,e),T(this,d,null!=n?n:ie._getInstance()),this.UserProfile=t,this.EComm=s,this.PushNotifications=i,this.Prompts=r}static getInstance(){const t=Ne();if(t)return t;const s=new ps,i=new fs(new bs),r=new Ps,n=new vs(s,i),o=new Os(n);st._setEventManager(o);const a=new Yt(o,s,i,new Is(r),new Ds(s,o),r),l=new me(a),u=new De(a),c=new ve(a),d=new we(a);return n.setUserProfileModule(l),new e(a,l,u,c,d)}setConfiguration(e){w(this,c)._setConfiguration(e)}getConfiguration(){var e;return null!=(e=w(this,c).loadConfig)?e:null}get version(){return ye._libraryVersion}get iid(){return w(this,c).iid}get isLoaded(){return w(this,c).isLoaded}registerPushSDKLifecycleCallbacks(e){w(this,c)._registerPushSdkLifecycleCallbacks(e)}registerPermissionLifecycleCallbacks(e){w(this,c)._registerPermissionLifecycleCallbacks(e)}registerAppMessageLifecycleCallbacks(e){w(this,c)._registerAppMessageLifecycleCallbacks(e)}registerPromptLifecycleCallbacks(e){w(this,c)._registerPromptLifecycleCallbacks(e)}get logLevel(){return w(this,d).logLevel}set logLevel(e){w(this,d).logLevel=e}debug(e=!0){return N(this,null,(function*(){yield w(this,c)._toggleDebugPanel(e)}))}load(e){this.setConfiguration(e)}requestNotificationPermission(e){return N(this,null,(function*(){void 0===e?this.PushNotifications.showPermissionPrompt():this.PushNotifications.showPermissionPrompt(e)}))}showLogs(e=!0){this.logLevel=e?C.VERBOSE:C.NONE}getLogs(){return w(this,d)._getLogs()}isUserSoftUnsubscribed(){return N(this,null,(function*(){return this.PushNotifications.getIsPaused()}))}isUserEligibleToPrompt(){return N(this,null,(function*(){return this.PushNotifications.getIsEligibleToPrompt()}))}isUserSubscribed(){return N(this,null,(function*(){return this.PushNotifications.getIsSubscribed()}))}get context(){return w(this,c)._legacyContext}getUser(){return this.context.user}on(e,t){this.push([`on_${e}`,t])}watch(e,t){this.on(e,t)}watchOnce(e,t){this.on(e,t)}trigger(e,t){this.push([e,t])}push(e,t){try{switch(e[0]){case re.LOAD:this.setConfiguration(e[1]);break;case re.REQUEST_USER_DELETION:this.UserProfile.requestUserDeletion();break;case re.DEBUG:w(this,c)._toggleDebugPanel();break;case re.CONFIRM_CONSENT:break;case re.EXTERNAL_ID:this.UserProfile.setExternalId(e[1]);break;case re.DEREGISTER_EXTERNAL_ID:this.UserProfile.unsetExternalId();break;case re.PROFILE:this.UserProfile.set(e[1]);break;case re.PROFILE_APPEND:Object.entries(e[1]).forEach((([e,t])=>{this.UserProfile.append(e,t)}));break;case re.PROFILE_REMOVE:Object.entries(e[1]).forEach((([e,t])=>{this.UserProfile.remove(e,t)}));break;case re.PAGE_TAG_VISIT:{const t=Be._location.href;let i=[];if(Array.isArray(e[1]))i=e[1];else try{i=[String(e[1])]}catch(s){}i=i.filter((e=>{try{return void 0!==e&&"undefined"!==e&&null!==e&&"null"!==e&&!!String(e).trim()}catch(s){}return!1})).map((e=>e.toString())),w(this,c)._executeWhenConfiguredIfEnabled((()=>{w(this,d).verbose(`Sending ${i.length} tag${i.length>1?"s":""} for ${t}`),w(this,c).eventManager._track(ae.PAGE_TAG_VISIT,{[ye._tevDataPageUrlKey]:t,[ye._tevDataPageTagsKey]:i})}));break}case re.SHOW_PROMPT:if(1===e.length)this.PushNotifications.showPermissionPrompt();else{const{id:t,checkEligibility:s}=e[1];null!=t?this.PushNotifications.showPermissionPrompt(t,{skipEligibilityCheck:!s}):this.PushNotifications.showPermissionPrompt({skipEligibilityCheck:!s})}break;case re.PAUSE_PUSH_NOTIFICATIONS:this.PushNotifications.pause();break;case re.RESUME_PUSH_NOTIFICATIONS:this.PushNotifications.resume();break;case re.GET_PUSH_NOTIFICATIONS_PAUSED_STATE:this.PushNotifications.getIsPaused().then(e[1]);break;case re.SAVE_ITEM:{const t="products"in e[1]?e[1].products:e[1].events;Array.isArray(t)&&w(this,c)._executeWhenConfiguredIfEnabled((()=>{w(this,d).verbose(`Adding ${t.length} item${t.length>1?"s":""} to saved items`),w(this,c).eventManager._track(ae.SAVE_ITEM,e[1])}));break}case re.VIEW_ITEM:{const t="products"in e[1]?e[1].products:e[1].events;Array.isArray(t)&&w(this,c)._executeWhenConfiguredIfEnabled((()=>{w(this,d).verbose(`Adding ${t.length} item${t.length>1?"s":""} to viewed items`),w(this,c).eventManager._track(ae.VIEW_ITEM,e[1])}));break}case re.ADD_TO_CART:{const t="products"in e[1]?e[1].products:e[1].events;Array.isArray(t)&&w(this,c)._executeWhenConfiguredIfEnabled((()=>{w(this,d).verbose(`Adding ${t.length} item${t.length>1?"s":""} to cart`),w(this,c).eventManager._track(ae.ADD_TO_CART,e[1])}));break}case re.UPDATE_CART:{const t="products"in e[1]?e[1].products:e[1].events;Array.isArray(t)&&w(this,c)._executeWhenConfiguredIfEnabled((()=>{t.length?w(this,d).verbose(`Updating cart with ${t.length} item${t.length>1?"s":""}.`):w(this,d).verbose("Clearing cart"),w(this,c).eventManager._track(ae.UPDATE_CART,e[1])}));break}case re.PURCHASE:if(1===e.length)w(this,d).verbose("Tracking purchase"),w(this,c).eventManager._track(ae.PURCHASE);else{let t;if("products"in e[1]){const s=e[1].products.map((e=>Pe(e,Ie.PRODUCT))),i=Ts(s)?s:Ns(s);e[1].products=i,t=i}if("events"in e[1]){const s=e[1].events.map((e=>Pe(e,Ie.EVENT))),i=Ts(s)?s:Ns(s);e[1].events=i,t=i}Array.isArray(t)||(t=void 0);const s=["Tracking purchase"];(null==t?void 0:t.length)&&s.push(`of ${t.length} item${t.length>1?"s":""}`),"purchase_id"in e[1]&&s.push(`Purchase ID: ${e[1].purchase_id}`),"price_value"in e[1]&&s.push(`Total value: ${e[1].price_value}`),w(this,d).verbose(s.join(" ")),w(this,c).eventManager._track(ae.PURCHASE,e[1])}break;case`on_${ne.LOADED}`:case`on_${ne.WEB_PUSH_SUPPORTED}`:case`on_${ne.WEB_PUSH_UNSUPPORTED}`:case`on_${ne.READY}`:case`on_${ne.PROMPT_ELIGIBLE}`:case`on_${ne.PROMPT_INELIGIBLE}`:case`on_${ne.PROMPT_SHOWN}`:case`on_${ne.PROMPT_DISMISSED}`:case`on_${ne.PROMPT_ALLOWED}`:case`on_${ne.PERMISSION_SHOWN}`:case`on_${ne.PERMISSION_ALLOWED}`:case`on_${ne.PERMISSION_DENIED}`:case`on_${ne.PERMISSION_DISMISSED}`:{const s=e[0].replace(/^on_/,"");"function"==typeof e[1]?w(this,c)._registerLegacyEventCallback(s,e[1],t):w(this,d).warn("Invalid SDK event handler callback specified:",e);break}default:!oe.includes(e[0])&&w(this,c).debugController&&w(this,c).debugController._debugUnknownAsyncBrowserCommand(e),w(this,d).warn("Unknown SDK command received:",e)}}catch(i){const e=H(i);w(this,d).error(e),w(this,c).eventManager._track(e)}}};const ks=Cs.getInstance();let As;try{As=ie._getInstance()}catch(Rs){As=console}try{if(window.self===window.top||window.self!==window.top&&window.frameElement&&"about:blank"===window.frameElement.src){const e=window.PushlySDK;if(e&&e instanceof Array)for(const t of e)ks.push(t);window.PushlySDK=ks}else As.warn("PushlySDK must be loaded from the top frame or a sourceless iFrame")}catch(Ls){As.warn("Unable to assign global PushlySDK"),As.error(Ls)}return e.PushSDK=ks,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({}); //# sourceMappingURL=pushly-sdk.min.js.map