var e=function(e){"use strict";var t,s,i,r,n,o,a,l,u,c,d=Object.defineProperty,_=Object.defineProperties,h=Object.getOwnPropertyDescriptors,g=Object.getOwnPropertySymbols,p=Object.getPrototypeOf,m=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable,E=Reflect.get,f=(e,t,s)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,b=(e,t)=>{for(var s in t||(t={}))m.call(t,s)&&f(e,s,t[s]);if(g)for(var s of g(t))S.call(t,s)&&f(e,s,t[s]);return e},v=(e,t)=>_(e,h(t)),y=(e,t)=>{var s={};for(var i in e)m.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&g)for(var i of g(e))t.indexOf(i)<0&&S.call(e,i)&&(s[i]=e[i]);return s},I=(e,t,s)=>(f(e,"symbol"!=typeof t?t+"":t,s),s),P=(e,t,s)=>{if(!t.has(e))throw TypeError("Cannot "+s)},D=(e,t,s)=>(P(e,t,"read from private field"),s?s.call(e):t.get(e)),w=(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)},O=(e,t,s,i)=>(P(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||{}),T="prod",k="@pushly/push-sdk-web",R="3.0.37",A="cdn.p-n.io",L="k.p-n.io",M="PushlySDK";let U=class{static get _env(){return T}static get _libraryName(){return k}static get _libraryVersion(){return R}static get _cdnDomain(){return A}static get _kApiDomain(){return L}static get _publicNamespace(){return M}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 x(e){try{const t=parseInt(String(e));return isNaN(t)?e:t}catch(t){return e}}const $={V8:{signature:/^\s*at\s+\S+\s+\(?\S+\)?$/,split:/:(?!\/)|\s+/},SpiderMonkeyOrJSCore:{signature:/^[^@]*@\S*$/,split:/:(?!\/)|@+/}};function K(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($).find((t=>$[t].signature.test(e)))])).filter((([,e])=>e)).map((([e,t])=>e.split($[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:x(s),column:void 0===i?0:x(i)})));return null==t||t.forEach((e=>{s=e(s)})),s}function W(e){return{message:e}}function F(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 V={exception:W("Unknown exception"),duplicate_sdk_detected:F("Another instance of the SDK is already running"),sdk_already_loaded:F("The SDK has already been loaded"),domain_config_load_failed:F("Failed to load Domain configuration from remote"),host_not_allowed:F("Current host is not allowed for use"),prompts_load_failed:W("Failed to load Prompts from remote"),web_push_not_supported:F("Web push not supported"),web_push_subscription_failed:W("Error encountered during subscription"),web_push_config_missing:F("Web push configuration missing"),push_worker_not_found_exception:W("Service Worker file not found"),push_worker_registration_exception:W("Service Worker registration exception encountered"),push_worker_subscription_exception:W("Web push subscription exception encountered"),storage_not_available:W("Storage not available"),storage_failed_to_open:W("Storage failed to open"),storage_ns_required:W("Store name is required"),storage_key_empty:W("No data for storage key"),idb_invalid_store_name:W("IndexedDB requires a valid store name; `null` provided"),idb_blocked:W("IndexedDB is blocked"),request_failed:W("Request exception encountered"),request_url_invalid:W("Invalid URL"),request_no_result:W("No result"),request_deserialization_failed:W("Failed to decode response"),unknown_context_key:W("Unknown context key"),unknown_config_keys:W("Unknown configuration key"),unknown_async_command:W("Unknown pushly() command"),unknown_prompt_message:W("Unknown prompt message"),worker_missing_push_data:W("Push event data missing"),unknown_worker_push:W("Unknown worker push event"),unknown_worker_pushly_interaction:W("Unknown worker pushly interaction"),unknown_worker_3p_interaction:W("Unknown worker 3rd-party interaction")};function G(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 H=class e extends Error{constructor(t,s,i,r=!1){null!=t||(t=B.EXCEPTION);const n=[V[t].message];i&&n.push(i),super(n.join(" - ")),I(this,"originalError"),I(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:G(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!!V[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=K(null==(t=this.originalError)?void 0:t.stack,[e._filterBuilderStackEntry]),i=K(this.stack,[e._filterBuilderStackEntry]);return s.length?s:i}toString(){return this._compositeMessage}};I(H,"KNOWN_NAMES",["AbortError","SecurityError","NetworkError"]),I(H,"FORCE_ALLOW_MESSAGE_PATTERNS",[/no active service worker/i]);let j=H;function q(e){return Object.keys(e).filter((t=>(isNaN(Number(t))||/^0\d+/.test(t))&&("string"==typeof e[t]||"number"==typeof e[t])))}function Y(e,t){const s=function(e){return q(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(q(e).map((t=>[t,e[t]])))}(e))}`);return s}function Q(e,t){try{return Y(e,t)}catch(s){}}const z={[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"}},X="pn_ll",Z=[],J={},ee={};class te{constructor(e){I(this,"_logLevel"),this.name=e,this._logLevel=C.NONE,this._restorePrevLogLevel()}static _getInstance(e){return e||(e=U._publicNamespace),J[e]||(J[e]=new te(e)),J[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(X);e&&Q(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(X,e)}catch(t){}}_log(e,t,s){const i=z[t],r=z[this.logLevel];e&&(s=s.slice()).unshift(`[${e}]`);let n=i.label[0];if(t===C.CRITICAL&&(n="!"+n),Z.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){Z.push([new Date,`!${z[C.CRITICAL].label[0]}`,o])}}}class se{constructor(e,t){I(this,"_globalLogger"),I(this,"_tag"),this._globalLogger=te._getInstance(t),this._tag=null!=e?e:null}static _getInstance(e,t){const s=null!=e?e:"root";return J[s]||(ee[s]=new se(e,t)),ee[s]}get logLevel(){return this._globalLogger.logLevel}set logLevel(e){this._globalLogger.logLevel=e}_getLogs(e=!1){return e?Z.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 j?e._compositeMessage:e instanceof Error?e.message:JSON.stringify(e)}catch(t){}return e})).join(" "))):Z.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 ie=(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.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))(ie||{}),re=(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))(re||{});const ne=["subscribe"];var oe=(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.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))(oe||{});const ae=e=>["debug","sdk_impression","prompt_not_shown"].includes(e),le=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 ue(e=32){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",s="";for(let i=0;iObject.assign(Object.create(null),e);function de(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 he=class{static _build(e,t,s){return N(this,null,(function*(){var i,r;const n=ce({sendAttemptCount:0,event_id:ue(5),channel:U._tevChannel,provider:U._tevVapidProvider,action:e,domain_id:this._domainId,domain_key:this._domainKey,pushly_unique_user_id:this._anonymousId,token:this._token,meta:ce({sdk:{name:U._libraryName,version:U._libraryVersion,library:U._libraryName,library_version:U._libraryVersion},event:{version:3}}),data:null!=t?t:{}});return s&&(n.jxms=s),(null==(i=this._loadConfig)?void 0:i.externalId)&&!n.data[oe.EXTERNAL_ID]&&(n.data[oe.EXTERNAL_ID]=null==(r=this._loadConfig)?void 0:r.externalId),n}))}static _getErrorEvent(e,t){return N(this,null,(function*(){return this._build(oe.ERROR,b({[U._tevFieldErrorCode]:e instanceof j?(s=e.code,s.replace(/^.|_+[a-z]/gi,(e=>e.replace(/_+/,"").toUpperCase()))):e.name,[U._tevFieldErrorDescription]:e instanceof j?e._name:e.name,[U._tevFieldErrorMessage]:e instanceof j?e._compositeMessage:e.message,[U._tevFieldErrorStack]:e instanceof j?e._stack:K(e.stack,[j._filterBuilderStackEntry]),page_url:location.href},null!=t?t:{}));var s}))}static _getProfileExternalIdEvent(e){return N(this,null,(function*(){return this._build(oe.PROFILE,{external_id:e})}))}static _getProfileLanguageEvent(e){return N(this,null,(function*(){return this._build(oe.PROFILE,{language:e})}))}static _getProfileTimeZoneEvent(e){return N(this,null,(function*(){return this._build(oe.PROFILE,{time_zone:e})}))}static _isEqual(e,t){return((e,t)=>le(e)===le(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=y(s,["sendAttemptCount","event_id","data"]);t=ce(b({},o))}return t.sendAttemptCount=0,t.event_id=ue(5),t.data=ce(e.data),t}static _getEventHashParts(e){var t,s;return ce({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)})}};I(he,"_domainKey"),I(he,"_domainId"),I(he,"_anonymousId"),I(he,"_loadConfig"),I(he,"_token"),he._domainKey=null,he._domainId=null,he._anonymousId=null,he._loadConfig=null,he._token=null;let ge=he;class pe{constructor(e,i){w(this,t,void 0),w(this,s,void 0),O(this,t,e),O(this,s,null!=i?i:se._getInstance("UserProfile"))}getAnonymousId(){return N(this,null,(function*(){return D(this,t).userStore._getAnonymousId()}))}getToken(){return N(this,null,(function*(){if(!D(this,t).notificationPermissionService)return null;return(yield D(this,t).notificationPermissionService._getCurrentPermissions()).token}))}setExternalId(e){return N(this,null,(function*(){if(!D(this,t).isLoaded)return void D(this,t)._registerOnLoadedCallback((()=>this.setExternalId(e)));const s=yield D(this,t).userStore._getExternalId();if(!s||e!==s){yield D(this,t).userStore._setExternalId(e);const s=yield ge._getProfileExternalIdEvent(e);D(this,t).eventManager._track(s)}}))}getExternalId(){return N(this,null,(function*(){return D(this,t).userStore._getExternalId()}))}unsetExternalId(){return N(this,null,(function*(){(()=>{N(this,null,(function*(){if(null!==this.getExternalId()){yield D(this,t).userStore._removeExternalId();const e=yield ge._build(oe.DEREGISTER_EXTERNAL_ID);D(this,t).eventManager._track(e)}}))})()}))}getSubscriberStatus(){return N(this,null,(function*(){return D(this,t).userStore._getSubscriberStatus()}))}getIsDeleted(){return N(this,null,(function*(){return D(this,t).userStore._getIsInDeletedState()}))}requestUserDeletion(){D(this,t)._executeWhenConfigured((()=>D(this,t)._handleUserDeletionRequest()))}set(e,i){const r="string"==typeof e?{[e]:i}:e;D(this,t)._executeWhenConfiguredIfEnabled((()=>{D(this,s).verbose(`Setting to profile: ${r}`),D(this,t).eventManager._track(oe.PROFILE,r)}))}append(e,i){D(this,t)._executeWhenConfiguredIfEnabled((()=>{D(this,s).verbose(`Appending to profile ${e}: ${i}`),D(this,t).eventManager._track(oe.PROFILE_APPEND,{[e]:i})}))}remove(e,i){D(this,t)._executeWhenConfiguredIfEnabled((()=>{D(this,s).verbose(`Removing from profile ${e}: ${i}`),D(this,t).eventManager._track(oe.PROFILE_REMOVE,{[e]:i})}))}trackActivity(e,s){D(this,t)._executeWhenConfiguredIfEnabled((()=>{const i={page_url:e};(null==s?void 0:s.length)&&(i.tags=s),D(this,t).eventManager._track(oe.VIEW_PAGE,i)}))}}t=new WeakMap,s=new WeakMap;var me=(e=>(e.SUBSCRIBED="subscribed",e.DISMISSED="dismissed",e.DENIED="denied",e.NOT_DETERMINED="not_determined",e))(me||{});const Se={not_determined:0,dismissed:1,subscribed:2,denied:-1},Ee=e=>{switch("string"==typeof e&&(e=e.toLowerCase()),e){case"subscribed":case Se.subscribed:return"subscribed";case"dismissed":case Se.dismissed:return"dismissed";case"blocked":case"denied":case Se.denied:return"denied";default:return"not_determined"}},fe=e=>"not_determined"===e?"not determined":e;class be{constructor(e,t){w(this,i,void 0),w(this,r,void 0),O(this,i,e),O(this,r,null!=t?t:se._getInstance("Notifications"))}showPermissionPrompt(e,t){D(this,i)._executeWhenConfiguredIfEnabled((()=>{var s;null==(s=D(this,i).promptsController)||s._showPrompt(e,t)}))}getIsEligibleToPrompt(){return N(this,null,(function*(){const e=yield D(this,i).userStore._getIsInDeletedState(),t=yield D(this,i).userStore._getIsSubscribed(),s=yield D(this,i).userStore._getIsUserInSoftUnsubscribedState(),r=yield D(this,i).userStore._getSubscriberStatus();return D(this,i).isLoaded&&D(this,i).isEnabled&&!e&&!t&&r!=me.DENIED&&r!=me.DISMISSED&&!s}))}pause(){return N(this,null,(function*(){this._executeIfSubscribed((()=>N(this,null,(function*(){(yield D(this,i).userStore._getIsUserInSoftUnsubscribedState())?D(this,r).info("The user is already in soft unsubscribe status."):(D(this,i).userStore._setIsUserInSoftUnsubscribedState(),D(this,i).eventManager._track(oe.SOFT_UNSUBSCRIBE),D(this,r).info("The user's notifications have been paused."))}))))}))}resume(){return N(this,null,(function*(){this._executeIfSubscribed((()=>N(this,null,(function*(){(yield D(this,i).userStore._getIsUserInSoftUnsubscribedState())?(D(this,i).userStore._unsetIsUserInSoftUnsubscribedState(),D(this,i).eventManager._track(oe.SOFT_RESUBSCRIBE),D(this,r).info("The user's notifications have been resumed.")):D(this,r).info("The user is not in a soft unsubscribe status.")}))))}))}getIsPaused(){return N(this,null,(function*(){return D(this,i).userStore._getIsUserInSoftUnsubscribedState()}))}getIsSubscribed(){return N(this,null,(function*(){return D(this,i).userStore._getIsSubscribed()}))}_executeIfSubscribed(e){return N(this,null,(function*(){yield D(this,i)._executeWhenConfigured((()=>N(this,null,(function*(){if(yield this.getIsSubscribed())try{yield e()}catch(t){const e=G(t);D(this,r).error(e),D(this,i).eventManager._track(e)}else D(this,r).warn("User is not currently subscribed and can not use this method")}))))}))}}i=new WeakMap,r=new WeakMap;class ve extends U{static get _dynamicDomainKey(){var e,t,s;return null!=(s=null!=(t=ve._injectedDomainKey)?t:null==(e=ve._injectedDomainConfig)?void 0:e.domain_key)?s:ve._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 _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 ye=(e=>(e.PRODUCT="product",e.EVENT="event",e))(ye||{});function Ie(e,t){let s;try{s={item_type:"item_type"in e?Q(ye,e.item_type):"event_id"in e?ye.EVENT:"product_id"in e?ye.PRODUCT:t,id:"id"in e?e.id:"event_id"in e?String(e.event_id):"product_id"in e?String(e.product_id):"",quantity:"quantity"in e?e.quantity:void 0}}catch(i){throw new TypeError(`ECommItem could not be parsed: ${G(i).message}. ${JSON.stringify(e)}`)}if(!s.item_type)throw new TypeError(`ECommItem.item_type could not be parsed. ${JSON.stringify(e)}`);if(!s.id)throw new TypeError(`ECommItem.id could not be parsed. ${JSON.stringify(e)}`);if(s.id!==String(s.id))throw new TypeError(`ECommItem.id is not a string. ${JSON.stringify(e)}`);if(null!==s.quantity&&void 0!==s.quantity&&isNaN(s.quantity))throw new TypeError(`ECommItem.quantity is not numeric. ${JSON.stringify(e)}`);return s}class Pe{constructor(e,t){w(this,n,void 0),w(this,o,void 0),O(this,n,e),O(this,o,null!=t?t:se._getInstance("ECommModule"))}trackViewedItems(e){return N(this,null,(function*(){D(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig("trackViewedItems",(t=>{const s={[t.item_type]:e.map((e=>Ie(e,t.item_type)))};D(this,o).verbose(`Adding ${e.length} item${e.length>1?"s":""} to viewed items`),D(this,n).eventManager._track(oe.VIEW_ITEM,s)}))}))}))}addToCart(e){return N(this,null,(function*(){D(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig("addToCart",(t=>{const s={[t.item_type]:e.map((e=>Ie(e,t.item_type)))};D(this,o).verbose(`Adding ${e.length} item${e.length>1?"s":""} to cart`),D(this,n).eventManager._track(oe.ADD_TO_CART,s)}))}))}))}updateCart(e){return N(this,null,(function*(){D(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig("updateCart",(t=>{const s={[t.item_type]:e.map((e=>Ie(e,t.item_type)))};D(this,o).verbose(`Updating cart with ${e.length} item${e.length>1?"s":""}.`),D(this,n).eventManager._track(oe.UPDATE_CART,s)}))}))}))}clearCart(){return N(this,null,(function*(){D(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig("clearCart",(e=>{const t={[e.item_type]:[]};D(this,o).verbose("Clearing cart"),D(this,n).eventManager._track(oe.UPDATE_CART,t)}))}))}))}trackPurchase(e,t,s){return N(this,null,(function*(){D(this,n)._executeWhenConfiguredIfEnabled((()=>{this._withECommConfig(`trackPurchase(${e?"items":""}${t?":purchaseId":""}${s?":priceValue":""})`,(i=>{if(void 0===e)return D(this,o).verbose("Tracking purchase"),void D(this,n).eventManager._track(oe.PURCHASE);const r={[i.item_type]:e.map((e=>Ie(e,i.item_type)))};t&&(r.purchase_id=t),s&&(r.price_value=s),D(this,o).verbose(`Tracking purchase of ${e.length} item${e.length>1?"s":""}${t?" Purchase ID: "+t:""}${s?" Total value: "+s:""}.`),D(this,n).eventManager._track(oe.PURCHASE,r)}))}))}))}_withECommConfig(e,t){return N(this,null,(function*(){D(this,n)._executeWhenConfigured((()=>N(this,null,(function*(){const s=yield D(this,n).domainConfigProvider._get();if(s.isErr())return D(this,o).warn(s.getErr()),void D(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(ve._domainFeatIntegrationsECommFlag)?t(r):D(this,o).warn("E-Commerce support is not currently enabled for this domain"):D(this,o).warn(`E-Commerce configuration has unrecognized item type: ${r.item_type}`):D(this,o).warn("E-Commerce configuration is not defined for this domain")}))))}))}}n=new WeakMap,o=new WeakMap;class De{constructor(e,t){w(this,a,void 0),w(this,l,void 0),O(this,a,e),O(this,l,null!=t?t:se._getInstance("Prompts"))}dispatch(e){return N(this,null,(function*(){var t;e.prompt_action?yield null==(t=D(this,a).promptsController)?void 0:t._processDispatchMessage(e):D(this,l).debug("Received unknown Prompt message:",e)}))}}a=new WeakMap,l=new WeakMap;const we=["domainKey","sw","swScope","externalId","classNames","consentRequired","requireConsent","frameMessenger"];class Oe{constructor(e,t=null){I(this,"ok"),I(this,"err",null),I(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 Oe(e)}static Err(e){return new Oe(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 Te=e=>new j(B.REQUEST_URL_INVALID,null,e),ke=()=>new j(B.REQUEST_NO_RESULT),Re=(e,t)=>new j(B.REQUEST_DESERIALIZATION_FAILED,t,e),Ae=e=>new j(B.REQUEST_FAILED,e);class Le{constructor(e,t,s=null,i={},r){var n,o;I(this,"_id"),I(this,"_method"),I(this,"_requestUrl"),I(this,"_data"),I(this,"_headers"),I(this,"_parameters"),I(this,"_logger"),I(this,"jitterMillis"),this._logger=null!=r?r:se._getInstance("Request"),this._id=ue(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[U._eventPriorityHeader]=U._eventPriorityHeaderImmFlag:delete this._headers[U._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)})),Oe.Ok(e)}catch(e){return Oe.Err(Te(this._requestUrl))}}get _requestOptions(){const e=this._url;return e.isErr()?e:Oe.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>=U._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(Oe.Ok({response:a}));const l=yield a.text();if(!l)return n(),void e(Oe.Err(ke()));try{n(),e(Oe.Ok({data:JSON.parse(l),response:a}))}catch(t){this._logger.warn(`${i()} Unable to decode response: ${l}`),e(Oe.Err(Re(l,G(t))))}}catch(s){if(!o()){n();const t=G(s);e(Oe.Err(Ae(t)))}}}));a()}))}))}}var Me=(e=>(e.GET="GET",e.POST="POST",e))(Me||{});const Ue=e=>{const t="number"==typeof e?new Date(e):e,s=new Date;return t.getTime()-s.getTime()};class xe{constructor(e,t,s){I(this,"logger"),I(this,"cached",null),this.domainKey=e,this.settingsStore=t,this.logger=null!=s?s:se._getInstance("DomainConfigProvider")}_get(){return N(this,null,(function*(){const e=yield this._getFromCache();return e?(this.logger.verbose("Hydrated from cache"),Oe.Ok(e)):this._getFromRemote()}))}get _injectedDomainConfig(){return ve._injectedDomainConfig}_getFromCache(){return N(this,null,(function*(){const e=yield this.settingsStore._getDomainConfig();if(e){const t=1e3*ve._pnDomainConfigCacheTtlSeconds-Math.abs(Ue(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*ve._pnPromptsCacheTtlSeconds-Math.abs(Ue(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=`${ve._cdnDomainSettingsUrl}/${this.domainKey}/web/config`,s=new Le(Me.GET,t),i=yield s._perform();if(i.isErr())return i;const r=i.unwrap().data;if(!r)return Oe.Err(new j(B.DOMAIN_CONFIGURATION_LOAD_FAILED));e=ce(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)),Oe.Ok(e)}))}}var $e=(e=>(e.VAPID="VAPID",e.APNS="APNS",e))($e||{});let Ke=class e{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 t=this._navigator,s="safari"in e._scope&&!t.userAgent.match(/crios/i)&&!t.userAgent.match(/fxios/i)&&!t.userAgent.match(/Opera|OPT\//),i="vendor"in t?!!t.vendor.match(/apple/i):"userAgentData"in t&&/macos/i.test(navigator.userAgentData.platform);return s&&i}static get _requires2Step(){if(this._isSafari)return!0;if(!navigator.userAgentData)return!0;for(const e of navigator.userAgentData.brands){if(/firefox/i.test(e.brand))return!0;if("Microsoft Edge"===e.brand)return!0}return!1}static get _isPushManagerInScope(){return"PushManager"in this._scope}static get _pushProvider(){return this._isInWorkerGlobalScope||!this._isSafari||this._isPushManagerInScope?$e.VAPID:$e.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,G(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,G(t).message]}return[!0]}};function We(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(U._sdkHasEventsOnlyDomainsFlag),o=i.some(Fe),a=r.some(Fe);return n&&o&&a}function Fe(e){const t=Ke._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 Ke{static get _isDevMode(){return"development"===U._env}static _getIsWebPushSupported(){return N(this,null,(function*(){try{const[t,s]=this._getIsEnvBaseSupported();if(!t)return[!1,s];if(this._pushProvider===$e.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,G(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 Ve{constructor(e,t,s){this.delegate=e,this.domain=t,this.logger=s}static get _defaultPermissions(){return{permission:"default",token:null}}}class Ge extends Ve{constructor(e,t,s,i){super(t,s,null!=i?i:se._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=Ve._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.",G(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 He=(e=>(e.GRANTED="granted",e.DENIED="denied",e.DISMISSED="dismissed",e))(He||{}),je=(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))(je||{});class qe{constructor(e,t,s,i,r,n,o){I(this,"registrationService"),I(this,"additionalEventData",{}),I(this,"additionalEventContext",{}),I(this,"logger"),this.domain=e,this.workerService=t,this.eventManager=s,this.userStore=i,this.lifecycleCallbacks=r,this.delegate=n,this.logger=null!=o?o:se._getInstance("NotificationPermissionService"),this.registrationService=new Ge(this.workerService,this,this.domain)}static _getWebPushSupport(){return N(this,null,(function*(){const[e,t]=yield Be._getIsWebPushSupported();return e?Oe.Ok(!0):Oe.Err(new j(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?Oe.Ok(!0):Oe.Err(new j(B.WEB_PUSH_CONFIGURATION_MISSING))}))}_getCurrentPermissions(){return N(this,null,(function*(){const e=yield this.registrationService._getCurrentPermissions();return b({provider:this._provider},e)}))}_synchronize(){return N(this,null,(function*(){var e,t;if(We(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===$e.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&&(ge._token=s.token),"default"===s.permission&&i===me.NOT_DETERMINED||"granted"===s.permission&&i===me.SUBSCRIBED&&s.token||"denied"===s.permission&&i===me.DENIED)this.logger.info("Current notification permissions:",fe(i));else if("denied"===s.permission&&i===me.DISMISSED||"denied"===s.permission&&i===me.NOT_DETERMINED)this.logger.debug("Updating subscriber status to",fe(me.DENIED)),yield this.userStore._setSubscriberStatus(me.DENIED);else if("granted"===s.permission&&i===me.DENIED||"granted"===s.permission&&i===me.DISMISSED||"granted"===s.permission&&i===me.NOT_DETERMINED||"granted"===s.permission&&!s.token){this.logger.verbose(`Granted permissions mismatch found - current: ${s.permission}, cached: ${fe(i)}`);const e=yield this._attemptSilentSubscription();i!==me.SUBSCRIBED&&e&&(this.logger.debug("Updating subscriber status to",fe(me.SUBSCRIBED)),yield this.userStore._setSubscriberStatus(me.SUBSCRIBED))}else"default"===s.permission&&i===me.DISMISSED?this.logger.info(`User has recently ${fe(me.DISMISSED)} permissions`):"default"===s.permission&&i===me.DENIED?(this.logger.debug("Updating subscriber status to",fe(me.NOT_DETERMINED)),yield this.userStore._setSubscriberStatus(me.NOT_DETERMINED)):"denied"===s.permission&&i===me.SUBSCRIBED?(yield this.userStore._setSubscriberStatus(me.DENIED),yield this._revokePermission()):"default"===s.permission&&i===me.SUBSCRIBED?(this.logger.debug("Updating subscriber status to",fe(me.NOT_DETERMINED)),yield this.userStore._setSubscriberStatus(me.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?ge._token=null:r.token?(ge._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.delegate)?void 0:e._onPermissionChanged)||t.call(e,r,s),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=v(b({},r),{provider:this._provider});return n.permission===i.permission&&n.token===i.token||null==(s=null==(t=this.delegate)?void 0:t._onPermissionChanged)||s.call(t,n,i),n}))}_revokePermission(){return N(this,null,(function*(){(yield this.workerService._unsubscribe())&&this.eventManager._track(oe.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),ge._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?Oe.Err(je.USER_DELETED):t?Oe.Err(je.USER_PERMISSION_GRANTED):s||i===me.DENIED?Oe.Err(je.USER_PERMISSION_DENIED):i===me.DISMISSED?Oe.Err(je.USER_PERMISSION_DISMISSED):Oe.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(oe.PERMISSION_SHOWN,b({},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(me.DENIED),null==(t=null==(e=this.lifecycleCallbacks)?void 0:e.onPushSDKDidReceivePermissionResponse)||t.call(e,He.DENIED),this.eventManager._track(oe.PERMISSION_DENIED,b({},this.additionalEventData)),this._resetPermissionEventContext()}))}_onPushPermissionDismissed(){return N(this,null,(function*(){var e,t,s;const i=null!=(e=this.additionalEventContext.dismissalExpirationSeconds)?e:ve._defaultDismissedStatusExpirationSeconds;0===i?(this.logger.debug("Setting subscriber status to NOT_DETERMINED"),yield this.userStore._setSubscriberStatus(me.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,He.DISMISSED),this.eventManager._track(oe.PERMISSION_DISMISSED,b({},this.additionalEventData)),this._resetPermissionEventContext()}))}_onPushPermissionGranted(){return N(this,null,(function*(){var e,t;yield this.userStore._setSubscriberStatus(me.SUBSCRIBED),null==(t=null==(e=this.lifecycleCallbacks)?void 0:e.onPushSDKDidReceivePermissionResponse)||t.call(e,He.GRANTED),this.eventManager._track(oe.PERMISSION_ACCEPTED,b({},this.additionalEventData))}))}_onPushSubscriptionSucceeded(e){return N(this,null,(function*(){var t,s;ge._token=e,null==(s=null==(t=this.lifecycleCallbacks)?void 0:t.onPushSDKDidRegisterForRemoteNotificationsWithDeviceToken)||s.call(t,e);const i=yield this._getBaseSubscriptionEvent();i.data=b(b({},this.additionalEventData),i.data),this.eventManager._track(i),this._resetPermissionEventContext()}))}_getBaseSubscriptionEvent(){return N(this,null,(function*(){return ge._build(oe.TOKEN_RECEIVED,{[ve._tevDataPageUrlKey]:this._currentHref,[ve._tevSubscribedUrlKey]:this._currentHref})}))}_onPushSubscriptionFailed(e){return N(this,null,(function*(){var t,s;ge._token=null,this.logger.info(`event:${oe.ERROR}`,e),null==(s=null==(t=this.lifecycleCallbacks)?void 0:t.onPushSDKDidFailToRegisterForRemoteNotificationsWithError)||s.call(t,new j(B.WEB_PUSH_SUBSCRIPTION_FAILED,e)),e&&this.eventManager._track(e),this._resetPermissionEventContext()}))}}const Ye=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},Qe=e=>{const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=Ye(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 Xe(e,t){return Promise.race(["function"==typeof t?t():Promise.resolve(t),new Promise((t=>{setTimeout((()=>t()),e)}))])}var Ze=(e=>(e[e.ERROR=1]="ERROR",e))(Ze||{});const Je=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(G(s))}}};I(Je,"eventManager"),I(Je,"logger"),Je.logger=se._getInstance("Dispatch"),I(Je,"EventType",Ze);let et=Je;const tt=(e=100)=>Math.floor(Math.random()*e),st=(e,t=!1)=>{const s=e?G(e):void 0;return j._from(s,null,B.PUSH_WORKER_REGISTRATION_EXCEPTION,t)},it=e=>{const t=e?G(e):void 0;return j._from(t,null,B.PUSH_WORKER_NOT_FOUND_EXCEPTION)},rt=(e,t=!1)=>{const s=e?G(e):void 0;return j._from(s,null,B.PUSH_WORKER_SUBSCRIPTION_EXCEPTION,t)};class nt{constructor(e,t,s){I(this,"logger"),this.pushSdkConfig=e,this.domain=t,this.logger=null!=s?s:se._getInstance("PushWorkerService")}get _worker(){return Be._navigator.serviceWorker}get _location(){return Be._location}_ready(e){return N(this,null,(function*(){return Xe(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(ve._swShouldUnregisterNonPushlyWorkersFlag);if(a&&l){if(s=n,!u)break}else if(a||!u){if(a&&!l&&!this.domain.flags.includes(ve._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=G(t);et._dispatch(et.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(G(i),t)}return yield Xe(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=G(t);et._dispatch(et.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"),Oe.Ok(e);let t=yield this._getRegistration();if(!t)try{t=yield this._register()}catch(i){return Oe.Err(st(i))}this.logger.info("Subscribing");let s=Oe.Ok(null);for(let r=0;r++<10;){try{yield this._ready();const e=yield t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Qe(this.domain.vapid_public_key)});if(e){s=Oe.Ok(e);break}}catch(i){const e=this._sanitizeSubscriptionError(G(i));if(10===r){s=Oe.Err(e);break}this.logger.warn(e)}this.logger.debug("Retrying subscription"),yield Ce(tt(500))}return s}))}_unsubscribe(){return N(this,null,(function*(){try{const e=yield this._getSubscription();if(e)return yield e.unsubscribe(),!0}catch(e){const t=G(e);et._dispatch(et.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(ve._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(ve._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(j.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 st(e,!0);if(/404/.test(e.message)||404===(yield this._tryFetchResourceStatus(t)))throw it(e);return st(e)}))}_sanitizeSubscriptionError(e){const t=j.KNOWN_NAMES.includes(e.name)||[/push service error/i,/could not retrieve the public key/i].some((t=>t.test(e.message)));return rt(e,t)}}class ot{constructor(e,t,s,i){I(this,"_name"),I(this,"_task"),I(this,"_intervalMilliseconds"),I(this,"_options"),I(this,"_timer"),I(this,"_isStarted"),I(this,"_isPaused"),I(this,"_startTime"),I(this,"_stopTime"),I(this,"_pausedStartTime"),I(this,"_totalPausedTime"),I(this,"_expectedTime"),I(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 at=class e{constructor(e,t,s,i,r){I(this,"previousSubscriberState",null),this.domainConfig=e,this.eventManager=t,this.userStore=s,this.sessionStore=i,this.logger=r,this.evaluateInitialSubscriberStatus()}static _init(t,s,i,r,n){return null!=n||(n=se._getInstance("PageViewProcessor")),new ot("pvp_timer",new e(t,s,i,r,n),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*(){try{const e=this._currentLocation.href,t=yield this.userStore._getLastPageViewed(),s=yield this.userStore._getSubscriberStatus(),i=s!==this.previousSubscriberState&&s===me.SUBSCRIBED;this.previousSubscriberState=s,t&&t===e&&!i||(i||(yield this.userStore._setLastPageViewed(e),this.logger.verbose("Incrementing page views"),yield this.sessionStore._incrementSessionPageViewCount()),s===me.SUBSCRIBED?(this.logger.verbose("Preparing page view event"),yield this._track(oe.VIEW_PAGE,e)):this.domainConfig.flags.includes(ve._domainFeatInformedContentFlag)?(this.logger.verbose("Preparing anonymous page view event"),yield this._track(oe.ANONYMOUS_VIEW_PAGE,e)):this.logger.debug("Page View tracking is not enabled"))}catch(e){const t=G(e);this.eventManager._track(t),this.logger.warn(t)}}))}get _currentLocation(){return Ke._location}_track(e,t){return N(this,null,(function*(){const s={[ve._tevDataPageUrlKey]:t};this.eventManager._track(e,s)}))}};I(at,"PAGE_VIEW_INTERVAL_SECONDS",1);let lt=at;class ut{constructor(e,t,s){I(this,"logger"),I(this,"cached",null),this.domainKey=e,this.settingsStore=t,this.logger=null!=s?s:se._getInstance("PromptsProvider")}_get(){return N(this,null,(function*(){const e=yield this._getFromCache();return e?(this.logger.verbose("Hydrated from cache"),Oe.Ok(e)):this._getFromRemote()}))}get _injectedPromptGroups(){return ve._injectedPromptGroups}_getFromCache(){return N(this,null,(function*(){const e=yield this.settingsStore._getCachedPrompts();if(e){const t=1e3*ve._pnPromptsCacheTtlSeconds-Math.abs(Ue(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*ve._pnPromptsCacheTtlSeconds-Math.abs(Ue(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=`${ve._cdnDomainSettingsUrl}/${this.domainKey}/web/prompts`,s=new Le(Me.GET,t),i=yield s._perform();if(i.isErr())return i;const r=i.unwrap().data;if(!r)return Oe.Err(new j(B.PROMPTS_LOAD_FAILED));e=r.map((e=>ce(e))),this.logger.verbose("Hydrated from remote")}return yield this.settingsStore._setCachedPrompts(e),Oe.Ok(e)}))}}var ct=(e=>(e.SLIDE="SLIDE",e.PUBLISHER_CUSTOM="PUBLISHER_CUSTOM",e.NATIVE="NATIVE",e))(ct||{}),dt=(e=>(e.SECONDS="seconds",e.MINUTES="minutes",e.HOURS="hours",e.DAYS="days",e.MONTHS="months",e))(dt||{}),_t=(e=>(e.TOP="top",e.BOTTOM="bottom",e))(_t||{}),ht=(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))(ht||{});function gt(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:dt.SECONDS}}}return{type:"SESSION_START"}}function pt(e){var t;return e.style!==ct.PUBLISHER_CUSTOM&&(null==(t=e.behavior.is_auto_show)||t)}var mt=(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))(mt||{}),St=(e=>(e.ENTRY="entry",e.EXIT="exit",e))(St||{});function Et(e){return`matrix(${e.scaleX}, ${e.skewY}, ${e.skewX}, ${e.scaleY}, ${e.translateX}, ${e.translateY})`}class ft{constructor(e,t){var s;I(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:[mt.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:[mt.FADE],duration_milliseconds:420}}_generateAnimationId(){return`${ft.ANIMATION_PREFIX}_${this.prompt.id}_${ue(5)}`}_animateIn(e,t){this._applyAnimation(St.ENTRY,e,t)}_animateOut(e,t){this._applyAnimation(St.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(mt.FADE)&&(n.add("opacity"),i.from.opacity=e===St.ENTRY?0:1,i.to.opacity=e===St.ENTRY?1:0);t.animations.includes(mt.ZOOM_IN)&&(n.add("transform"),e===St.ENTRY?(r.start.scaleX=0,r.start.scaleY=0):(r.end.scaleX=2,r.end.scaleY=2)),t.animations.includes(mt.ZOOM_OUT)&&(n.add("transform"),e===St.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(mt.SLIDE_DOWN)&&(n.add("transform"),e===St.ENTRY?r.start.translateY-=o:r.end.translateY+=o),t.animations.includes(mt.SLIDE_UP)&&(n.add("transform"),e===St.ENTRY?r.start.translateY+=o:r.end.translateY-=o),t.animations.includes(mt.SLIDE_RIGHT)&&(n.add("transform"),e===St.ENTRY?r.start.translateX-=a:r.end.translateX+=a),t.animations.includes(mt.SLIDE_LEFT)&&(n.add("transform"),e===St.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=Et(r.start),i.to.transform=Et(r.end),i}}class bt extends ft{constructor(e,t){super(e,null!=t?t:se._getInstance("CSSAnimationCoordinator")),I(this,"lastConfig")}_clearAnimationClassNames(e,t){const s=new RegExp(`^${ft.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-${ft.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[ft.ANIMATION_PREFIX]&&l.remove();i.addEventListener("animationend",(()=>{try{null==s||s()}catch(e){}}))}}class vt{constructor(e,t,s,i){I(this,"logger"),I(this,"animationCoordinator"),this.prompt=e,this.group=t,this.delegate=s,this.logger=null!=i?i:se._getInstance("PromptView"),this.animationCoordinator=new bt(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:_t.TOP:null!=(t=this.prompt.theme.position.desktop)?t:_t.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:[mt.FADE,this.position===_t.TOP?mt.SLIDE_DOWN:mt.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:[mt.FADE,this.position===_t.TOP?mt.SLIDE_UP:mt.SLIDE_DOWN],duration_milliseconds:420},(()=>{e.remove()}))):this.logger.warn(`Prompt ${this.prompt.id} is already hidden`)}}var yt=(e=>(e.ALLOW="allow",e.DISMISS="dismiss",e))(yt||{}),It=(e=>(e.NOT_AVAILABLE="not_available",e.OTHER_PROMPT_SHOWING="other_prompt_showing",e.ALREADY_SHOWING="already_showing",e.USER_INELIGIBLE="user_eligible",e))(It||{});const Pt=Symbol("lazy_empty_value");function Dt(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:Pt}),s.get=function(){return this[i]===Pt&&(this[i]=r.call(this)),this[i]}}var wt=Object.defineProperty,Ot=Object.getOwnPropertyDescriptor,Nt=(e,t,s,i)=>{for(var r,n=i>1?void 0:i?Ot(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&&wt(t,s,n),n};const Ct="pushly-prompt-visible";class Tt{constructor(e,t,s,i,r,n,o,a){I(this,"_promptElements",null),I(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:se._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=G(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:yt.ALLOW,is_custom_prompt:!0}})}))}_dismiss(){return N(this,null,(function*(){this._setSubscriptionDismissedClassNames(),yield this.delegate._processDispatchMessage({prompt_action:{id:this.prompt.id,type:yt.DISMISS,is_custom_prompt:!0}})}))}_setInitialSubscriptionClassName(){return N(this,null,(function*(){const e=yield this.userStore._getSubscriberStatus();e===me.DENIED?this._setDeniedClassNames():e===me.DISMISSED?this._setDismissedClassNames():e===me.SUBSCRIBED?this._setSubscribedClassNames():this._setNoSubscriptionClassNames()}))}_setPromptCompositeSubscribedClassNames(){this._setIneligibleClassNames(),this._setSubscribedClassNames(),this._promptConfig.element.classList.remove(Ct)}_setSubscriptionDismissedClassNames(){this._setIneligibleClassNames(),this._setDismissedClassNames(),this._promptConfig.element.classList.remove(Ct)}_setSubscriptionDeniedClassNames(){this._setIneligibleClassNames(),this._setDeniedClassNames(),this._promptConfig.element.classList.remove(Ct)}_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)}}Nt([Dt],Tt.prototype,"_document",1),Nt([Dt],Tt.prototype,"_defaultElementStub",1),Nt([Dt],Tt.prototype,"_promptConfig",1),Nt([Dt],Tt.prototype,"_classNames",1);var kt=Object.defineProperty,Rt=Object.getOwnPropertyDescriptor,At=(e,t,s,i)=>{for(var r,n=i>1?void 0:i?Rt(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&&kt(t,s,n),n};class Lt{constructor(e,t,s,i,r,n,o,a,l,u,c){I(this,"logger"),I(this,"isDisplayEvaluationReady",!1),I(this,"isPromptLoadingCompleted",!1),I(this,"timeInSessionTimer"),I(this,"manualShowRequestIsActive",!1),I(this,"promptViewInitializedCallbacks",[]),I(this,"allPrompts",[]),I(this,"matchedPrompt"),I(this,"activeView"),I(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 ot("prompts_tis_timer",this._handleSessionTimerDidAdvance.bind(this),1),this.logger=null!=c?c:se._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(je.WEB_PUSH_UNSUPPORTED,null!=(t=e.getErr().details)?t:"unknown"),this.setPromptViewInitializedCallbacks((t=>{t instanceof Tt&&(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(je.PROMPTS_LOAD_FAILED);const t=e.unwrap();if(!t.length)return this.logger.warn("No prompts available"),void this.debugController._debugPromptNotShown(je.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||!pt(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,It.NOT_AVAILABLE));const a=yield this._hasMetGlobalAndUserConditions(o.prompt,t);if(o.prompt.style===ct.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===ct.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!==ct.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 yt.ALLOW:{this.logger.debug("Received Prompt Allow"),this.eventManager._track(oe.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 Tt&&o._handlePermissionsResponse(t);break}case yt.DISMISS:this.logger.debug("Received Prompt Dismiss"),this.eventManager._track(oe.PROMPT_DISMISSED,{prompt_id:e.prompt_action.id}),0===a?(this.logger.debug("Setting subscriber status to NOT_DETERMINED"),yield this.userStore._setSubscriberStatus(me.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(oe.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!==ct.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.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!==ct.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),!pt(r.prompt))return;(n=r.prompt).style!==ct.PUBLISHER_CUSTOM&&"SESSION_START"===gt(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===ct.PUBLISHER_CUSTOM||(yield this.userStore._getSubscriberStatus())!==me.DENIED;const s=yield this.notificationPermissionService._getIsEligibleToPrompt();if(s.isErr()){const e=s.getErr();return(e===je.USER_PERMISSION_DENIED||e===je.USER_PERMISSION_DISMISSED||e===je.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:ve._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 v(b({},e),{displayCoordinator:"displayCoordinator"in e?e.displayCoordinator:e.prompt.style===ct.PUBLISHER_CUSTOM?yield this._buildCustomPromptView(e):this._buildPromptView(e)})}))}_buildPromptView(e){if(e.displayCoordinator instanceof vt)return e.displayCoordinator;const t=new vt(e.prompt,e.group,this);return this.promptViewInitializedCallbacks.forEach((e=>e(t))),t}_buildCustomPromptView(e){return N(this,null,(function*(){if(e.displayCoordinator instanceof Tt)return e.displayCoordinator;const t=new Tt(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,It.ALREADY_SHOWING),Oe.Err(`Prompt ${o} is already showing`)):(null==(r=null==(i=this.promptLifecycleCallbacks)?void 0:i.onPushSDKFailedToShowPrompt)||r.call(i,null,It.OTHER_PROMPT_SHOWING),Oe.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(je.PROMPT_INELIGIBLE_FCAP),e}return Oe.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,It.USER_INELIGIBLE),Oe.Err(je.PROMPT_INELIGIBLE_FCAP)):Oe.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):Oe.Ok(!0)}_evaluatePromptGroupDisplayConditions(e){switch(e[this._devicePlacement]){case"enabled":return Oe.Ok(!0);case"pass":return Oe.Ok(!1);case"disabled":return Oe.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 Oe.Ok(!1);if(Array.isArray(e.keywords)&&e.keywords.length>0){if(!this._currentPageMetaKeywords.length)return Oe.Ok(!1);if(!e.keywords.map((e=>e.trim().toLowerCase())).some((e=>this._currentPageMetaKeywords.includes(e))))return Oe.Ok(!1)}return Array.isArray(e.page_urls)&&e.page_urls.length>0?Oe.Ok(e.page_urls.some(t)):Oe.Ok(!0)}_evaluatePromptConditions(e){return N(this,null,(function*(){const t=gt(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 ht.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 ht.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(Ue(t.getTime()))/1e3>=(null!=(s=e.timeInterval.intervalSeconds)?s:0)}}}))}}At([Dt],Lt.prototype,"_devicePlacement",1),At([Dt],Lt.prototype,"_isTwoStepPromptsRequired",1);var Mt=(e=>(e.sub="sub",e.sdk="sdk",e.WORKER="w",e))(Mt||{}),Ut=(e=>(e.IDB="idb",e.COOKIE="cookie",e.LEGACY_COOKIE="legacy_cookie",e.MEM="mem",e.SESSION="session",e))(Ut||{});class xt{constructor(e,t,s){I(this,"_storageType"),I(this,"_storeName"),I(this,"_logger"),this._storageType=e,this._storeName=t,this._logger=null!=s?s:se._getInstance(`${e}${t?`:${t}`:""}`)}get _isInWorkerGlobalScope(){return Ke._isInWorkerGlobalScope}_getLastUpdatedAt(){return N(this,null,(function*(){const e=yield this._getData(U._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(U._pnStorageTypeLuaKey,t.getTime());return s.isErr()?s:Oe.Ok(t)}))}}const $t=()=>new j(B.STORAGE_NOT_AVAILABLE,null," - Cookie"),Kt=e=>new j(B.STORAGE_KEY_EMPTY,null,e),Wt=e=>new j(B.STORAGE_FAILED_TO_OPEN,e," - Cookie"),Ft=class e extends xt{constructor(t,s=se._getInstance("CookieStore")){super(Ut.COOKIE,t,s),I(this,"_preDomainConfigTempData"),e._domainKey=ve._dynamicDomainKey,e._domain=ve._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(ve._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 Oe.Err($t());const r=this._openCookie();if(r.isErr())return r;const n=r.unwrap();let o;return o=this._isUsingLegacyCookies?n[this._buildName(e)]:e===ve._pnStorageTypeLuaKey?null!=(t=n[ve._pnStorageTypeLuaKey])?t:null:null==(s=n[this._storeName])?void 0:s[e],null==o&&e!==ve._pnStorageTypeLuaKey?Oe.Err(Kt(e)):Oe.Ok({value:o,ts:null!=(i=n[ve._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===ve._pnStorageTypeLuaKey?r[e]=t:(null!=r[s=this._storeName]||(r[s]={}),r[this._storeName][e]=t),n=ve._pnCookieStorageKey,o=r),this._persist(n,o,void 0,e===ve._pnStorageTypeLuaKey),Oe.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=ve._pnCookieStorageKey,r=s),i&&this._persist(i,r,n),Oe.Ok(null)}_openCookie(){var e;let t={};try{const i=ve._pnCookieStorageKeyRegex,r=ve._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(Qe(e)))}catch(s){console.warn("Unable to decode base64 string",s)}return void 0===t&&(t=Ye(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=Wt(G(i));return this._logger.warn("Unable to open cookie",e.message),Oe.Err(e)}return Oe.Ok(t)}_persist(t,s,i,r){try{const o=null===this._storeName;o||!s||"object"!=typeof s||Array.isArray(s)||!0===r||(s[ve._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:ve._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(G(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}};I(Ft,"_domainKey"),I(Ft,"_domain");let Bt=Ft;class Vt{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]:de(String(s))in t?t[de(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)}`)))}})}}class Gt{constructor(e,t,s,i,r,n){I(this,"iid",ue(5)),I(this,"domainConfigProvider"),I(this,"notificationPermissionService",null),I(this,"promptsController",null),I(this,"_logger"),I(this,"isLoading"),I(this,"_isLoaded"),I(this,"_isExited"),I(this,"_isEnabled"),I(this,"_domainKey"),I(this,"_loadConfig"),I(this,"pageViewProcessor"),I(this,"_pushSdkLifecycleCallbacks"),I(this,"_permissionLifecycleCallbacks"),I(this,"_appMessageLifecycleCallbacks"),I(this,"promptLifecycleCallbacks"),I(this,"_onLoadedCallbacks"),I(this,"_postConfigActionsQueue"),I(this,"legacyEventCallbacks"),this.eventManager=e,this.settingsStore=t,this.userStore=s,this.sessionManager=i,this.debugController=r,this.settingsStore=t,this.userStore=s,this._logger=null!=n?n:se._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=G(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 Vt(this.debugController,this._logger),r=null!=(s=null!=(t=ve._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===me.SUBSCRIBED,e!==me.NOT_DETERMINED&&(o.subscriberState=e)}catch(a){}return{domainKey:this.loadConfig.domainKey,env:i.get("env"),app:i.get("app"),domain:i.get("domain",b({},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=ue(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?Oe.Err(new j(B.DUPLICATE_SDK_DETECTED)):e.isLoaded?Oe.Err(new j(B.SDK_ALREADY_LOADED)):Oe.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,Bt._setDomainKey(e.domainKey),this.sessionManager._start(),this._loadConfig=e,ge._loadConfig=e,function(e){return Object.keys(e).some((e=>!we.includes(e)))}(e)&&this.debugController._debugUnknownConfigurationKeys(e),this._domainKey=e.domainKey,this.domainConfigProvider=new xe(e.domainKey,this.settingsStore);try{yield this._load()}catch(s){const e=G(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(G(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 j(B.DOMAIN_CONFIGURATION_LOAD_FAILED,e.getErr())))}const t=e.unwrap();Bt._setDomain(t),ge._domainKey=this._domainKey,yield this._handleDomainConfigInitialLoadCompleted(t)}))}_logInitializingState(){return N(this,null,(function*(){this._logger.debug(`Initializing SDK v${ve._libraryVersion} (${ve._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: ${fe(e)}`;e===me.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(je.HOST_NOT_WHITELISTED),void(yield this._handleExit(new j(B.HOST_NOT_ALLOWED)));if(yield this._dispatchLegacyEventCallbacks(re.LOADED),this.loadConfig.externalId&&(yield this.userStore._setExternalId(this.loadConfig.externalId)),We(e))this._logger.debug("[Event Only Mode] Skipping notification & prompt services");else{this._logger.debug("Starting notification services"),this.notificationPermissionService=new qe(e,new nt(this._loadConfig,e),this.eventManager,this.userStore,this),this.promptsController=new Lt(this.loadConfig,e,new ut(e.domain_key,this.settingsStore),this.notificationPermissionService,this.userStore,this.settingsStore,this.sessionManager,this.eventManager,this.debugController,this);let s=null;const i=yield qe._getWebPushSupport();if(i.isErr())s=i.getErr(),this.onPushSDKDidNotDetectWebPushSupport(s);else{this.onPushSDKDidDetectWebPushSupport(),yield this._logUserInfo(),yield this.userStore._synchronizeData(),yield this._logCurrentSubscriptionStatus();try{yield this.userStore._getAnonymousId().then((e=>{ge._anonymousId=e})).catch()}catch(t){}const e=yield this.notificationPermissionService._init();if(e.isErr()){const t=e.getErr();t instanceof j&&t._isExitException?(s=t,t.code===B.PUSH_WORKER_REGISTRATION_EXCEPTION&&this.debugController._debugPromptNotShown(je.SW_INSTALL_FAILED)):this._logger.warn(t.message)}}if(this.promptsController._setIsWebPushSupported(i),s)return void(yield this._handleExit(s));yield this.notificationPermissionService._synchronize()}this.pageViewProcessor=lt._init(e,this.eventManager,this.userStore,this.sessionManager.transient.store),function(e){return e.flags.includes(U._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((()=>ge._getProfileLanguageEvent(t))).then((e=>this.eventManager._track(e)))),(!s||i&&s!==i)&&r.push(this.userStore._setTimeZone(i).then((()=>ge._getProfileTimeZoneEvent(i))).then((e=>this.eventManager._track(e)))),yield Promise.all(r).catch((e=>this._logger.error(e)))}catch(e){const t=G(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(G(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(oe.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(ve._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:`,G(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(oe.SDK_IMPRESSION)})))().then()}onPushSDKDidDetectWebPushSupport(){var e,t;null==(t=null==(e=this._pushSdkLifecycleCallbacks)?void 0:e.onPushSDKDidDetectWebPushSupport)||t.call(e),this._dispatchLegacyEventCallbacks(re.WEB_PUSH_SUPPORTED)}onPushSDKDidNotDetectWebPushSupport(e){var t,s;null==(s=null==(t=this._pushSdkLifecycleCallbacks)?void 0:t.onPushSDKDidNotDetectWebPushSupport)||s.call(t),this._dispatchLegacyEventCallbacks(re.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(re.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(re.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(re.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(re.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(re.PROMPT_ALLOWED,r):this._dispatchLegacyEventCallbacks(re.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(re.PERMISSION_SHOWN,{}),this._dispatchLegacyEventCallbacks(re.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 He.GRANTED:this._dispatchLegacyEventCallbacks(re.PERMISSION_ALLOWED,{}),this._dispatchLegacyEventCallbacks(re.LEGACY_PERMISSION_ALLOWED,{});break;case He.DENIED:this._dispatchLegacyEventCallbacks(re.PERMISSION_DENIED,{});break;case He.DISMISSED:this._dispatchLegacyEventCallbacks(re.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;switch(null==(s=null==(t=this._permissionLifecycleCallbacks)?void 0:t.onPushSDKDidReceivePermissionStatusChange)||s.call(t,e),e){case He.GRANTED:case He.DENIED:null==(i=this.promptsController)||i._disable();break;case He.DISMISSED:null==(r=this.promptsController)||r._enable()}}))}}const Ht=()=>new j(B.STORAGE_NOT_AVAILABLE,null," - IndexedDB"),jt=()=>new j(B.IDB_INVALID_STORE_NAME),qt=()=>new j(B.IDB_BLOCKED);class Yt extends xt{constructor(e,t=se._getInstance("IdbStore")){super(Ut.IDB,e,t)}get _isAvailable(){return Ke._getIsEnvBaseSupported()[0]&&!!this._storeName&&!!this._indexedDB}get _indexedDB(){return Ke._scope.indexedDB}get _isSafari(){return Ke._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!==U._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(Oe.Err(Ht()));if(!this._storeName)return void e(Oe.Err(jt()));const t=this._indexedDB.open("pn_store",1);t.onerror=s=>{e(Oe.Err(t.error||new Error(s)))},t.onsuccess=t=>{this._handleOnOpenSuccess(t.target.result,(t=>{e(Oe.Ok(t))}))},t.onupgradeneeded=e=>{this._handleOnUpgradeNeeded(e.target.result)},t.onblocked=()=>{e(Oe.Err(qt()))}}))}))}_handleOnOpenSuccess(e,t){e.onversionchange=()=>{this._handleOnVersionChange(e)},this._isSafari&&this._selfHeal(e),t(e)}_handleOnUpgradeNeeded(e){e.objectStoreNames.contains(Mt.sub)||e.createObjectStore(Mt.sub,{keyPath:"k"}),e.objectStoreNames.contains(Mt.sdk)||e.createObjectStore(Mt.sdk,{keyPath:"k"}),e.objectStoreNames.contains(Mt.WORKER)||e.createObjectStore(Mt.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===U._pnStorageTypeLuaKey?t[1]:l});break;case"delete":d=u.delete(c)}a.onabort=e=>{i(Oe.Err(d.error||new Error(e)))},a.oncomplete=()=>{var r,n,o,a;let l;switch(e){case"read":l=Oe.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=Oe.Ok(t[1]);break;case"delete":l=Oe.Ok(null)}i(l),null==s||s(l)}}))}))}_updateLua(){this._executeTransaction("write",[U._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(Mt).every((t=>e.objectStoreNames.contains(t)))||this._handleOnUpgradeNeeded(e)}}const Qt=()=>new j(B.STORAGE_NS_REQUIRED,null,"Mem");class zt extends xt{constructor(e,t=se._getInstance("MemStore")){super(Ut.MEM,e,t),I(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 Oe.Err(Qt());const r=null==(t=this._db[this._storeName])?void 0:t[e];return Oe.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()},Oe.Ok(t)):Oe.Err(Qt())}))}_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],Oe.Ok(null)):Oe.Err(Qt())}))}}const Xt=()=>new j(B.STORAGE_NOT_AVAILABLE,null," - Session"),Zt=e=>new j(B.STORAGE_KEY_EMPTY,null,e),Jt=e=>new j(B.STORAGE_FAILED_TO_OPEN,e," - Session");class es extends xt{constructor(e,t=se._getInstance("SessionStore")){super(Ut.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 Oe.Err(Xt());const t=this._openStore();if(t.isErr())return t;const s=t.unwrap()[e]||null;return null==s&&e!==U._pnStorageTypeLuaKey?Oe.Err(Zt(e)):Oe.Ok(s)}))}_setData(e,t){return N(this,null,(function*(){if(!this._isAvailable)return Oe.Err(Xt());const s=this._openStore();if(s.isErr())return s;const i=s.unwrap();return i[e]=e===U._pnStorageTypeLuaKey?t:{value:t,ts:(new Date).getTime()},this._persist(i),Oe.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)),Oe.Ok(null)}))}_openStore(){var e;let t={};if(!this._storeName)return Oe.Err(Jt(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=Jt(G(s));return this._logger.warn(e.message),Oe.Err(e)}return Oe.Ok(t)}_persist(e){try{e&&"object"==typeof e&&!Array.isArray(e)&&(e[U._pnStorageTypeLuaKey]=(new Date).getTime()),this._store.setItem(this._storeName,JSON.stringify(e))}catch(t){this._logger.error(G(t))}}storageAvailable(){let e;try{e=this._store;const t=U._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 ts=e=>new Error(`No available stores found for ${e.join(", ")}`),ss=e=>new j(B.STORAGE_KEY_EMPTY,null,e);class is{constructor(e,t,s=se._getInstance("StorageManager")){I(this,"_storeName"),I(this,"_logger"),I(this,"_stores"),I(this,"_preferredStores"),this._storeName=e,this._preferredStores=t,this._logger=s,this._stores=Object.fromEntries(this._preferredStores.map((t=>{switch(t){case Ut.IDB:return[Ut.IDB,new Yt(e)];case Ut.COOKIE:return[Ut.COOKIE,new Bt(e)];case Ut.LEGACY_COOKIE:return[Ut.LEGACY_COOKIE,new Bt(null)];case Ut.MEM:return[Ut.MEM,new zt(e)];case Ut.SESSION:return[Ut.SESSION,new es(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?Oe.Err(ts(t)):Oe.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:Oe.Ok(s.unwrap().value)}))}_getDataSync(e,t){const s=this._getTimestampedDataSync(e,t);return s.isErr()?s:Oe.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)),Oe.Ok(i[0])):Oe.Err(ss(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?Oe.Ok(i[0]):Oe.Err(ss(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,Oe.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,Oe.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?(et._dispatch(et.EventType.ERROR,s.getErr()),this._logger.warn(s.getErr().message),s):Oe.Err(ts(t))}return e.forEach((e=>{(null==e?void 0:e.isErr())&&et._dispatch(et.EventType.ERROR,e.getErr())})),Oe.Ok(s)}}var rs=(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))(rs||{});const ns={id:"pushly.user_puuid",t:"_pntx",xid:"_pnxd",ss:"_pnss",udr:"_pnudr",dse:"_pnpdm"};var os=(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))(os||{}),as=(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))(as||{});function ls(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 us=[Ut.IDB,Ut.MEM],cs=[Ut.SESSION,Ut.MEM];class ds extends is{constructor(e){super(Mt.sdk,[Ut.MEM,Ut.IDB,Ut.SESSION],null!=e?e:se._getInstance("SettingsStore"))}_getDomainConfig(){return N(this,null,(function*(){return(yield this._getTimestampedData(os.domainConfig,{preferredStores:us})).unwrapOrNull()}))}_setDomainConfig(e){return N(this,null,(function*(){return(yield this._setData(os.domainConfig,e,{preferredStores:us})).unwrapOrNull()}))}_getCachedEvents(){return N(this,null,(function*(){return(yield this._getData(os.eventsCache,{preferredStores:us})).unwrapOr([])}))}_setCachedEvents(e){return N(this,null,(function*(){return(yield this._setData(os.eventsCache,e,{preferredStores:us})).unwrapOr([])}))}_getCachedPrompts(){return N(this,null,(function*(){return(yield this._getTimestampedData(os.PROMPTS_CACHE,{preferredStores:cs})).unwrapOrNull()}))}_setCachedPrompts(e){return N(this,null,(function*(){return(yield this._setData(os.PROMPTS_CACHE,e,{preferredStores:cs})).unwrapOrNull()}))}_getViewedPromptOccurrencesCount(){return N(this,null,(function*(){return ls(yield this._getViewedPromptOccurrencesMap(),((e,[,t])=>e+t.length),0)}))}_getViewedPromptOccurrencesMap(){return N(this,null,(function*(){return(yield this._getData(os.PROMPTS_OCCURRENCES_MAP,{preferredStores:us})).unwrapOr(new Map)}))}_dropViewedPromptOccurrencesNotInInterval(e){return N(this,null,(function*(){const t=ls(yield this._getViewedPromptOccurrencesMap(),((t,[s,i])=>{const r=i.filter((t=>Math.abs(Ue(t))<=e));return r.length>0&&t.push([s,r]),t}));yield this._setData(os.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(os.PROMPTS_OCCURRENCES_MAP,s)}))}_getLastViewedPromptId(){return N(this,null,(function*(){return(yield this._getData(os.PROMPTS_LAST_VIEWED,{preferredStores:us})).unwrapOrNull()}))}_setLastViewedPromptId(e){return N(this,null,(function*(){return(yield this._setData(os.PROMPTS_LAST_VIEWED,e,{preferredStores:us})).unwrapOrNull()}))}_setLastMatchedPromptId(e){return N(this,null,(function*(){return(null===e?yield this._removeData(as.SESSION_READY_PROMPT):yield this._setData(as.SESSION_READY_PROMPT,e)).unwrapOrNull()}))}_getLastMatchedPromptId(){return N(this,null,(function*(){return(yield this._getData(as.SESSION_READY_PROMPT)).unwrapOrNull()}))}}const _s=[Ut.COOKIE,Ut.IDB,Ut.MEM],hs=[Ut.IDB,Ut.MEM],gs=[Ut.SESSION,Ut.MEM];class ps extends is{constructor(e,t=se._getInstance("UserStore")){super(Mt.sub,[Ut.MEM,Ut.IDB,Ut.COOKIE,Ut.SESSION],t),I(this,"_legacyStorage"),this._legacyStorage=e}_synchronizeData(){return N(this,null,(function*(){yield(()=>N(this,null,(function*(){const e=this._getAvailableStores([Ut.IDB,Ut.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=[rs.anonymousId,rs.subscriberStatus,rs.isInDeletedState,rs.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!==ss(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===me.DISMISSED&&(null===t||(new Date).getTime()>=t)?(this._logger.info("Removing subscriber dismissed state"),yield Promise.all([this._removeData(rs.DISMISSED_STATUS_EXPIRATION),this._setSubscriberStatus(me.NOT_DETERMINED)])):e!==me.DISMISSED&&null!==t&&(this._logger.verbose("Removing subscriber dismissed expiration key"),yield this._removeData(rs.DISMISSED_STATUS_EXPIRATION))}))}_getAnonymousId(){return N(this,null,(function*(){let e=(yield this._getData(rs.anonymousId,{preferredStores:_s})).unwrapOrNull();if(!e){const t=this._legacyStorage._getAnonymousId(),s=yield this._setData(rs.anonymousId,null!=t?t:ue(),{preferredStores:_s});s.isOk()&&(e=s.unwrap(),this._removeLegacyKey(ns[rs.anonymousId]))}return e}))}_getAnonymousIdSync(){let e=this._getDataSync(rs.anonymousId,{preferredStores:[Ut.COOKIE]}).unwrapOrNull();if(!e){const t=this._legacyStorage._getAnonymousId(),s=this._setDataSync(rs.anonymousId,null!=t?t:ue(),{preferredStores:[Ut.COOKIE]});s.isOk()&&(e=s.unwrap())}return e}_getLocale(){return N(this,null,(function*(){return(yield this._getData(rs.locale,{preferredStores:hs})).unwrapOrNull()}))}_setLocale(e){return N(this,null,(function*(){return(yield this._setData(rs.locale,e,{preferredStores:hs})).unwrapOrNull()}))}_getTimeZone(){return N(this,null,(function*(){return(yield this._getData(rs.timeZone,{preferredStores:hs})).unwrapOrNull()}))}_setTimeZone(e){return N(this,null,(function*(){return(yield this._setData(rs.timeZone,e,{preferredStores:hs})).unwrapOrNull()}))}_getExternalId(){return N(this,null,(function*(){let e=(yield this._getData(rs.externalId,{preferredStores:hs})).unwrapOrNull();if(!e){const t=this._legacyStorage._getExternalId();if(t){(yield this._setData(rs.externalId,t,{preferredStores:hs})).isOk()&&(e=t,this._removeLegacyKey(ns[rs.externalId]))}}return e}))}_getExternalIdSync(){let e=this._getDataSync(rs.externalId,{preferredStores:[Ut.COOKIE]}).unwrapOrNull();if(!e){const t=this._legacyStorage._getExternalId();if(t){this._setDataSync(rs.externalId,t,{preferredStores:[Ut.COOKIE]}).isOk()&&(e=t)}}return e}_setExternalId(e){return N(this,null,(function*(){return(yield this._setData(rs.externalId,e,{preferredStores:hs})).isOk()}))}_removeExternalId(){return N(this,null,(function*(){return(yield this._removeData(rs.externalId,{preferredStores:hs})).isOk()}))}_getIsSubscribed(){return N(this,null,(function*(){return(yield this._getSubscriberStatus())===me.SUBSCRIBED}))}_getSubscriberStatus(){return N(this,null,(function*(){const e=yield this._getData(rs.subscriberStatus,{preferredStores:_s});let t=me.NOT_DETERMINED;const s=e.unwrapOrNull();if(null===s){const e=this._legacyStorage._getSubscriberStatus(),s=yield this._setData(rs.subscriberStatus,Se[null!=e?e:t],{preferredStores:_s});s.isOk()&&(t=Ee(s.unwrap())),e&&this._removeLegacyKey(ns[rs.subscriberStatus])}else t=Ee(s);return t}))}_getIsUserInSoftUnsubscribedState(){return N(this,null,(function*(){return!!(yield this._getData(rs.IS_USER_IN_SOFT_UNSUBSCRIBE_STATE,{preferredStores:_s})).unwrapOrNull()}))}_setIsUserInSoftUnsubscribedState(){return N(this,null,(function*(){yield this._setData(rs.IS_USER_IN_SOFT_UNSUBSCRIBE_STATE,1,{preferredStores:_s})}))}_unsetIsUserInSoftUnsubscribedState(){return N(this,null,(function*(){yield this._removeData(rs.IS_USER_IN_SOFT_UNSUBSCRIBE_STATE,{preferredStores:_s})}))}_getSubscriberStatusSync(){const e=this._getDataSync(rs.subscriberStatus,{preferredStores:[Ut.COOKIE]});let t=me.NOT_DETERMINED;const s=e.unwrapOrNull();if(null===s){const e=this._legacyStorage._getSubscriberStatus(),s=this._setDataSync(rs.subscriberStatus,Se[null!=e?e:t],{preferredStores:[Ut.COOKIE]});s.isOk()&&(t=Ee(s.unwrap()))}else t=Ee(s);return t}_setSubscriberStatus(e){return N(this,null,(function*(){return(yield this._setData(rs.subscriberStatus,Se[e],{preferredStores:_s})).isOk()}))}_setSubscriberStatusDismissed(e){return N(this,null,(function*(){if(!(yield this._setSubscriberStatus(me.DISMISSED)))return this._logger.warn("Unable to set subscriber dismissed status. Skipping dismissed expiration."),!1;const t=yield this._setData(rs.DISMISSED_STATUS_EXPIRATION,(new Date).getTime()+1e3*e,{preferredStores:_s});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(rs.DISMISSED_STATUS_EXPIRATION,{preferredStores:_s})).unwrapOrNull();if(!e){const t=yield this._legacyStorage._getDismissedStatusExpiration();t&&(e=t,yield this._setData(rs.DISMISSED_STATUS_EXPIRATION,t,{preferredStores:_s}))}return e}))}_getIsInDeletedState(){return N(this,null,(function*(){let e=!1;const t=(yield this._getData(rs.isInDeletedState,{preferredStores:_s})).unwrapOrNull();if(null!==t)e=!!t;else{const t=this._legacyStorage._getIsInDeletedState(),s=(null!=t?t:e)?1:0,i=yield this._setData(rs.isInDeletedState,s,{preferredStores:_s});i.isOk()&&(e=!!i.unwrap(),this._removeLegacyKey(ns[rs.isInDeletedState]))}return e}))}_setIsInDeletedState(e){return N(this,null,(function*(){return(yield this._setData(rs.isInDeletedState,e?1:0,{preferredStores:_s})).isOk()}))}_getLastPageViewed(){return N(this,null,(function*(){return(yield this._getData(rs.LAST_PAGE_VIEWED,{preferredStores:gs})).unwrapOrNull()}))}_setLastPageViewed(e){return N(this,null,(function*(){return(yield this._setData(rs.LAST_PAGE_VIEWED,e,{preferredStores:gs})).isOk()}))}_removeLegacyKey(e){this._logger.debug(`!! Legacy key removal DISABLED !! key: ${e}`)}}class ms extends is{constructor(e){super(null,[Ut.LEGACY_COOKIE],null!=e?e:se._getInstance("LegacyStoreManager"))}_getAnonymousId(){return this._getDataSync(ns[rs.anonymousId]).unwrapOrNull()}_getExternalId(){return this._getDataSync(ns[rs.externalId]).unwrapOrNull()}_getSubscriberStatus(){let e=null;const t=this._getDataSync(ns[rs.subscriberStatus]).unwrapOrNull();return t&&(e=Ee(t)),e}_getIsInDeletedState(){return this._getDataSync(ns[rs.isInDeletedState]).unwrapOrNull()}_getDismissedStatusExpiration(){return N(this,null,(function*(){return(yield this._getData(ns[rs.DISMISSED_STATUS_EXPIRATION])).unwrapOrNull()}))}}class Ss{constructor(e,t){I(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=ve._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 Es{constructor(e){I(this,"timer"),this.store=e,this.timer=new ot("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 fs{constructor(e){I(this,"transient"),this.transient=new Es(e)}_start(){this.transient._start()}_stop(){this.transient._stop()}}class bs extends is{constructor(e){super(Mt.sdk,[Ut.SESSION,Ut.MEM],null!=e?e:se._getInstance("SessionStore"))}_setSessionStart(e){return N(this,null,(function*(){return(yield this._setData(as.SESSION_START,e)).unwrapOrNull()}))}_getSessionStart(){return N(this,null,(function*(){const e=(yield this._getData(as.SESSION_START)).unwrapOrNull();return e?new Date(e):null}))}_getCurrentPageViewStart(){return N(this,null,(function*(){const e=(yield this._getData(as.SESSION_PAGE_VIEW_START)).unwrapOrNull();return e?new Date(e):null}))}_getSessionPageViewCount(){return N(this,null,(function*(){return(yield this._getData(as.SESSION_PAGE_VIEWS)).unwrapOr(0)}))}_getSessionRuntimeSeconds(){return N(this,null,(function*(){return(yield this._getData(as.SESSION_RUNTIME)).unwrapOr(0)}))}_setSessionRuntimeSeconds(e){return N(this,null,(function*(){return(yield this._setData(as.SESSION_RUNTIME,e)).unwrapOrNull()}))}_incrementSessionPageViewCount(){return N(this,null,(function*(){const e=yield this._getSessionPageViewCount();yield Promise.all([this._setData(as.SESSION_PAGE_VIEWS,e+1),this._setData(as.SESSION_PAGE_VIEW_START,(new Date).getTime())])}))}}class vs{constructor(e,t){I(this,"debugPanelElement"),this.settingsStore=e,this.eventManager=t}_getIsEventsEnabled(){return N(this,null,(function*(){let e=[];const t=ve._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(ve._sdkDebugEventsEnabledFlag)}))}_shouldShowDebugPanel(){return this._currLocation&&/(^|[?&#])(push(ly)?_debug(73485)?)=1(?=[&#]|$)/i.test(this._currLocation.href)}get _currLocation(){return Ke._location}get _document(){return Ke._document}get _clipboard(){return Ke._navigator.clipboard}get _userAgent(){return Ke._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=`Push User Id: ${e}, Subscriber State: ${t}, External ID: ${i}, Endpoint: ${s}, Browser Permissions: ${r}, UserAgent: ${this._userAgent}`.trim(),d=`pushly_debug_handle_${ue(12)}`,_=`pushly_debug_close_${ue(12)}`,h=`pushly_debug_copy_${ue(12)}`,g=`pushly_debug_shadow_${ue(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 Push User 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===_&&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===h&&v.addEventListener("click",b),this.debugPanelElement||(u.body.appendChild(p),this.debugPanelElement=p)}))}_debug(e,t={},s=!1){(()=>N(this,null,(function*(){ae(e)&&(s||(yield this._getIsEventsEnabled()))&&this.eventManager._track(e,t)})))().then()}_debugPromptNotShown(e,t){const s={[ve._tevDataPromptNotShownKey]:e};return t&&(s[ve._tevFieldErrorMessage]=t),this._debug(oe.PROMPT_NOT_SHOWN,s)}_debugUnknownAsyncBrowserCommand(e){return this.eventManager._track(new j(B.UNKNOWN_ASYNC_COMMAND,null,String(e[0])),{async_command:e})}_debugUnknownConfigurationKeys(e){return this.eventManager._track(new j(B.UNKNOWN_CONFIG_KEYS),{push_sdk_config:e})}_debugUnknownContextKey(e){return this.eventManager._track(new j(B.UNKNOWN_CONTEXT_KEY,null,e),{context_key:e})}_debugUnknownPromptMessage(e){return this.eventManager._track(new j(B.UNKNOWN_PROMPT_MESSAGE),{prompt_message:e})}}class ys{constructor(e={},t){I(this,"_logger"),I(this,"_eventQueue"),I(this,"_trackedEventQueueTimer"),I(this,"_isEventQueueFlushing"),this.asyncProvider=e,this._logger=null!=t?t:se._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(j._isSuppressed(e))return;s=yield ge._getErrorEvent(e),s.data.logs=this._logger._getLogs(!0).splice(-10).reverse(),t&&(s.data[U._tevFieldErrorContext]=t)}else s="string"==typeof e?yield ge._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>=U._eventQueueMaxSize&&(this._eventQueue=this._eventQueue.slice(0,U._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=>ge._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)||ae(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)?U._kApiAllowUrl:U._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()}))}),U._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,U._kApiEventsUrl)).isErr()&&this._eventQueue.push(...e)}))}_process(e,t){return N(this,null,(function*(){let s;yield this._preloadTrackedEventUtilProperties(),e.forEach((e=>{ge._prepareSendEvent(e)}));const i=e.map((e=>{const t=e,{sendAttemptCount:i,jxms:r,data:n}=t,o=y(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 Le(Me.POST,t,n,{jitterMillis:s}),this._logger.debug(`Prepared ${e.length} event(s):`,n)}catch(n){const e=G(n);return this._logger.error(`Unable to prepare events: ${e.message}`),Oe.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"),Oe.Ok(!0))}return this._logger.verbose("No request to process"),Oe.Ok(!1)}))}_getNextBatch(){return N(this,null,(function*(){if(!(this._eventQueue.length>U._eventQueueFlushTriggerSize?U._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([ge._domainId?null:null==(s=null==(t=(e=this.asyncProvider)._getDomainId)?void 0:t.call(e))?void 0:s.then((e=>{ge._domainId=e})),ge._anonymousId?null:null==(n=null==(r=(i=this.asyncProvider)._getAnonymousId)?void 0:r.call(i))?void 0:n.then((e=>{ge._anonymousId=e})),ge._token?null:null==(l=null==(a=(o=this.asyncProvider)._getToken)?void 0:a.call(o))?void 0:l.then((e=>{e&&(ge._token=e)}))]).catch()}))}}class Is extends ys{_trackEvent(e){return N(this,null,(function*(){return this._ensurePageUrlProperty(e),(t=Is.prototype,s=this,i="_trackEvent",E(p(t),i,s)).call(this,e);var t,s,i}))}_ensurePageUrlProperty(e){var t;(t=e.action,[oe.PROMPT_SHOWN,oe.PROMPT_ACCEPTED,oe.PROMPT_DISMISSED,oe.PROMPT_NOT_SHOWN,oe.PERMISSION_SHOWN,oe.PERMISSION_ACCEPTED,oe.PERMISSION_DISMISSED,oe.PERMISSION_DENIED,oe.PERMISSION_CHANGED].includes(t))&&(e.data[ve._tevDataPageUrlKey]||(e.data[ve._tevDataPageUrlKey]=Be._location.href))}}u=new WeakMap,c=new WeakMap;let Ps=class e{constructor(e,t,s,i,r,n){I(this,"UserProfile"),I(this,"EComm"),I(this,"PushNotifications"),I(this,"Prompts"),w(this,u,void 0),w(this,c,void 0),O(this,u,e),O(this,c,null!=n?n:se._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 ds,i=new ps(new ms),r=new bs,n=new Ss(s,i),o=new Is(n);et._setEventManager(o);const a=new Gt(o,s,i,new fs(r),new vs(s,o)),l=new pe(a),u=new Pe(a),c=new be(a),d=new De(a);return n.setUserProfileModule(l),new e(a,l,u,c,d)}setConfiguration(e){D(this,u)._setConfiguration(e)}getConfiguration(){var e;return null!=(e=D(this,u).loadConfig)?e:null}get version(){return ve._libraryVersion}get iid(){return D(this,u).iid}get isLoaded(){return D(this,u).isLoaded}registerPushSDKLifecycleCallbacks(e){D(this,u)._registerPushSdkLifecycleCallbacks(e)}registerPermissionLifecycleCallbacks(e){D(this,u)._registerPermissionLifecycleCallbacks(e)}registerAppMessageLifecycleCallbacks(e){D(this,u)._registerAppMessageLifecycleCallbacks(e)}registerPromptLifecycleCallbacks(e){D(this,u)._registerPromptLifecycleCallbacks(e)}get logLevel(){return D(this,c).logLevel}set logLevel(e){D(this,c).logLevel=e}debug(e=!0){return N(this,null,(function*(){yield D(this,u)._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 D(this,c)._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 D(this,u)._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 ie.LOAD:this.setConfiguration(e[1]);break;case ie.REQUEST_USER_DELETION:this.UserProfile.requestUserDeletion();break;case ie.DEBUG:D(this,u)._toggleDebugPanel();break;case ie.CONFIRM_CONSENT:break;case ie.EXTERNAL_ID:this.UserProfile.setExternalId(e[1]);break;case ie.DEREGISTER_EXTERNAL_ID:this.UserProfile.unsetExternalId();break;case ie.PROFILE:this.UserProfile.set(e[1]);break;case ie.PROFILE_APPEND:Object.entries(e[1]).forEach((([e,t])=>{this.UserProfile.append(e,t)}));break;case ie.PROFILE_REMOVE:Object.entries(e[1]).forEach((([e,t])=>{this.UserProfile.remove(e,t)}));break;case ie.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())),D(this,u)._executeWhenConfiguredIfEnabled((()=>{D(this,c).verbose(`Sending ${i.length} tag${i.length>1?"s":""} for ${t}`),D(this,u).eventManager._track(oe.PAGE_TAG_VISIT,{[ve._tevDataPageUrlKey]:t,[ve._tevDataPageTagsKey]:i})}));break}case ie.SHOW_PROMPT:if(1===e.length)this.PushNotifications.showPermissionPrompt();else{const{id:t,checkEligibility:s}=e[1];if(null==t)return void D(this,c).warn(`${ie.SHOW_PROMPT} command missing Prompt ID.`);this.PushNotifications.showPermissionPrompt(t,{skipEligibilityCheck:!s})}break;case ie.PAUSE_PUSH_NOTIFICATIONS:this.PushNotifications.pause();break;case ie.RESUME_PUSH_NOTIFICATIONS:this.PushNotifications.resume();break;case ie.GET_PUSH_NOTIFICATIONS_PAUSED_STATE:this.PushNotifications.getIsPaused().then(e[1]);break;case ie.VIEW_ITEM:{const t="products"in e[1]?e[1].products:e[1].events;Array.isArray(t)&&D(this,u)._executeWhenConfiguredIfEnabled((()=>{D(this,c).verbose(`Adding ${t.length} item${t.length>1?"s":""} to viewed items`),D(this,u).eventManager._track(oe.VIEW_ITEM,e[1])}));break}case ie.ADD_TO_CART:{const t="products"in e[1]?e[1].products:e[1].events;Array.isArray(t)&&D(this,u)._executeWhenConfiguredIfEnabled((()=>{D(this,c).verbose(`Adding ${t.length} item${t.length>1?"s":""} to cart`),D(this,u).eventManager._track(oe.ADD_TO_CART,e[1])}));break}case ie.UPDATE_CART:{const t="products"in e[1]?e[1].products:e[1].events;Array.isArray(t)&&D(this,u)._executeWhenConfiguredIfEnabled((()=>{t.length?D(this,c).verbose(`Updating cart with ${t.length} item${t.length>1?"s":""}.`):D(this,c).verbose("Clearing cart"),D(this,u).eventManager._track(oe.UPDATE_CART,e[1])}));break}case ie.PURCHASE:if(1===e.length)D(this,c).verbose("Tracking purchase"),D(this,u).eventManager._track(oe.PURCHASE);else{let t;"products"in e[1]&&(t=e[1].products=e[1].products.map((e=>Ie(e,ye.PRODUCT)))),"events"in e[1]&&(t=e[1].events=e[1].events.map((e=>Ie(e,ye.EVENT)))),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}`),D(this,c).verbose(s.join(" ")),D(this,u).eventManager._track(oe.PURCHASE,e[1])}break;case`on_${re.LOADED}`:case`on_${re.WEB_PUSH_SUPPORTED}`:case`on_${re.WEB_PUSH_UNSUPPORTED}`:case`on_${re.READY}`:case`on_${re.PROMPT_ELIGIBLE}`:case`on_${re.PROMPT_INELIGIBLE}`:case`on_${re.PROMPT_SHOWN}`:case`on_${re.PROMPT_DISMISSED}`:case`on_${re.PROMPT_ALLOWED}`:case`on_${re.PERMISSION_SHOWN}`:case`on_${re.PERMISSION_ALLOWED}`:case`on_${re.PERMISSION_DENIED}`:case`on_${re.PERMISSION_DISMISSED}`:{const s=e[0].replace(/^on_/,"");"function"==typeof e[1]?D(this,u)._registerLegacyEventCallback(s,e[1],t):D(this,c).warn("Invalid SDK event handler callback specified:",e);break}default:!ne.includes(e[0])&&D(this,u).debugController&&D(this,u).debugController._debugUnknownAsyncBrowserCommand(e),D(this,c).warn("Unknown SDK command received:",e)}}catch(i){const e=G(i);D(this,c).error(e),D(this,u).eventManager._track(e)}}};const Ds=Ps.getInstance();let ws;try{ws=se._getInstance()}catch(Os){ws=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)Ds.push(t);window.PushlySDK=Ds}else ws.warn("PushlySDK must be loaded from the top frame or a sourceless iFrame")}catch(Ns){ws.warn("Unable to assign global PushlySDK"),ws.error(Ns)}return e.PushSDK=Ds,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({}); (function(){try{self._PN_IDK_="9wtpSygI7yeyxz5mXOOehWTI11kjKq0OPI7a"}catch(_){}})(); (function(){try{self._PN_IDC_={"id":23272,"name":"thekitchn.com","domain_key":"9wtpSygI7yeyxz5mXOOehWTI11kjKq0OPI7a","time_zone":"US/Eastern","integration_type":"direct","custom_allow_domain":null,"frequency_caps":null,"global_prompt_settings":{},"flags":["FEAT_NATIVE_ANDROID_NOTIFICATIONS_FG_DISPLAY","FEAT_NATIVE_IOS_NOTIFICATIONS_FG_DISPLAY","USE_ISOLATED_COOKIE_STORAGE_LOCATION"],"custom_sdk_package_name":null,"vapid_public_key":"BAGq_1kGJITT3PD-pFqSOpF-XYsrxY4gGZHtIgp9alsYMG1VSXw_FvmGlUVkXxp5ZI7Rk177ghtyPaPgBTo6wQw","additional_subscription_data":null,"whitelist_domains":["www.thekitchn.com"],"sdk_event_only_domains":[],"apns_configuration":{"is_active":false},"ecomm_config":null,"domain_integrations":null}}catch(_){}})(); (function(){try{self._PN_IPG_=[{"id":36651,"domain":23272,"name":"System","priority":0,"conditions":{"display":{"desktop":"enabled","mobile":"enabled"},"page":{"page_urls":[],"excluded_page_urls":["/logout","/sign-in"]}},"behavior":{"display_to_pct":100},"prompts":[{"id":38667,"domain":23272,"name":"4 sec","style":"NATIVE","behavior":{"is_auto_show":true,"post_dismiss_redisplay":{"enabled":true,"fcap":{"interval_seconds":604800,"display_metric":"seconds"}}},"theme":null,"conditions":{"visitor":{"time_on_page_seconds":4}},"weight":100}]},{"id":36654,"domain":23272,"name":"Slide","priority":1,"conditions":{"display":{"desktop":"enabled","mobile":"enabled"},"page":{"page_urls":[],"excluded_page_urls":["/logout","/sign-in"]}},"behavior":{"display_to_pct":100},"prompts":[{"id":35082,"domain":23272,"name":null,"style":"SLIDE","template_html":"
We'd like to send you some notifications
Notifications can be turned off anytime from browser settings
","behavior":{"is_auto_show":true,"post_dismiss_redisplay":{"enabled":true,"fcap":{"interval_seconds":604800,"display_metric":"seconds"}}},"theme":{"position":{"desktop":"top","mobile":"bottom"}},"conditions":{"visitor":{"time_on_page_seconds":8}},"weight":100}]}]}catch(_){}})(); (function(){ PushlySDK.watch('ready', () => { try { const validSchemaTypes = ['Article', 'NewsArticle', 'Recipe', 'BlogPosting', 'LiveBlogPosting']; const validNodeProperties = ['articleSection', 'keywords', 'genre', 'recipeCategory', 'recipeCuisine']; let keywords = []; function parseNode(node) { if (validSchemaTypes.some(v => node['@type'].includes(v))) { validNodeProperties.forEach(np => { if (np in node) { if (Array.isArray(node[np])) { keywords.push(...node[np]); } else { keywords.push(...node[np].split(',')); } } }); } } const qss = document.querySelectorAll('script[type="application/ld+json"]'); if (qss) { qss.forEach(qs => { let parsedA = JSON.parse(qs.innerText); if (!Array.isArray(parsedA)) { parsedA = [parsedA] } parsedA.forEach(parsed => { if ('@graph' in parsed) { parsed['@graph'].forEach(node => { parseNode(node); }); } else if ('@type' in parsed) { parseNode(parsed); } }); }); if (keywords.length) { PushlySDK.push(['page_tag_visit', [... new Set(keywords)].map(v => v.trim().toLowerCase())]); } } } catch(e) {} }); })();