web-push-notifications 3.103.1 → 3.104.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/helpers/pagePath.d.ts +1 -1
- package/modules/Api/Api.d.ts +2 -0
- package/modules/ApiClient/ApiClient.types.d.ts +2 -0
- package/npm.js +1 -1
- package/npm.js.map +1 -1
- package/package.json +1 -1
- package/service-worker.js +1 -1
- package/service-worker.js.map +1 -1
- package/widget-web-popups.js +1 -1
- package/widget-web-popups.js.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,25 @@ the same mapping is in the
|
|
|
9
9
|
Entries for 3.71.0 through 3.78.0 are grouped under version headings, which is how this file was
|
|
10
10
|
kept before the version moved to the tag; earlier versions live only in the git history.
|
|
11
11
|
|
|
12
|
+
## fix(events): keep the letter case of the page path in PW_SiteOpened and page rules
|
|
13
|
+
|
|
14
|
+
- `path` in `PW_SiteOpened` keeps the site's letter case (`/Catalog/Shoes/`); a path that does not decode is sent
|
|
15
|
+
as it is. Web campaign page rules (`matching_page_rules`, `matching_pages`, `excluded_pages`) are compared with
|
|
16
|
+
this path case-sensitively, the rule path as stored: `/Catalog` and `/catalog` are different pages.
|
|
17
|
+
- A page rule whose case differs from the site's no longer matches its pages, e.g. `/catalog` saved lowercased on
|
|
18
|
+
`/Catalog`: re-save it in the site's case.
|
|
19
|
+
- A `path` condition in lowercase does not find new events from pages with capitals; events sent by the previous
|
|
20
|
+
release stay lowercased.
|
|
21
|
+
|
|
22
|
+
## feat(locale): send the browser locale on application open
|
|
23
|
+
|
|
24
|
+
- `applicationOpen` and `registerDevice` carry a `locale` field (BCP 47, e.g. `pt-BR`): the device language value,
|
|
25
|
+
canonicalized. On the web that value already is a locale (`navigator.language`, `setLanguage`, `initParams.tags.Language`),
|
|
26
|
+
so `language` and `locale` never disagree. The server stores the locale only for accounts with locale support.
|
|
27
|
+
- New `Pushwoosh.api.setLocale(locale | null)` and `Pushwoosh.api.getLocale()`. `setLocale` sets the same value as
|
|
28
|
+
`setLanguage` without sending setTags (`pt_br` → `pt-BR`, an invalid value is ignored, null goes back to
|
|
29
|
+
`navigator.language`); the change goes out with the next applicationOpen.
|
|
30
|
+
|
|
12
31
|
## fix(web-popups): do not count the FORM content Submit as an interaction
|
|
13
32
|
|
|
14
33
|
- An interaction (`recordPopupFormEvent`, event 3) is a click on a link or a button of the content, except the ✕ and
|
package/helpers/pagePath.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/** The page path events and page rules use: decoded
|
|
1
|
+
/** The page path events and page rules use: decoded, in the site's case, read anew on every call. */
|
|
2
2
|
export declare function getPagePath(): string;
|
package/modules/Api/Api.d.ts
CHANGED
|
@@ -45,6 +45,8 @@ export declare class Api {
|
|
|
45
45
|
}): Promise<IMapResponse['setTags']>;
|
|
46
46
|
getTags(): Promise<IMapResponse['getTags']>;
|
|
47
47
|
setLanguage(language: string): Promise<IMapResponse['setTags']>;
|
|
48
|
+
setLocale(locale: string | null): Promise<void>;
|
|
49
|
+
getLocale(): Promise<string | undefined>;
|
|
48
50
|
registerUser(userId: string | number, isManual?: boolean): Promise<IMapResponse['registerUser']>;
|
|
49
51
|
registerEmail(email: string, isManual?: boolean): Promise<IMapResponse['registerEmail']>;
|
|
50
52
|
registerSmsNumber(number: string, isManual?: boolean): Promise<IMapResponse['registerSmsNumber']>;
|
|
@@ -66,9 +66,11 @@ interface IRequestSubmitPopupForm extends IRequest {
|
|
|
66
66
|
}
|
|
67
67
|
interface IRequestApplicationOpen extends IRequest {
|
|
68
68
|
push_permission_status?: TPushPermissionStatus;
|
|
69
|
+
locale?: string;
|
|
69
70
|
}
|
|
70
71
|
interface IRequestRegisterDevice extends IRequest {
|
|
71
72
|
push_permission_status?: TPushPermissionStatus;
|
|
73
|
+
locale?: string;
|
|
72
74
|
push_token?: string;
|
|
73
75
|
public_key?: string;
|
|
74
76
|
auth_token?: string;
|
package/npm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>$e});const s="/pushwoosh-service-worker.js",i="https://api.pushwoosh.com/json/1.3/",a="deviceRegistrationStatus",r="reportedPushPermissionStatus",n="registered",o="unregistered",c="granted",h="default",u="onReady",d="onSubscribe",g="onUnsubscribe",l="onRegister",p="onPermissionPrompt",m="onPermissionDenied",w="onPermissionGranted",b="onSWInitError",f="onPushDelivery",y="onNotificationClick",v="onNotificationClose",P="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",C="onUpdateInboxMessages",I="onShowNotificationPermissionDialog",k="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",W="PW_SiteOpened",_="Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.",x=[210],T={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function R(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const M=e=>"function"==typeof e;function N(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const F={[l]:{name:"register"},[d]:{name:"subscribe"},[g]:{name:"unsubscribe"},[b]:{name:"initialize-service-worker-error",prop:"error"},[f]:{name:"receive-push",prop:"notification"},[y]:{name:"open-notification",prop:"notification"},[v]:{name:"hide-notification",prop:"notification"},[P]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[C]:{name:"update-inbox-messages",prop:"messages"},[I]:{name:"show-notification-permission-dialog"},[k]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[E]:{name:"hide-subscription-widget"},[m]:{name:"permission-denied"},[p]:{name:"permission-default"},[w]:{name:"permission-granted"}},U="keyValue",L="messages",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[q(U,function(e){e.createObjectStore(U,{keyPath:"key"})}),q("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(L,function(e){e.createObjectStore(L,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),q(O,function(e){const t="status",s=e.createObjectStore(O,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class V{constructor(e,t=new j){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function $(e,t){console.info("onversionchange",t),e.close()}let H;function K(){return H||(H=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=$.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=$.bind(null,s,t);new V(s).applyMigrations()}})),H}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=U,{get:(e,t)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||t):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=L,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||R(),i=this.handlers[e];return i?(i.forEach(e=>{M(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e,t){if(t)return{...e,...t}}class re{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const ne=["classic","captioned","banner","carousel"];function oe(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const ce=/^(?:javascript|vbscript|data|blob|file):/i,he=/^[a-z][a-z\d+\-.]*:/i;function ue(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function de(e){const t=ue(e);return he.test(t)&&!ce.test(t)}function ge(e,t){return t||e.image||""}function le(e){const t=["displayType","carousel","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class pe{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new re){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&de(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),g=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(ne.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&oe(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:ge(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),l=ge(h,s)||await this.data.getDefaultNotificationImage(),p=i||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(a)),{title:p,imageUrl:l,iconUrl:l,heroUrl:d,layout:g,carousel:u,customData:le(h),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!ce.test(ue(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class me{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class we{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new me(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new me(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new me(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new me(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new me(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new me(i,e);return a.index=t,a.countByIndex(s)}}class be{constructor(e,t,s,i=new we,a=new re){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new pe(this.data,this.api,this)})}}class fe extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const ye=e=>`params.${e}`;class ve{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(ye(t),void 0)}async setApplicationCode(e){await this.store.set(ye("applicationCode"),e)}async getApplicationCode(){return this.store.get(ye("applicationCode"))}async setApiToken(e){return await this.store.set(ye("apiToken"),e)}async getApiToken(){return this.store.get(ye("apiToken"))}async setHwid(e){await this.store.set(ye("hwid"),e)}async getHwid(){return this.store.get(ye("hwid"))}async setDeviceType(e){await this.store.set(ye("deviceType"),e)}async getDeviceType(){return this.store.get(ye("deviceType"))}async setFormFactor(e){await this.store.set(ye("formFactor"),e)}async getFormFactor(){return this.store.get(ye("formFactor"))}async setDeviceModel(e){await this.store.set(ye("deviceModel"),e)}async getDeviceModel(){return this.store.get(ye("deviceModel"))}async setLanguage(e){await this.store.set(ye("language"),e)}async getLanguage(){return this.store.get(ye("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(ye("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(ye("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(ye("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(ye("apiEntrypoint"),i)}async setTokens(e){await this.store.set(ye("tokens"),e)}getTokens(){return this.store.get(ye("tokens"))}async setApplicationServerKey(e){await this.store.set(ye("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(ye("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(ye("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(ye("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(ye("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(ye("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(ye("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(ye("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(ye("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(ye("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(ye("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(ye("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(ye("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(ye("userId"))}async getFeatureFlags(){return this.store.get(ye("featureFlags"))}async setFeatureFlags(e){await this.store.set(ye("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(ye("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(ye("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(ye("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(ye("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(ye("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(ye("email"))}async setStatusEmailWasChanged(e){await this.store.set(ye("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(ye("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(ye("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(ye("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(ye("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(ye("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(ye("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(ye("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(ye("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(ye("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(ye("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(ye("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(ye("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(ye("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(ye("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(ye("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(ye("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(ye("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(ye("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(ye("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(ye("sdkVersion"),e)}async getSdkVersion(){return this.store.get(ye("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(ye("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(ye("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(ye("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(ye("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(ye("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(ye("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(ye("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(ye("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(ye("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(ye("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(ye("features"),e)}async getFeatures(){return this.store.get(ye("features"))}async setInitParams(e){await this.store.set(ye("init"),e)}async getInitParams(){return this.store.get(ye("init"))}async setInboxLastRequestCode(e){await this.store.set(ye("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(ye("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(ye("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(ye("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(ye("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(ye("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(ye("delayedEvent"),e)}getDelayedEvent(){return this.store.get(ye("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(ye("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(ye("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(ye("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(ye("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(ye("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(ye("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(ye("logLevel"),e)}async getLogLevel(){return this.store.get(ye("logLevel"),"error")}async getShownWebPopups(){return this.store.get(ye("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(ye("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(ye("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(ye("isRecurringVisitor"),!1)}}class Pe{constructor(e=new ve,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new fe(s,t)}const t=await e.json();if(200!==t.status_code)throw new fe(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class Se{constructor(e,t=new ve,s=new Pe,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=N(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...e,push_permission_status:s,push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:e,metaData:s})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:R()}:s)}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?(await this.data.setLanguage(u.language),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(_);return e}}class Ce{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class Ie extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const ke=/json\/1\.3\/?$/,De="api/v2/device-api/getFeatureFlags";const Ee=18e5;class We{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new Ce(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<Ee)){await this.deps.data.setFeatureFlagImpressions({...Te(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new Ie("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new Ie("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(ke.test(t))return t.replace(ke,De);try{return`${new URL(t).origin}/${De}`}catch(e){return i.replace(ke,De)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new Ie(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new Ie(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new Ie("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!_e(c.response))throw new Ie(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:xe(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Ae(this.cache.flags):""}}function _e(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function xe(e){const t={};return _e(e)?(Object.keys(e).forEach(s=>{const i=e[s];_e(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:_e(i.properties)?i.properties:{}})}),t):t}function Te(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<Ee&&(s[i]=e[i])}),s}function Ae(e){return Array.isArray(e)?`[${e.map(Ae).join(",")}]`:_e(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ae(e[t])}`).join(",")}}`:JSON.stringify(e)}class Re{constructor(e){this.global=e,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion(),this._formFactor=this.getFormFactor()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}get formFactor(){return this._formFactor}get isMobile(){return"MOBILE"===this._formFactor}get isDesktop(){return"DESKTOP"===this._formFactor}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let e=11;switch(!0){case this._isSafari:e=10;break;case this._isOpera||this._isChrome:e=11;break;case this._isFirefox:e=12;break;case this._isEdge:e=150}return e}getFormFactor(){const e=navigator.userAgentData;if(e&&"boolean"==typeof e.mobile)return e.mobile?"MOBILE":"DESKTOP";return/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?"MOBILE":"DESKTOP"}getBrowserVersion(){const{userAgent:e}=navigator,t=e.match(/\bOPR\/(\d+)/);if(null!==t)return`Opera ${t[1]}`;const s=e.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const i=e.match(/\bEdg\/(\d+)/);if(null!==i)return`Edge ${i[1]}`;let a=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=a;a=a[2]?[r,a[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=e.match(/version\/([.\d]+)/i);return null!==n&&a.splice(1,1,n[1]),a.join(" ")}}const Me="pushwoosh-recommendations-views";function Ne(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class Fe{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:Ne(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(Me));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(Me,JSON.stringify(i))}catch{}return!1}}const Ue="sdkUsageReportedOn";class Le{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(Ue)===t)return;localStorage.setItem(Ue,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents]},{keepalive:!0}).catch(()=>{})}}function Oe(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function qe(e){return"safari"in e?e.safari?.pushNotification:void 0}function Be(e,t){try{return qe(e)?.permission(t)}catch{return}}class je{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${R()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class Ve{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class $e{constructor(){this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isLegacySafari=!1,this.waitForPermissionWork=N(1e4),this.moduleRegistry={},this.sdkUsage=new Le,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new ve,this.apiClient=new Pe(this.data),this.api=new Se(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new We({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new Fe({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.platformChecker=new Re(A()),this.inboxModel=new be(this.eventBus,this.data,this.api),this.pwinbox=new pe(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget())}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}push(e){if(M(e))this.subscribeToLegacyEvents(u,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await t.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const e=this.driver?.checkIsPermissionGranted();e&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),this.initParams={...T,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.platformChecker.formFactor),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion());if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.103.1"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.data.setDeviceType(this.resolvePlatformType()),await this.initStep("applicationOpen",()=>this.open()),await this.initStep("sendData",()=>this.sendData()),!this.isInitAborted){if(this.isAvailableNotifications()){await this.data.getApplicationServerKey()?await this.initStep("initPushNotifications",()=>this.initPushNotifications(this.initParams)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==x.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){this.isLegacySafari=this.detectLegacySafari();return!this.isLegacySafari&&(this.initParams.unifiedPlatform||this.platformChecker.isSafari)?11:this.platformChecker.getPlatformType()}detectLegacySafari(){if(!this.platformChecker.isSafari)return!1;if(!this.platformChecker.isAvailableServiceWorker)return!0;const{safariWebsitePushID:e,unifiedPlatform:t}=this.initParams??{};return!!function(e,t){const s=t?Be(e,t):void 0;return s?.permission===c&&!!s.deviceToken}(A(),e)||!t&&!this.isWebVapidConfigured}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+R();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(_)}catch(e){te.info(e,_)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(t){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.unsubscribe();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.unsubscribe();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){return this.driver?Oe(this.driver.getPermission()):function(e,t){const s=qe(e);if(s&&t){const s=Be(e,t);return s?Oe(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?Oe(e.Notification.permission):s?"not_determined":"unsupported"}(A(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=A();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c)s||e||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const e=this.dropRevokedSubscription(t).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(function(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups}:void 0}(t)),t.events&&t.events.length){t.events.some(e=>e===W)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=ae(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=ae(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new Ve(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}te.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new je(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=function(){const{pathname:e}=window.location;try{return decodeURIComponent(e).toLowerCase()}catch{return e.toLowerCase()}}(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in F:this.eventBus.addEventHandler(F[e].name,s=>{const{prop:i}=F[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var s=t();for(var i in s)("object"==typeof exports?exports:e)[i]=s[i]}}(this,()=>(()=>{"use strict";const e={d:(t,s)=>{for(var i in s)e.o(s,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:s[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}};let t={};e.r(t),e.d(t,{Pushwoosh:()=>He});const s="/pushwoosh-service-worker.js",i="https://api.pushwoosh.com/json/1.3/",a="deviceRegistrationStatus",r="reportedPushPermissionStatus",n="registered",o="unregistered",c="granted",h="default",u="onReady",d="onSubscribe",g="onUnsubscribe",l="onRegister",p="onPermissionPrompt",m="onPermissionDenied",w="onPermissionGranted",b="onSWInitError",f="onPushDelivery",y="onNotificationClick",v="onNotificationClose",P="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",C="onUpdateInboxMessages",I="onShowNotificationPermissionDialog",k="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",E="onHideSubscriptionWidget",W="PW_SiteOpened",_="Pushwoosh: the SDK storage does not keep the hwid in this browser (in-app webview, private window or insecure context), so this device cannot be identified. Requests that need an hwid are not sent.",x=[210],T={autoSubscribe:!0,serviceWorkerUrl:s};function A(){return globalThis}function R(){return crypto.randomUUID?.()||"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}const M=e=>"function"==typeof e;function N(e){const t=new WeakSet;return async s=>{if(t.has(s))return!1;const i=await function(e,t){let s;const i=new Promise(e=>{s=setTimeout(()=>e(!1),t)}),a=e.then(()=>!0,()=>!0);return Promise.race([a,i]).finally(()=>clearTimeout(s))}(s,e);return i||t.add(s),i}}const F={[l]:{name:"register"},[d]:{name:"subscribe"},[g]:{name:"unsubscribe"},[b]:{name:"initialize-service-worker-error",prop:"error"},[f]:{name:"receive-push",prop:"notification"},[y]:{name:"open-notification",prop:"notification"},[v]:{name:"hide-notification",prop:"notification"},[P]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[C]:{name:"update-inbox-messages",prop:"messages"},[I]:{name:"show-notification-permission-dialog"},[k]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[E]:{name:"hide-subscription-widget"},[m]:{name:"permission-denied"},[p]:{name:"permission-default"},[w]:{name:"permission-granted"}},L="keyValue",U="messages",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const B=[q(L,function(e){e.createObjectStore(L,{keyPath:"key"})}),q("log",function(e){const t=e.createObjectStore("log",{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(U,function(e){e.createObjectStore(U,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})}),q(O,function(e){const t="status",s=e.createObjectStore(O,{keyPath:"inbox_id",autoIncrement:!1});s.createIndex(t,t,{unique:!1,multiEntry:!0}),s.createIndex("rt","rt",{unique:!1,multiEntry:!0})})];class j{get all(){return B}}class V{constructor(e,t=new j){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.all)}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function $(e,t){console.info("onversionchange",t),e.close()}let H;function K(){return H||(H=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=$.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=$.bind(null,s,t);new V(s).applyMigrations()}})),H}function z(e){return K().then(t=>new Promise((s,i)=>e(t,s,i)))}class G{_add(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).add(e);a.onsuccess=()=>{s(e)},a.onerror=()=>{i(a.error)}}).then(e=>this.getAll().then(t=>{if(Array.isArray(t)){const s=t.map(e=>e.id).sort((e,t)=>e==t?0:e<t?1:-1);if(s.length>this.maxItems)return Promise.all(s.slice(this.maxItems).map(e=>this.delete(e))).then(()=>e)}return e}))}delete(e){return z((t,s,i)=>{const a=t.transaction([this.name],"readwrite").objectStore(this.name).delete(e);a.onsuccess=()=>{s(a.result)},a.onerror=()=>{i(a.error)}})}getAll(){return z((e,t,s)=>{const i=[],a=e.transaction(this.name).objectStore(this.name).openCursor();a.onsuccess=e=>{const s=e.target.result;s?(s.value&&i.push(s.value),s.continue()):t(i)},a.onerror=()=>{s(a.error)}})}}const J=(Y=L,{get:(e,t)=>z((s,i,a)=>{const r=s.transaction(Y).objectStore(Y).get(e);let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(r.result?.value||t):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()}),getAll:()=>z((e,t,s)=>{const i={},a=e.transaction(Y).objectStore(Y).openCursor();let r,n=!1,o=!1;const c=()=>{clearTimeout(r),n?t(i):o?s(a.error):r=setTimeout(c,0)};a.onsuccess=e=>{const t=e.target.result;t?(i[t.key]=t.value.value,t.continue()):n=!0},a.onerror=()=>o=!0,c()}),async extend(e,t){const s=await this.get(e),{...i}=t;await this.set(e,{...s,...i})},set:(e,t)=>z((s,i,a)=>{const r=s.transaction([Y],"readwrite").objectStore(Y).put({key:e,value:t});let n,o=!1,c=!1;const h=()=>{clearTimeout(n),o?i(e):c?a(r.error):n=setTimeout(h,0)};r.onsuccess=()=>o=!0,r.onerror=()=>c=!0,h()})});var Y;const X=new class extends G{constructor(){super(...arguments),this.name="log",this.maxItems=100,this.environment="undefined"!=typeof self&&self.registration?"worker":"browser"}add(e,t,s){const i={type:e,environment:this.environment,message:`${t}`,date:new Date};return t instanceof Error&&(i.stack=t.stack),s&&(i.additional=s),this._add(i)}},Q=new class extends G{constructor(){super(...arguments),this.name=U,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Z={error:1,info:2,debug:3};let ee=3;const te={setLevel(e){Z[e]||(e="error"),ee=Z[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),X.add(e,t,s)}};Object.keys(Z).forEach(e=>{const t=Z[e];te[e]=(...s)=>{t<=ee&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class se{constructor(){this.addEventHandler=(e,t)=>{let s=this.handlers[e];s||(s=[]),s.push(t),this.handlers[e]=s},this.removeEventHandler=(e,t)=>{const s=this.handlers[e];s&&(this.handlers[e]=s.filter(e=>e!==t))},this.dispatchEvent=(e,t)=>{const s=t.eventId||R(),i=this.handlers[e];return i?(i.forEach(e=>{M(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}const ie=["autoSubscribe","defaultNotificationTitle","defaultNotificationImage","safariWebsitePushID","unifiedPlatform","subscriptionWidget"];function ae(e,t){if(t)return{...e,...t}}class re{constructor(e=new Date){this._date=e}set date(e){this._date=e}get date(){return this._date}getUtcTimestamp(){return Math.floor((this.date.getTime()+60*this.date.getTimezoneOffset()*1e3)/1e3)}getTimestamp(){return Math.round(this.date.getTime()/1e3)}setLocal(){const e=this._date.getTime()-60*this.date.getTimezoneOffset()*1e3;this._date=new Date(e)}addDays(e){const t=this._date.getTime()+24*e*60*60*1e3;this._date=new Date(t)}getInboxFakeOrder(){return(100*this._date.getTime()+9e9).toString()}}const ne=["classic","captioned","banner","carousel"];function oe(e){return(Array.isArray(e)?e:[]).filter(e=>!!e&&!!e.imageUrl).slice(0,5)}const ce=/^(?:javascript|vbscript|data|blob|file):/i,he=/^[a-z][a-z\d+\-.]*:/i;function ue(e){return e.split("").filter(e=>e.charCodeAt(0)>32&&127!==e.charCodeAt(0)).join("")}function de(e){const t=ue(e);return he.test(t)&&!ce.test(t)}function ge(e,t){return t||e.image||""}function le(e){const t=["displayType","carousel","image"];return Object.keys(e).filter(e=>-1===t.indexOf(e)).reduce((t,s)=>(t[s]=e[s],t),{})}class pe{constructor(e,t,s,i={},a=()=>Promise.resolve(void 0),r=new re){this.data=e,this.api=t,this.inboxModel=s,this.moduleRegistry=i,this.loadWebPopups=a,this.dateModule=r,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}parseActionParams(e){try{return JSON.parse(e)||{}}catch(t){return te.write("error",`Pushwoosh: cannot parse inbox action_params: ${e}`,t),{}}}messageTypeFactory(e,t){let s=0;return 2===e?s=1:"l"in t&&null!=t.l&&(s=t.l.startsWith("http")?2:3),s}async updateMessagesStatusWithCodes(e,t,s){const i=[],a=[];t.forEach(async t=>{-1!==e.indexOf(t.inbox_id)&&(t.status=s,i.push(t),a.push(this.api.inboxStatus(t.order,t.status)))}),await this.inboxModel.putBulkMessages(i),await Promise.all(a)}async publicMessageBuilder({action_type:e,action_params:t,image:s,title:i,send_date:a,inbox_id:r,text:n,status:o}){const c=this.parseActionParams(t),h=function(e){const t=e?.u;if(!t)return{};if("string"==typeof t)try{return JSON.parse(t)||{}}catch{return{}}return"object"==typeof t?t:{}}(c),u=function(e){return(Array.isArray(e.carousel)?e.carousel:[]).filter(e=>!!e&&!!e.image).slice(0,5).map(e=>({imageUrl:e.image,caption:e.title||"",link:e.url&&de(e.url)?e.url:""}))}(h),d=function(e,t,s){return e?.b||s||t.image||""}(c,h,s),g=function(e){const t=!!e.title,s=!!e.body,i=function(e){return e.bannerUrl||e.iconUrl||""}(e);let a=e.layoutType;switch(ne.includes(a)||(a=e.bannerUrl&&!t?"banner":e.bannerUrl&&t&&s?"captioned":"classic"),a){case"banner":return i?"banner":"classic";case"captioned":return i&&t&&s?"captioned":"classic";case"carousel":return t&&s&&oe(e.carousel).length>0?"carousel":"classic";default:return"classic"}}({title:i,body:n,iconUrl:ge(h,s),bannerUrl:c.b,layoutType:h.displayType,carousel:u}),l=ge(h,s)||await this.data.getDefaultNotificationImage(),p=i||await this.data.getDefaultNotificationTitle();return this.dateModule.date=new Date(1e3*parseInt(a)),{title:p,imageUrl:l,iconUrl:l,heroUrl:d,layout:g,carousel:u,customData:le(h),webPopupCode:c.wp||"",code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,c),link:c?.l||"/",isRead:2===o||3===o,isActionPerformed:3===o}}messagesWithNoActionPerformedCount(){return this.inboxModel.getDeliveredReadMessagesCount()}unreadMessagesCount(){return this.inboxModel.getDeliveredMessagesCount()}messagesCount(){return this.inboxModel.messagesCount()}async loadMessages(){const e=[...await this.inboxModel.getReadOpenMessages(),...await this.inboxModel.getDeliveredMessages()].sort((e,t)=>parseInt(t.send_date,10)-parseInt(e.send_date,10)).sort((e,t)=>parseInt(t.order||"0",10)-parseInt(e.order||"0",10)).map(this.publicMessageBuilder);return Promise.all(e)}async readMessagesWithCodes(e){const t=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,t,2)}async performActionForMessageWithCode(e){const t=await this.inboxModel.getMessage(e),s=this.parseActionParams(t.action_params),i=this.messageTypeFactory(t.action_type,s),a=2===i||3===i;var r;!await this.showWebPopup(s.wp)&&a&&null!=s.l&&((r=s.l)&&!ce.test(ue(r)))&&(document.location.href=s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}async showWebPopup(e){if(!e)return!1;try{const t=this.moduleRegistry.webPopups??await this.loadWebPopups();return t?await t.show(e):(te.write("error",`Pushwoosh: inbox message opens web popup "${e}", but the web popups widget could not be loaded`),!1)}catch(t){return te.write("error",`Pushwoosh: failed to open web popup "${e}" from inbox`,t),!1}}async deleteMessagesWithCodes(e){const t=await this.inboxModel.getReadOpenMessages(),s=await this.inboxModel.getDeliveredMessages();await this.updateMessagesStatusWithCodes(e,[...t,...s],4)}async syncMessages(){await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}}class me{constructor(e,t){this.name=t,this.store=e.transaction(this.name,"readwrite").objectStore(this.name)}set index(e){this.store.indexNames.contains(e)?this._index=this.store.index(e):console.warn(`Index "${e}" in `)}writeRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=()=>{s(t)},e.onerror=()=>{i(e.error)}})}readRequestPromise(e,t){return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target;s(i.result||t)},e.onerror=()=>{i(e.error)}})}put(e,t){const s=this.store.put(e,t);return this.writeRequestPromise(s,t)}add(e,t){return this.put(e,t)}delete(e){const t=this.store.delete(e);return this.writeRequestPromise(t)}get(e,t){const s=this.store.get(e);return this.readRequestPromise(s,t)}getAll(){const e=this.store.openCursor(),t=[];return new Promise((s,i)=>{e.onsuccess=e=>{const i=e.target.result;i?(t.push(i.value),i.continue()):s(t)},e.onerror=()=>{i(e.error)}})}count(e){const t=this.store.count(e);return this.readRequestPromise(t,0)}countByIndex(e){const t=this._index.count(e);return this.readRequestPromise(t,0)}}class we{getDB(){return K()}async put(e,t,s){const i=await this.getDB();return new me(i,e).put(t,s)}async delete(e,t){const s=await this.getDB();return new me(s,e).delete(t)}async get(e,t,s){const i=await this.getDB();return new me(i,e).get(t,s)}async getAll(e){const t=await this.getDB(),s=new me(t,e);return await s.getAll()||[]}async count(e,t){const s=await this.getDB();return new me(s,e).count(t)}async countByIndex(e,t,s){const i=await this.getDB(),a=new me(i,e);return a.index=t,a.countByIndex(s)}}class be{constructor(e,t,s,i=new we,a=new re){this.eventBus=e,this.data=t,this.api=s,this.storage=i,this.storeName="inboxMessages",this.dateModule=a}async getInboxMessages(){const e=await this.api.getInboxMessages();return await this.storeGetInboxMessagesRequestParams(e.next,e.new_inbox),e}async storeGetInboxMessagesRequestParams(e,t){this.dateModule.date=new Date,await this.data.setInboxLastRequestTime(this.dateModule.getUtcTimestamp()),await this.data.setInboxLastRequestCode(e),await this.data.setInboxNewMessagesCount(t)}async putServerMessages(e){const t=e.map(async e=>{const t=await this.storage.get(this.storeName,e.inbox_id,{});return"status"in t&&(e.status=t.status),this.putMessage(e)});return Promise.all(t)}putMessage(e){return this.storage.put(this.storeName,e)}putBulkMessages(e){const t=e.map(e=>this.putMessage(e));return Promise.all(t)}deleteMessages(e){const t=e.map(e=>this.storage.delete(this.storeName,e));return Promise.all(t)}async deleteExpiredMessages(){this.dateModule.date=new Date;const e=this.dateModule.getTimestamp().toString(),t=(await this.storage.getAll(this.storeName)).filter(t=>t.rt<e).map(e=>e.inbox_id);return this.deleteMessages(t)}getMessage(e){return this.storage.get(this.storeName,e)}async getReadOpenMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>2===e.status||3===e.status)}async getDeliveredMessages(){return(await this.storage.getAll(this.storeName)).filter(e=>1===e.status)}async messagesCount(){return this.storage.count(this.storeName)}async getDeliveredMessagesCount(){return this.storage.countByIndex(this.storeName,"status",1)}async getReadMessagesCount(){return this.storage.countByIndex(this.storeName,"status",2)}async getDeliveredReadMessagesCount(){const[e,t]=[2,3],s=IDBKeyRange.bound(e,t);return this.storage.countByIndex(this.storeName,"status",s)}async updateMessages(){const e=await this.getInboxMessages();await this.deleteExpiredMessages(),e.deleted&&await this.deleteMessages(e.deleted),await this.putServerMessages(e.messages),this.eventBus.dispatchEvent("update-inbox-messages",{messages:new pe(this.data,this.api,this)})}}class fe extends Error{constructor(e,t){super(e),this.name="ApiRequestError",this.statusCode=t}}const ye=e=>`params.${e}`;class ve{constructor(e=J){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","languageWasChanged","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","webVapidConfigured","webSitePushId","defaultNotificationImage","defaultNotificationTitle","userId","userIdWasChanged","email","emailWasChanged","isLastPermissionStatus","isManualUnsubscribed","isCommunicationDisabled","communicationEnabled","isDropAllData","sdkVersion","serviceWorkerVersion","serviceWorkerUrl","serviceWorkerScope","lastOpenMessage","lastOpenApplicationTime","features","init","inbox.lastRequestCode","inbox.lastRequestTime","inbox.newMessagesCount","delayedEvent","promptDisplayCount","promptLastSeenTime","logLevel","shownWebPopups","isRecurringVisitor","featureFlags","featureFlagImpressions"];for(const t of e)await this.store.set(ye(t),void 0)}async setApplicationCode(e){await this.store.set(ye("applicationCode"),e)}async getApplicationCode(){return this.store.get(ye("applicationCode"))}async setApiToken(e){return await this.store.set(ye("apiToken"),e)}async getApiToken(){return this.store.get(ye("apiToken"))}async setHwid(e){await this.store.set(ye("hwid"),e)}async getHwid(){return this.store.get(ye("hwid"))}async setDeviceType(e){await this.store.set(ye("deviceType"),e)}async getDeviceType(){return this.store.get(ye("deviceType"))}async setFormFactor(e){await this.store.set(ye("formFactor"),e)}async getFormFactor(){return this.store.get(ye("formFactor"))}async setDeviceModel(e){await this.store.set(ye("deviceModel"),e)}async getDeviceModel(){return this.store.get(ye("deviceModel"))}async setLanguage(e){await this.store.set(ye("language"),e)}async getLanguage(){return this.store.get(ye("language"),"en")}async setStatusLanguageWasChanged(e){await this.store.set(ye("languageWasChanged"),e)}async getStatusLanguageWasChanged(){return this.store.get(ye("languageWasChanged"),!1)}async setApiEntrypoint(e){await this.store.set(ye("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(ye("apiEntrypoint"),i)}async setTokens(e){await this.store.set(ye("tokens"),e)}getTokens(){return this.store.get(ye("tokens"))}async setApplicationServerKey(e){await this.store.set(ye("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(ye("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(ye("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(ye("isVapidChanged"),!1)}async setWebVapidConfigured(e){await this.store.set(ye("webVapidConfigured"),e)}async getWebVapidConfigured(){return this.store.get(ye("webVapidConfigured"),!1)}async setWebSitePushId(e){await this.store.set(ye("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(ye("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(ye("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(ye("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(ye("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(ye("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(ye("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(ye("userId"))}async getFeatureFlags(){return this.store.get(ye("featureFlags"))}async setFeatureFlags(e){await this.store.set(ye("featureFlags"),e)}async getFeatureFlagImpressions(){return this.store.get(ye("featureFlagImpressions"),{})}async setFeatureFlagImpressions(e){await this.store.set(ye("featureFlagImpressions"),e)}async setStatusUserIdWasChanged(e){await this.store.set(ye("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(ye("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(ye("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(ye("email"))}async setStatusEmailWasChanged(e){await this.store.set(ye("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(ye("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(ye("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(ye("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(ye("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(ye("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(ye("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(ye("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(ye("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(ye("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(ye("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(ye("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(ye("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(ye("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(ye("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(ye("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(ye("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(ye("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(ye("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(ye("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(ye("sdkVersion"),e)}async getSdkVersion(){return this.store.get(ye("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(ye("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(ye("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(ye("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(ye("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(ye("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(ye("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(ye("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(ye("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(ye("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(ye("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(ye("features"),e)}async getFeatures(){return this.store.get(ye("features"))}async setInitParams(e){await this.store.set(ye("init"),e)}async getInitParams(){return this.store.get(ye("init"))}async setInboxLastRequestCode(e){await this.store.set(ye("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(ye("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(ye("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(ye("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(ye("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(ye("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(ye("delayedEvent"),e)}getDelayedEvent(){return this.store.get(ye("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(ye("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(ye("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(ye("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(ye("promptLastSeenTime"),0)}async setSubscriptionWidgetHistory(e){await this.store.set(ye("subscriptionWidgetHistory"),e)}async getSubscriptionWidgetHistory(){return this.store.get(ye("subscriptionWidgetHistory"),{shownCount:0,lastShownAt:null})}async setLogLevel(e){await this.store.set(ye("logLevel"),e)}async getLogLevel(){return this.store.get(ye("logLevel"),"error")}async getShownWebPopups(){return this.store.get(ye("shownWebPopups"),[])}async addShownWebPopup(e){const t=await this.getShownWebPopups();t.includes(e)||(t.push(e),await this.store.set(ye("shownWebPopups"),t))}async setIsRecurringVisitor(e){await this.store.set(ye("isRecurringVisitor"),e)}async getIsRecurringVisitor(){return this.store.get(ye("isRecurringVisitor"),!1)}}class Pe{constructor(e=new ve,t=te){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",e)}getPopupForms(e){return this.createRequest("getPopupForms",e)}getPopupFormContent(e){return this.createRequest("getPopupFormContent",e)}recordPopupFormEvent(e){return this.createRequest("recordPopupFormEvent",e)}submitPopupForm(e){return this.createRequest("submitPopupForm",e)}applicationOpen(e){return this.createRequest("applicationOpen",e)}registerDevice(e){return this.createRequest("registerDevice",e)}unregisterDevice(e){return this.createRequest("unregisterDevice",e)}deleteDevice(e){return this.createRequest("deleteDevice",e)}messageDeliveryEvent(e){return this.createRequest("messageDeliveryEvent",e)}pushStat(e){return this.createRequest("pushStat",e)}setTags(e){return this.createRequest("setTags",e)}getTags(e){return this.createRequest("getTags",e)}registerUser(e){return this.createRequest("registerUser",e)}registerEmail(e){return this.createRequest("registerEmail",e)}registerEmailUser(e){return this.createRequest("registerEmailUser",e)}setEmailTags(e){return this.createRequest("setEmailTags",e)}postEvent(e,t){return this.createRequest("postEvent",e,t)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}multiRegisterDevice(e){return this.createRequest("multiRegisterDevice",e)}sdkUsage(e,t){return this.createRequest("sdkUsage",e,t)}async createRequest(e,t,s={}){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:A().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n,keepalive:s.keepalive}),c=await this.checkResponse(o);return c.base_url&&await this.data.setApiEntrypoint(c.base_url),await this.logger.write("apirequest",`${e} call with arguments: ${JSON.stringify(t)} to Pushwoosh has been successful. Result: ${JSON.stringify(c.response)}`),c.response}async checkResponse(e){if(200!==e.status){let t,s=`status: ${e.status}. statusText: ${e.statusText}.`;try{const i=await e.json();i&&"number"==typeof i.status_code&&(t=i.status_code),i&&i.status_message&&(s+=` status_code: ${i.status_code}. status_message: ${i.status_message}.`)}catch(e){}throw new fe(s,t)}const t=await e.json();if(200!==t.status_code)throw new fe(`Error code: ${t.status_code}. Error text: ${t.status_message}`,"number"==typeof t.status_code?t.status_code:void 0);return t}}class Se{constructor(e,t=new ve,s=new Pe,i=()=>!1,a=()=>{},r=()=>{}){this.ensureDeviceRegisteredPromise=null,this.checkDevicePromise=null,this.registerDevicePromise=null,this.waitForRegisterDevice=N(1e4),this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i,this.getInitUserId=a,this.getPushPermissionStatus=r}async checkDevice(){return this.checkDevicePromise||(this.checkDevicePromise=this.requestCheckDevice().catch(e=>{throw this.checkDevicePromise=null,e})),this.checkDevicePromise}async requestCheckDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(a);if(null===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(a,e&&s?n:o),t=localStorage.getItem(a)}return t===n}async ensureDeviceRegistered(){return!this.getIsCommunicationDisabled()&&(this.ensureDeviceRegisteredPromise||(this.ensureDeviceRegisteredPromise=this.registerDeviceIfNotExist().catch(e=>{throw this.ensureDeviceRegisteredPromise=null,e})),this.ensureDeviceRegisteredPromise)}async registerDeviceIfNotExist(){const{exist:e}=await this.checkDevice();if(e)return!1;const t=this.getPushPermissionStatus();return await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t),!0}async reportPushPermissionStatus(e=!1){const t=this.getPushPermissionStatus();if(t&&t!==this.reportingPushPermissionStatus&&t!==localStorage.getItem(r)){this.reportingPushPermissionStatus=t;try{if(this.registerDevicePromise&&!await this.waitForRegisterDevice(this.registerDevicePromise))return;if(this.getIsCommunicationDisabled()||!e&&await this.checkDeviceSubscribeForPushNotifications())return;await this.apiClient.registerDevice({...await this.getRequestParams(),push_permission_status:t,locale:await this.getLocale()}),this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(t)}finally{this.reportingPushPermissionStatus===t&&(this.reportingPushPermissionStatus=void 0)}}}isPushPermissionStatusReported(){return this.getPushPermissionStatus()===localStorage.getItem(r)}rememberReportedPushPermissionStatus(e){e&&localStorage.setItem(r,e)}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();await this.data.setLastOpenApplicationTime(Date.now());const t=this.getPushPermissionStatus(),s=await this.apiClient.applicationOpen({...e,push_permission_status:t,locale:await this.getLocale()});return this.rememberReportedPushPermissionStatus(t),s}async registerDevice(){const e=this.requestRegisterDevice();this.registerDevicePromise=e;try{return await e}finally{this.registerDevicePromise===e&&(this.registerDevicePromise=null)}}async requestRegisterDevice(){if(await this.data.getStatusCommunicationDisabled())throw new Error("Can't register device: Communication is disabled!");const e=await this.getRequestParams(),t=await this.data.getTokens();if(!t.pushToken)throw new Error("Can't register device: pushToken is not exist!");const s=this.getPushPermissionStatus(),i=await this.apiClient.registerDevice({...e,push_permission_status:s,locale:await this.getLocale(),push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return this.checkDevicePromise=null,this.rememberReportedPushPermissionStatus(s),await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{}),i}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return this.checkDevicePromise=null,localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(a,o),this.eventBus.dispatchEvent("unsubscribe",{}),t}async messageDeliveryEvent(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.messageDeliveryEvent({...i,hash:e,metaData:s})}async pushStat(e,t,s={}){const i=await this.getRequestParams();return await this.apiClient.pushStat({...i,hash:e,metaData:s})}async setTags(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:t,device_type:s,...i}=await this.getRequestParams(),a=await this.data.getEmail();return a&&await this.apiClient.setEmailTags({...i,email:a,tags:e}),this.apiClient.setTags({...i,hwid:t,device_type:s,tags:e})}async getTags(){const e=await this.getRequestParams();return this.apiClient.getTags(e)}async setLanguage(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):(await this.data.setLanguage(e),await this.data.setStatusLanguageWasChanged(!0),this.setTags({Language:e}))}async setLocale(e){if(!e)return await this.data.setLanguage(navigator.language),void await this.data.setStatusLanguageWasChanged(!1);const t=Ce(e.trim().replace(/_/g,"-"));t&&(await this.data.setLanguage(t),await this.data.setStatusLanguageWasChanged(!0))}async getLocale(){return Ce(await this.data.getLanguage())||void 0}async registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.data.getUserId(),c=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),n&&n!==o&&this.eventBus.dispatchEvent("change-user-id",{userId:n}),t&&await this.data.setStatusUserIdWasChanged(!0),c}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject(new Error("Invalid Email format"));const s=await this.getIdentityRequestParams(),i=await this.apiClient.registerEmail({...s,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),i}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:18});return await this.data.setSmsNumber(e),t&&await this.data.setStatusSmsNumberWasChanged(!0),a}async registerWhatsappNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));if(!/^(whatsapp:)?\+?[0-9]+$/.test(e))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));const{application:s,userId:i}=await this.getIdentityRequestParams(),a=await this.apiClient.registerDevice({application:s,userId:i,hwid:e,device_type:21});return await this.data.setWhatsAppNumber(e),t&&await this.data.setStatusWhatsAppNumberWasChanged(!0),a}async getPopupForms(){if(this.getIsCommunicationDisabled())return[];return(await this.apiClient.getPopupForms(await this.getRequestParams())).popup_forms??[]}async getPopupFormContent(e){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.getPopupFormContent({...await this.getRequestParams(),code:e})}async recordPopupFormEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s={...await this.getRequestParams(),code:e,event:t};return this.apiClient.recordPopupFormEvent(3===t?{...s,clickId:R()}:s)}async submitPopupForm(e,t){return this.getIsCommunicationDisabled()?Promise.reject(new Error("Communication is disabled")):this.apiClient.submitPopupForm({...await this.getRequestParams(),code:e,email:t.email,tags:t.tags,policy_accepted:t.policyAccepted})}async sdkUsage(e,t){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const s=await this.getRequestParams();return this.apiClient.sdkUsage({...s,...e},t)}async postEvent(e,t,s){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const i=await this.getRequestParams(),a=new Date,r=a.getTime(),n=Math.floor(r/1e3),o=n-a.getTimezoneOffset()/60*3600,c=await this.data.getLastOpenMessage();if(c&&c.expiry>Date.now()){if(t.msgHash)return Promise.reject(new Error("attribute msgHash already defined"));t={...t,msgHash:c.messageHash}}await this.data.setLastOpenMessage(void 0);const h=await this.apiClient.postEvent({...i,event:e,timestampUTC:n,timestampCurrent:o,attributes:t},s);return h&&h.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:h.code}),h}async getInboxMessages(e=0){const t=await this.getRequestParams(),s=await this.data.getInboxLastRequestCode(),i=await this.data.getInboxLastRequestTime();return this.apiClient.getInboxMessages({...t,count:e,last_code:s,last_request_time:i})}async inboxStatus(e,t){const s=await this.getRequestParams();return this.apiClient.inboxStatus({...s,inbox_code:e,status:t,time:(new Date).getTime()})}async multiRegisterDevice(e){if(this.getIsCommunicationDisabled())return Promise.reject(new Error("Communication is disabled"));const t=await this.data.getApplicationCode(),s=await this.data.getDeviceModel(),i=await this.data.getDeviceType(),r=await this.data.getLanguage(),o=await this.data.getSdkVersion(),c=await this.data.getTokens(),h=await this.data.getHwid();!e.push_devices&&c.pushToken&&await this.requireHwid();const u={application:t,...e};if(e.user_id){u.user_id=String(e.user_id);await this.data.getUserId()!==u.user_id&&(await this.data.setUserId(u.user_id),await this.data.setStatusUserIdWasChanged(!0))}if(e.email){if(!/^\S+@\S+\.\S+$/.test(e.email))return Promise.reject(new Error("Invalid Email format"));await this.data.getEmail()!==e.email&&(await this.data.setEmail(e.email),await this.data.setStatusEmailWasChanged(!0))}if(e.sms_phone_number){if(!/^\+?[0-9]+$/.test(e.sms_phone_number))return Promise.reject(new Error("Invalid Phone number format: +1234567890"));await this.data.getSmsNumber()!==e.sms_phone_number&&(await this.data.setSmsNumber(e.sms_phone_number),await this.data.setStatusSmsNumberWasChanged(!0))}if(e.whatsapp_phone_number){if(!/^(whatsapp:)?\+?[0-9]+$/.test(e.whatsapp_phone_number))return Promise.reject(new Error("Invalid WhatsApp number format: +1234567890"));await this.data.getWhatsAppNumber()!==e.whatsapp_phone_number&&(await this.data.setWhatsAppNumber(e.whatsapp_phone_number),await this.data.setStatusWhatsAppNumberWasChanged(!0))}if(u.language?(await this.data.setLanguage(u.language),await this.data.setStatusLanguageWasChanged(!0)):u.language=r,!u.timezone){const e=60*-(new Date).getTimezoneOffset();u.timezone=String(e)}if(!u.push_devices&&c.pushToken){const e={hwid:h,platform:i,push_token:c.pushToken,sdk_version:o};if(c.publicKey||c.authToken||s){const t={};c.publicKey&&(t.public_key=c.publicKey),c.authToken&&(t.auth_token=c.authToken),s&&(t.browser=s),e.platformData=t}u.push_devices=[e]}const d=await this.apiClient.multiRegisterDevice(u);return u.push_devices?.length&&(this.checkDevicePromise=null,await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(a,n),this.eventBus.dispatchEvent("register",{})),d}async getParams(){return{applicationCode:await this.data.getApplicationCode(),hwid:await this.data.getHwid(),...await this.data.getTokens(),...await this.data.getInitParams()}}async getRequestParams(){const e=await this.requireHwid(),t=await this.data.getDeviceType();return{...await this.getIdentityRequestParams(),hwid:e,device_type:t}}async getIdentityRequestParams(){const e=await this.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId()||this.getInitUserId(),i=await this.data.getDeviceModel(),a=await this.data.getLanguage(),r=await this.data.getSdkVersion(),n=60*-(new Date).getTimezoneOffset();if(!s&&!t)throw new Error("Pushwoosh: neither a userId nor an hwid is available, so there is nothing to register the email, SMS or WhatsApp channel to. Pass a userId in the init params.");return{application:e,userId:s||t,device_model:i,timezone:n,language:a,v:r}}async requireHwid(){const e=await this.data.getHwid();if(!e)throw new Error(_);return e}}function Ce(e){try{return e?Intl.getCanonicalLocales(e)[0]??"":""}catch{return""}}class Ie{constructor(e,t,s,i){this.key=e,this.enabled=t,this.ruleId=s,this.properties=i}getString(e,t){const s=this.properties[e];return"string"==typeof s?s:t}getNumber(e,t){const s=this.properties[e];return"number"==typeof s&&Number.isFinite(s)?s:t}getBool(e,t){const s=this.properties[e];return"boolean"==typeof s?s:t}getJson(e,t){const s=this.properties[e];return s??t}getProperties(){return{...this.properties}}}class ke extends Error{constructor(e,t){super(e),this.name="FeatureFlagsError",this.httpStatus=t}}const De=/json\/1\.3\/?$/,Ee="api/v2/device-api/getFeatureFlags";const We=18e5;class _e{constructor(e){this.listeners=new Set,this.pageImpressions=new Set,this.isMemoryOnly=!1,this.applicationCode="",this.userId="",this.lastRequestAt=0,this.lastSentUnregistered=!1,this.generation=0,this.isStarted=!1,this.isLoaded=!1,this.isActivated=!1,this.userChangedWhileLoading=!1,this.deps={fetch:(e,t)=>fetch(e,t),now:()=>Date.now(),...e},this.deps.eventBus.addEventHandler("change-user-id",({userId:e})=>this.onUserChanged(e)),this.deps.eventBus.addEventHandler("register",()=>this.onRegistered())}async start(){if(this.isStarted)return;this.isStarted=!0,this.applicationCode=await this.deps.data.getApplicationCode()||"";const e=await this.deps.data.getUserId()||"";this.userChangedWhileLoading||(this.userId=e);const t=await this.deps.data.getFeatureFlags();t&&t.applicationCode===this.applicationCode&&(this.cache=t),this.isLoaded=!0,this.isActivated&&(""!==this.visibleSnapshot()&&this.notify(),this.refreshOnPageLoad())}get(e){if(this.activate(),!this.cache||!this.hasValidCache())return null;const t=this.cache.flags[e];return t?new Ie(e,t.enabled,t.rule_id,t.properties):null}isEnabled(e,t){const s=this.get(e);return s?s.enabled:t}refresh(){return this.activate(),this.hasValidCache()&&this.deps.now()-this.lastRequestAt<3e5?Promise.resolve():this.send()}reset(){clearTimeout(this.timer),this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.isStarted=!1,this.isLoaded=!1,this.userChangedWhileLoading=!1}addUpdateListener(e){this.activate(),this.listeners.add(e)}removeUpdateListener(e){this.listeners.delete(e)}async logImpression(e){const t=this.get(e);if(!t||this.deps.isCommunicationDisabled())return;const s=`${e}|${t.ruleId}|${t.enabled}`;if(!this.pageImpressions.has(s)){this.pageImpressions.add(s);try{await this.sendImpression(t,s)}catch(e){this.pageImpressions.delete(s),te.error(e,"Pushwoosh: feature flag impression was not sent")}}}async sendImpression(e,t){const s=this.deps.now(),i=await this.deps.data.getFeatureFlagImpressions();if(!(void 0!==i[t]&&s-i[t]<We)){await this.deps.data.setFeatureFlagImpressions({...Ae(i,s),[t]:s});try{await this.deps.postEvent("PW_FeatureFlagImpression",{flag_key:e.key,rule_id:e.ruleId,enabled:e.enabled})}catch(e){const s=await this.deps.data.getFeatureFlagImpressions().catch(()=>{});throw s&&(delete s[t],await this.deps.data.setFeatureFlagImpressions(s).catch(()=>{})),e}}}onUserChanged(e){if(!this.isLoaded)return this.userId=e,void(this.userChangedWhileLoading=!0);e!==this.userId&&(this.userId=e,this.cache=void 0,this.isMemoryOnly=!1,this.generation++,this.pageImpressions.clear(),this.deps.data.setFeatureFlags(void 0),this.isActivated&&this.sendAfterInFlight())}onRegistered(){const e=!!this.cache&&!!this.cache.sentUnregistered;this.isLoaded&&this.isActivated&&(this.lastSentUnregistered||e)&&this.sendAfterInFlight()}activate(){this.isActivated||(this.isActivated=!0,this.isLoaded&&this.refreshOnPageLoad())}refreshOnPageLoad(){const e=this.cache?this.deps.now()-this.cache.fetchedAt:1/0,t=!!this.cache&&!!this.cache.sentUnregistered&&this.deps.isDeviceRegistered();!this.hasValidCache()||e>9e5||t?this.sendInBackground():this.schedulePeriodicRefresh()}sendAfterInFlight(){(this.inFlight||Promise.resolve()).catch(()=>{}).then(()=>this.sendInBackground())}sendInBackground(){this.send().catch(e=>te.error(e,"Pushwoosh: feature flags refresh failed"))}send(){return this.inFlight||(this.inFlight=this.request().finally(()=>{this.inFlight=void 0,this.schedulePeriodicRefresh()})),this.inFlight}async request(){if(this.lastRequestAt=this.deps.now(),this.deps.isCommunicationDisabled())throw new ke("Communication is disabled",0);const e=this.generation,t=await this.deps.data.getHwid();if(!t||!this.applicationCode)throw new ke("Pushwoosh SDK is not initialized",0);const s={application:this.applicationCode,hwid:t};this.cache&&this.hasValidCache()&&this.cache.etag&&(s.etag=this.cache.etag);const a=function(e){const t=e||i;if(De.test(t))return t.replace(De,Ee);try{return`${new URL(t).origin}/${Ee}`}catch(e){return i.replace(De,Ee)}}(await this.deps.data.getApiEntrypoint()),r=await this.deps.data.getApiToken(),n={method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",...r?{Authorization:`Token ${r}`}:{}},body:JSON.stringify(s),...r?{credentials:"include"}:{}};let o,c;this.lastSentUnregistered=!this.deps.isDeviceRegistered();try{o=await this.deps.fetch(a,n)}catch(e){throw new ke(`getFeatureFlags request failed: ${e instanceof Error?e.message:String(e)}`,0)}if(200!==o.status)throw new ke(`getFeatureFlags answered HTTP ${o.status}`,o.status);try{c=await o.json()}catch(e){throw new ke("getFeatureFlags answered an unreadable body",o.status)}if(!c||200!==c.status_code||!xe(c.response))throw new ke(`getFeatureFlags answered status_code ${String(c&&c.status_code)}`,o.status);e===this.generation&&await this.apply(c.response)}async apply(e){const t=this.visibleSnapshot(),s=this.deps.now();if(!0===e.not_modified){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return;this.cache={...this.cache,fetchedAt:s,sentUnregistered:this.lastSentUnregistered},this.isMemoryOnly||await this.deps.data.setFeatureFlags(this.cache)}else if(!0===e.partial){if(this.hasValidCache())return;this.cache=this.newCache(e,"",s),this.isMemoryOnly=!0}else this.cache=this.newCache(e,"string"==typeof e.etag?e.etag:"",s),this.isMemoryOnly=!1,await this.deps.data.setFeatureFlags(this.cache);this.visibleSnapshot()!==t&&this.notify()}newCache(e,t,s){return{applicationCode:this.applicationCode,userId:this.userId,flags:Te(e.flags),etag:t,fetchedAt:s,sentUnregistered:this.lastSentUnregistered}}notify(){this.listeners.forEach(e=>{try{e()}catch(e){te.error(e,"Pushwoosh: feature flags update listener failed")}})}schedulePeriodicRefresh(){if(!this.isLoaded)return;clearTimeout(this.timer);const e=Math.max(this.lastRequestAt,this.cache?this.cache.fetchedAt:0),t=Math.max(0,e+36e5-this.deps.now());this.timer=setTimeout(()=>this.sendInBackground(),t)}hasValidCache(){if(!this.cache||!this.isCacheOfCurrentUser(this.cache))return!1;const e=this.deps.now()-this.cache.fetchedAt;return e>=0&&e<=864e5}isCacheOfCurrentUser(e){return e.applicationCode===this.applicationCode&&e.userId===this.userId}visibleSnapshot(){return this.cache&&this.hasValidCache()?Re(this.cache.flags):""}}function xe(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Te(e){const t={};return xe(e)?(Object.keys(e).forEach(s=>{const i=e[s];xe(i)&&"boolean"==typeof i.enabled&&(t[s]={enabled:i.enabled,rule_id:"string"==typeof i.rule_id?i.rule_id:"",properties:xe(i.properties)?i.properties:{}})}),t):t}function Ae(e,t){const s={};return Object.keys(e).forEach(i=>{t-e[i]<We&&(s[i]=e[i])}),s}function Re(e){return Array.isArray(e)?`[${e.map(Re).join(",")}]`:xe(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Re(e[t])}`).join(",")}}`:JSON.stringify(e)}class Me{constructor(e){this.global=e,this._isSafari=this.isSafariBrowser(),this._isOpera=this.isOperaBrowser(),this._isEdge=this.isEdgeBrowser(),this._isFirefox=this.isFirefoxBrowser(),this._isChrome=this.isChromeBrowser(),this._isMacOS=this.isMacOS(),this._isAvailableServiceWorker=this.canUseServiceWorkers(),this._isAvailableNotifications=this.canReceiveNotifications(),this._platform=this.getPlatformType(),this._browserVersion=this.getBrowserVersion(),this._formFactor=this.getFormFactor()}get isEdge(){return this._isEdge}get isSafari(){return this._isSafari}get isOpera(){return this._isOpera}get isAvailableServiceWorker(){return this._isAvailableServiceWorker}get isAvailableNotifications(){return this._isAvailableNotifications}get platform(){return this._platform}get browserVersion(){return this._browserVersion}get formFactor(){return this._formFactor}get isMobile(){return"MOBILE"===this._formFactor}get isDesktop(){return"DESKTOP"===this._formFactor}isSafariBrowser(){return"safari"in this.global&&navigator.userAgent.indexOf("Safari")>-1}isOperaBrowser(){return-1!==navigator.userAgent.indexOf("Opera")||-1!==navigator.userAgent.indexOf("OPR")}isEdgeBrowser(){return navigator.userAgent.indexOf("Edge")>-1}isFirefoxBrowser(){return-1!==navigator.userAgent.toLowerCase().indexOf("firefox")}isChromeBrowser(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)&&!this._isOpera&&!this._isEdge}isMacOS(){return"platform"in navigator&&-1!==navigator.platform.toLowerCase().indexOf("mac")}canUseServiceWorkers(){return!!navigator.serviceWorker&&"PushManager"in this.global&&"Notification"in this.global}canReceiveNotifications(){return this._isSafari&&this._isMacOS||this._isAvailableServiceWorker&&!this._isEdge}getPlatformType(){let e=11;switch(!0){case this._isSafari:e=10;break;case this._isOpera||this._isChrome:e=11;break;case this._isFirefox:e=12;break;case this._isEdge:e=150}return e}getFormFactor(){const e=navigator.userAgentData;if(e&&"boolean"==typeof e.mobile)return e.mobile?"MOBILE":"DESKTOP";return/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?"MOBILE":"DESKTOP"}getBrowserVersion(){const{userAgent:e}=navigator,t=e.match(/\bOPR\/(\d+)/);if(null!==t)return`Opera ${t[1]}`;const s=e.match(/\bEdge\/(\d+)/);if(null!==s)return`Edge ${s[1]}`;const i=e.match(/\bEdg\/(\d+)/);if(null!==i)return`Edge ${i[1]}`;let a=e.match(/(opera|chrome|safari|firefox(?=\/))\/?\s*(\d+)/i)||[];const[,r=""]=a;a=a[2]?[r,a[2]]:[navigator.appName,navigator.appVersion,"-?"];const n=e.match(/version\/([.\d]+)/i);return null!==n&&a.splice(1,1,n[1]),a.join(" ")}}const Ne="pushwoosh-recommendations-views";function Fe(){try{if("undefined"!=typeof sessionStorage)return sessionStorage}catch{}const e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,s)=>{e.set(t,s)}}}class Le{constructor(e){this.deps={fetch:(...e)=>fetch(...e),now:Date.now,storage:Fe(),...e}}async trackProductView(e){!e?.id||this.deps.isCommunicationDisabled()||this.seenRecently(String(e.id))||await this.deps.postEvent("PW_ProductView",{productId:String(e.id),name:e.name,price:e.price,currency:e.currency,category:e.category,productUrl:e.url,imageUrl:e.imageUrl})}async fetch(e){const t=new URLSearchParams({application:await this.deps.getApplicationCode(),strategy:e.strategy});e.fallback&&t.set("fallback",e.fallback),e.limit&&t.set("limit",String(e.limit)),e.productId&&t.set("product_id",e.productId),e.exclude?.length&&t.set("exclude",e.exclude.join(",")),e.block&&t.set("block",e.block);const s={},i=this.deps.isCommunicationDisabled()?"":await this.deps.getHwid();i&&(s["X-PW-HWID"]=i);const a=(this.deps.getEndpoint()||"https://recommender-onsite.svc-nue.pushwoosh.com").replace(/\/+$/,""),r=await this.deps.fetch(`${a}/feed/v1/onsite/products.json?${t}`,{headers:s});if(!r.ok)throw new Error(`Pushwoosh: recommendations request failed with status ${r.status}`);return r.json()}async trackClick(e){e?.productId&&!this.deps.isCommunicationDisabled()&&await this.deps.postEvent("PW_RecommendationClick",{block:e.block,strategy:e.strategy,recoProductId:String(e.productId),position:e.position},{keepalive:!0})}seenRecently(e){const t=this.deps.now(),s=function(e){try{const t=JSON.parse(e||"{}");return null===t||"object"!=typeof t||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>"number"==typeof e))}catch{return{}}}(this.deps.storage.getItem(Ne));if(t-(s[e]??-1/0)<3e4)return!0;const i={[e]:t};Object.keys(s).forEach(e=>{t-s[e]<3e4&&(i[e]=s[e])});try{this.deps.storage.setItem(Ne,JSON.stringify(i))}catch{}return!1}}const Ue="sdkUsageReportedOn";class Oe{constructor(){this.initKeys=new Set,this.events=new Set,this.legacyEvents=new Set,this.isListening=!1}recordInitParams(e){Object.entries(e).forEach(([e,t])=>{this.initKeys.add(e),(e=>null!==e&&"object"==typeof e&&!Array.isArray(e))(t)&&Object.keys(t).forEach(t=>this.initKeys.add(`${e}.${t}`))})}recordEvent(e){this.events.add(e)}recordLegacyEvent(e){this.legacyEvents.add(e)}listen(e){if(this.isListening)return;this.isListening=!0;const t=()=>this.flush(e);document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&t()}),window.addEventListener("pagehide",t)}flush(e){const t=(new Date).toISOString().slice(0,10);try{if(localStorage.getItem(Ue)===t)return;localStorage.setItem(Ue,t)}catch{return}e({init_keys:[...this.initKeys],events:[...this.events],legacy_events:[...this.legacyEvents]},{keepalive:!0}).catch(()=>{})}}function qe(e){switch(e){case c:return"granted_explicit";case"denied":return"denied";default:return"not_determined"}}function Be(e){return"safari"in e?e.safari?.pushNotification:void 0}function je(e,t){try{return Be(e)?.permission(t)}catch{return}}class Ve{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return this.data.getStatusManualUnsubscribed()}async askPermission(){await Notification.requestPermission()}async getTokens(){return this.data.getTokens()}async subscribe(e){const t=e||await this.trySubscribe();if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const s=this.getPushToken(t),i=t.getKey("p256dh"),a=t.getKey("auth");if(!i||!a)throw new Error("Can't get subscription keys!");const r=btoa(String.fromCharCode.apply(String,new Uint8Array(i))),n=btoa(String.fromCharCode.apply(String,new Uint8Array(a)));await this.data.setTokens({publicKey:r,pushToken:s,authToken:n,endpoint:t.endpoint}),await this.api.registerDevice()}async unsubscribe(){const e=await this.getServiceWorkerRegistration(),t=await e.pushManager.getSubscription();await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice(),t&&await t.unsubscribe()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getLastPermissionStatus(),t=this.getPermission();if(e!==t&&(await this.data.setLastPermissionStatus(t),void 0!==e))return!0;const s=await this.getCredentials(),i=this.getPushToken(s),a=await this.data.getTokens(),r=i===(a&&a.pushToken||""),n=await this.data.getIsVapidChanged();return!r||n}async getServiceWorkerRegistration(){if(!this.registration){await this.registerServiceWorker();const e=await this.data.getServiceWorkerUrl();this.registration=await navigator.serviceWorker.getRegistration(e),await this.registration.update()}if(!this.registration)throw new Error("Internal Error: Can't register service worker!");return this.registration}async registerServiceWorker(){const e=await this.data.getServiceWorkerUrl(),t=await this.data.getServiceWorkerScope();let s="";await this.data.getSdkVersion()!==await this.data.getServiceWorkerVersion()&&(s=`?cache_clean=${R()}`),await navigator.serviceWorker.register(`${e}${s}`,{scope:t})}async trySubscribe(){try{return await this.subscribePushManager()}catch(e){return console.error(e),await this.unsubscribe(),this.subscribePushManager()}}async subscribePushManager(){const e=await this.getServiceWorkerRegistration(),t=await this.getApplicationServerKey();return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t?this.urlBase64ToUint8Array(t):null})}async getCredentials(){const e=await this.getServiceWorkerRegistration();return await e.pushManager.getSubscription()}getPushToken(e){return e?e.endpoint:""}async getApplicationServerKey(){return await this.data.getApplicationServerKey()}urlBase64ToUint8Array(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=atob(t),i=new Uint8Array(s.length);for(let e=0;e<s.length;++e)i[e]=s.charCodeAt(e);return i}}class $e{constructor(e,t,s){this.api=e,this.config=s,this.data=t}getPermission(){const{permission:e}=this.getPermissionInfo();return e}checkIsPermissionGranted(){return this.getPermission()===c}checkIsPermissionDefault(){return this.getPermission()===h}async checkIsManualUnsubscribed(){return await this.data.getStatusManualUnsubscribed()}async askPermission(){const e={application:await this.data.getApplicationCode(),hwid:await this.data.getHwid()};return new Promise(t=>{safari.pushNotification.requestPermission(this.config.entrypoint||"https://cp.pushwoosh.com/json/1.3/safari",this.config.webSitePushId,e,()=>t())})}getTokens(){return this.data.getTokens()}async subscribe(){if(!this.checkIsPermissionGranted())return void te.error("You must have permission granted before subscribe!");const{deviceToken:e}=this.getPermissionInfo();await this.data.setTokens({pushToken:e}),await this.api.registerDevice()}async unsubscribe(){await this.data.setTokens({}),await this.data.setStatusManualUnsubscribed(!0),await this.api.unregisterDevice()}async checkIsRegister(){return this.api.checkDeviceSubscribeForPushNotifications()}async checkIsNeedResubscribe(){const e=await this.data.getWebSitePushId(),t=void 0!==e&&this.config.webSitePushId!==e;await this.data.setWebSitePushId(this.config.webSitePushId);const s=await this.data.getLastPermissionStatus(),i=this.getPermission();return s!==i&&(await this.data.setLastPermissionStatus(i),void 0!==s)||t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class He{constructor(){this.ready=!1,this.rawInitParams={},this.isPushDisabled=!1,this.isInitAborted=!1,this.isPushPermissionWatched=!1,this.subscriptionInFlight=null,this.isWebVapidConfigured=!1,this.isLegacySafari=!1,this.waitForPermissionWork=N(1e4),this.moduleRegistry={},this.sdkUsage=new Oe,this.addEventHandler=(e,t)=>{this.sdkUsage.recordEvent(e),this.eventBus.addEventHandler(e,t)},this.addSdkEventHandler=(e,t)=>this.eventBus.addEventHandler(e,t),this.removeEventHandler=(e,t)=>this.eventBus.removeEventHandler(e,t),this.dispatchEvent=(e,t)=>this.eventBus.dispatchEvent(e,t),this.debug={async showLog(){const e=await X.getAll();console.log(e)},async showKeyValues(){const e=await J.getAll();console.log(e)},async showMessages(){(await Q.getAll()).forEach(e=>console.log(e))}},this.eventBus=new se,this.data=new ve,this.apiClient=new Pe(this.data),this.api=new Se(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled,()=>this.getInitUserId(),()=>this.getPushPermissionStatus()),this.featureFlags=new _e({eventBus:this.eventBus,data:this.data,postEvent:(e,t)=>this.api.postEvent(e,t),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,isDeviceRegistered:()=>this.isDeviceRegistered()}),this.recommendations=new Le({postEvent:(e,t,s)=>this.api.postEvent(e,t,s),isCommunicationDisabled:()=>!!this.isCommunicationDisabled,getApplicationCode:()=>this.data.getApplicationCode(),getHwid:()=>this.data.getHwid(),getEndpoint:()=>this.initParams?.recommendations?.endpoint}),this.platformChecker=new Me(A()),this.inboxModel=new be(this.eventBus,this.data,this.api),this.pwinbox=new pe(this.data,this.api,this.inboxModel,this.moduleRegistry,()=>this.loadWebPopupsWidget())}async loadWebPopupsWidget(){if(this.moduleRegistry.webPopups||!this.widgetLoader||!1===this.initParams?.webPopups?.enable)return this.moduleRegistry.webPopups;let e;const t=new Promise(t=>{e=setTimeout(()=>t(!1),1e4)});return await Promise.race([this.widgetLoader("web-popups"),t]),clearTimeout(e),this.moduleRegistry.webPopups}push(e){if(M(e))this.subscribeToLegacyEvents(u,e);else{if(!Array.isArray(e))throw new Error("Invalid command!");if("init"===e[0])this.initialize(e[1]).catch(e=>{console.error("Pushwoosh: Error during initialization",e)});else if(!this.subscribeToLegacyEvents(e[0],e[1]))throw console.log("Pushwoosh: Unknown command",e),new Error("Unknown command!")}}async subscribe(e=!0){const t=this.runSubscribe(e);this.subscriptionInFlight=t;try{await t}finally{this.subscriptionInFlight===t&&(this.subscriptionInFlight=null)}}async runSubscribe(e){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.isPushDisabled)throw new Error('Push notifications are disabled by the "pushNotifications" init param!');const t=this.requireDriver();if(t.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await t.askPermission();const e=t.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e}),e!==h&&this.announcePermissionChange(e)}const s=t.getPermission(),i=await this.data.getStatusManualUnsubscribed(),a=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(s===c){this.eventBus.dispatchEvent("permission-granted",{});return(!a&&!i||e)&&await t.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if("denied"===s)return this.eventBus.dispatchEvent("permission-denied",{}),a&&await t.unsubscribe(),void this.reportPushPermissionChangeInBackground()}async unsubscribe(){try{await this.requireDriver().unsubscribe()}catch(e){throw te.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(a)===n}isDeviceUnregistered(){return localStorage.getItem(a)===o}async isSubscribed(){return this.api.checkDeviceSubscribeForPushNotifications()}async isCommunicationEnabled(){return!await this.data.getStatusCommunicationDisabled()}async setCommunicationEnabled(e=!0){if(await this.data.setCommunicationEnabled(e),e){this.isCommunicationDisabled=!1,await this.data.setStatusDropAllData(!1),await this.finishInit();const e=this.driver?.checkIsPermissionGranted();e&&(await this.api.registerDevice(),await this.sendData())}else this.featureFlags.reset(),await this.api.unregisterDevice();this.eventBus.dispatchEvent("change-enabled-communication",{isEnabled:e});const t=await this.data.getDeviceType();await this.api.postEvent("GDPRConsent",{channel:e,device_type:t})}async removeAllDeviceData(){const e=await this.data.getDeviceType();await this.api.postEvent("GDPRDelete",{status:!0,device_type:e}),await this.api.deleteDevice(),await this.data.clearAll(),this.featureFlags.reset(),await this.data.setStatusDropAllData(!0)}trackProductView(e){return this.recommendations.trackProductView(e)}async getHWID(){return await this.data.getHwid()}async getPushToken(){const{pushToken:e}=await this.data.getTokens();return e}async getUserId(){return await this.data.getUserId()}async getParams(){return await this.api.getParams()}isAvailableNotifications(){return this.platformChecker.isAvailableNotifications}isPushAvailable(){return!!this.driver&&!this.isPushDisabled}requireDriver(){if(!this.driver)throw new Error("Push notifications are not available: the browser does not support them, or the application has no push configuration. Web popups, inbox, events and tags do not require it.");return this.driver}async initialize(e){this.rawInitParams={...e},this.sdkUsage.recordInitParams(e),this.initParams={...T,...e},this.isInitAborted=!1;const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(te.setLevel(t||e.logLevel||"error"),e.logLevel&&await this.data.setLogLevel(e.logLevel),this.isPushDisabled=!1===e.pushNotifications,this.isAvailableNotifications()||te.info("Pushwoosh: push notifications are not available in this browser, initializing without them"),!e.applicationCode)throw new Error("Can't find application code!");const s=!1===e.communicationEnabled,i=await this.data.getCommunicationEnabled(),a=await this.data.getStatusCommunicationDisabled();(s&&!0!==i||!1===i||a)&&(this.isCommunicationDisabled=!0);const r=await this.data.getApplicationCode(),n=await this.isUserIdChanged();(!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail(),await this.data.setStatusLanguageWasChanged(!1)),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.resolvePlatformType()),await this.data.setFormFactor(this.platformChecker.formFactor),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion());if(await this.data.getStatusLanguageWasChanged()||await this.data.setLanguage(e.tags?.Language||navigator.language),await this.data.setApiEntrypoint(e.pushwooshUrl||""),await this.data.setApiToken(e.apiToken||""),await this.data.setSdkVersion("3.104.1"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{if(await this.finishInit(),this.isInitAborted)return;try{this.initParams.inboxWidget?.enable&&await this.api.ensureDeviceRegistered(),await this.inboxModel.updateMessages()}catch(e){te.write("error",e)}const e=await this.data.getDelayedEvent();if(e){const{type:t,payload:s}=e;this.emitLegacyEventsFromServiceWorker(t,s),await this.data.setDelayedEvent(null)}if(this.isLegacySafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){if(await this.ensureHwid(),await this.data.setInitParams(this.initParams),await this.initStep("loadConfig",()=>this.loadConfig()),await this.data.setDeviceType(this.resolvePlatformType()),await this.initStep("applicationOpen",()=>this.open()),await this.initStep("sendData",()=>this.sendData()),!this.isInitAborted){if(this.isAvailableNotifications()){await this.data.getApplicationServerKey()?await this.initStep("initPushNotifications",()=>this.initPushNotifications(this.initParams)):te.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.knownPermission=this.readPermission(),await this.initStep("watchPushPermission",()=>this.watchPushPermission())}await this.featureFlags.start().catch(e=>te.error(e,"Pushwoosh: feature flags failed to start")),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),this.sdkUsage.listen((e,t)=>this.api.sdkUsage(e,t)),"serviceWorker"in navigator&&(navigator.serviceWorker.onmessage=e=>this.onServiceWorkerMessage(e)),localStorage.setItem("pushwoosh-websdk-status","init"),document.dispatchEvent(new CustomEvent("pushwoosh.initialized",{detail:{pw:this}}))}}async initStep(e,t){if(!this.isInitAborted)try{await t()}catch(t){const s=function(e){const t=e?.statusCode;return"number"==typeof t?t:void 0}(t);if(void 0!==s&&-1!==x.indexOf(s))return void this.abortInit(s);te.error(t,`Pushwoosh: init step "${e}" failed`)}}abortInit(e){this.isInitAborted=!0,te.error(`Pushwoosh: initialization stopped. The Pushwoosh API rejected the application code "${this.initParams.applicationCode}" (status_code: ${e}). Check the applicationCode init param against the application in your Pushwoosh Control Panel.`)}resolvePlatformType(){this.isLegacySafari=this.detectLegacySafari();return!this.isLegacySafari&&(this.initParams.unifiedPlatform||this.platformChecker.isSafari)?11:this.platformChecker.getPlatformType()}detectLegacySafari(){if(!this.platformChecker.isSafari)return!1;if(!this.platformChecker.isAvailableServiceWorker)return!0;const{safariWebsitePushID:e,unifiedPlatform:t}=this.initParams??{};return!!function(e,t){const s=t?je(e,t):void 0;return s?.permission===c&&!!s.deviceToken}(A(),e)||!t&&!this.isWebVapidConfigured}async ensureHwid(e=!1){if(await this.readHwid()&&!e)return;const t=this.initParams.applicationCode+"_"+R();try{await this.data.setHwid(t),await this.data.getHwid()!==t&&te.info(_)}catch(e){te.info(e,_)}}async readHwid(){try{return await this.data.getHwid()}catch{return""}}getInitUserId(){const{userId:e}=this.initParams||{};return e&&"user_id"!==e?e:void 0}async isUserIdChanged(){const{userId:e}=this.initParams,t=await this.data.getUserId(),s=await this.data.getStatusUserIdWasChanged();return!!e&&"user_id"!==e&&e!==t&&!s}async defaultProcess(){const e=this.requireDriver(),t=e.getPermission();"granted"===t&&await this.data.setLastPermissionStatus(t);const s=await this.data.getStatusCommunicationDisabled(),i=await this.data.getStatusDropAllData(),a=await e.checkIsNeedResubscribe();if(s||i)return void await this.unsubscribe();a&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const r=await this.data.getStatusManualUnsubscribed(),n=!a&&await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(t){case h:this.eventBus.dispatchEvent("permission-default",{}),n&&await this.unsubscribe();break;case"denied":this.eventBus.dispatchEvent("permission-denied",{}),n&&await this.unsubscribe();break;case c:this.eventBus.dispatchEvent("permission-granted",{}),r&&n&&await this.unsubscribe(),(!n&&!r||a)&&await this.subscribe(!0)}this.reportPushPermissionChangeInBackground()}onServiceWorkerMessage(e){const{data:t={}}=e||{},{type:s="",payload:i={}}=t||{};this.emitLegacyEventsFromServiceWorker(s,i)}async open(e){let t=await this.data.getLastOpenApplicationTime();const s=Date.now();t||(t=0);(e||!(s-t<36e5))&&(await this.data.setLastOpenApplicationTime(s),await this.api.applicationOpen())}getPushPermissionStatus(){return this.driver?qe(this.driver.getPermission()):function(e,t){const s=Be(e);if(s&&t){const s=je(e,t);return s?qe(s.permission):"unsupported"}return"PushManager"in e&&"Notification"in e?qe(e.Notification.permission):s?"not_determined":"unsupported"}(A(),this.isLegacySafari?this.initParams?.safariWebsitePushID:void 0)}readPermission(){try{if(this.driver)return this.driver.getPermission();const e=A();return"Notification"in e?e.Notification.permission:void 0}catch{return}}announcePermissionChange(e){e!==this.knownPermission&&(this.knownPermission=e,this.eventBus.dispatchEvent("change-permission",{permission:e}))}async reportPushPermissionChange(){const e=null!==this.subscriptionInFlight&&!await this.waitForPermissionWork(this.subscriptionInFlight);if(this.isCommunicationDisabled||!this.driver||this.api.isPushPermissionStatusReported())return;const t=this.driver.getPermission(),s=await this.api.checkDeviceSubscribeForPushNotifications();let i=!1;if(t===c)s||e||this.isPushDisabled||await this.data.getStatusManualUnsubscribed()||(this.subscribe(!1).catch(e=>te.error(e,"Pushwoosh: re-subscribe after a permission grant failed")),this.subscriptionInFlight&&await this.waitForPermissionWork(this.subscriptionInFlight));else if(s){const e=this.dropRevokedSubscription(t).catch(e=>te.error(e,"Pushwoosh: unsubscribe after a permission revoke failed"));i=!await this.waitForPermissionWork(e)}await this.api.reportPushPermissionStatus(i)}async dropRevokedSubscription(e){await this.data.setLastPermissionStatus(e),await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1)}reportPushPermissionChangeInBackground(){this.reportPushPermissionChange().catch(e=>te.error(e,"Pushwoosh: registerDevice after a permission change failed"))}async watchPushPermission(){if(!this.isPushPermissionWatched&&"function"==typeof navigator.permissions?.query)try{(await navigator.permissions.query({name:"notifications"})).addEventListener("change",()=>{const e=this.readPermission();e&&this.announcePermissionChange(e),this.reportPushPermissionChangeInBackground()}),this.isPushPermissionWatched=!0}catch(e){te.info(e,"Pushwoosh: notifications permission can not be watched")}}async sendData(){const e=this.initParams,t=await this.data.getUserId();if(e.userId&&"user_id"!==e.userId&&e.userId!==t)try{await this.api.registerUser(e.userId,!1)}catch(e){te.error(e,"Pushwoosh: registerUser failed")}const s=[{test:async()=>{if(await this.data.getStatusEmailWasChanged())return!1;const t=await this.data.getEmail();return!!e.email&&e.email!==t},task:async()=>{await this.api.registerEmail(e.email,!1)}},{test:async()=>{if(await this.data.getStatusSmsNumberWasChanged())return!1;const t=await this.data.getSmsNumber();return!!e.smsNumber&&e.smsNumber!==t},task:async()=>{await this.api.registerSmsNumber(e.smsNumber,!1)}},{test:async()=>{if(await this.data.getStatusWhatsAppNumberWasChanged())return!1;const t=await this.data.getWhatsAppNumber();return!!e.whatsAppNumber&&e.whatsAppNumber!==t},task:async()=>{await this.api.registerWhatsappNumber(e.whatsAppNumber,!1)}},{test:async()=>!!e.tags||await this.data.getStatusLanguageWasChanged(),task:async()=>{const t=await this.data.getLanguage(),s={...e.tags||{},Language:t};await this.api.setTags(s)}}];await Promise.all(s.map(async e=>{try{await e.test()&&await e.task()}catch(e){console.error("Pushwoosh: Error during data registration",e)}}))}async loadConfig(){this.isWebVapidConfigured=await this.data.getWebVapidConfigured();const e=await this.api.getConfig(["vapid_key","web_vapid_configured","events","subscription_prompt","popup_forms","web_sdk","web_sdk_modules"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(await this.applyServerInitParams(function(e){if(void 0!==e?.web_sdk)return e.web_sdk;const t=e?.web_sdk_modules;return void 0!==t?{inboxWidget:t.inboxWidget,webPopups:t.webPopups}:void 0}(t)),t.events&&t.events.length){t.events.some(e=>e===W)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),void 0!==e&&e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}const e=t.web_vapid_configured??this.isWebVapidConfigured;e!==this.isWebVapidConfigured&&(this.isWebVapidConfigured=e,await this.data.setWebVapidConfigured(e))}}async applyServerInitParams(e){const t=function(e,t){if(!t)return{};const s={};if(ie.forEach(e=>{void 0!==t[e]&&(s[e]=t[e])}),void 0!==t.inboxWidget&&(s.inboxWidget={...e.inboxWidget,...t.inboxWidget}),void 0!==t.webPopups&&(s.webPopups={...e.webPopups,...t.webPopups}),void 0!==t.subscriptionWidget){const i=ae(e.subscribeWidget,t.subscribeWidget)??e.subscribeWidget;return s.subscribeWidget={...i,enable:!1},s.subscribePopup={...e.subscribePopup,enable:!1},s}const i=ae(e.subscribeWidget,t.subscribeWidget);return i&&(s.subscribeWidget=i),s}(this.rawInitParams,e);0!==Object.keys(t).length&&(this.initParams={...this.initParams,...t},await this.data.setInitParams(this.initParams))}async initPushNotifications(e){if(await this.data.setDefaultNotificationImage(e.defaultNotificationImage),await this.data.setDefaultNotificationTitle(e.defaultNotificationTitle),await this.data.setServiceWorkerUrl(e.serviceWorkerUrl),await this.data.setServiceWorkerScope(e.scope),await this.initDriver(),this.driver){if(this.isPushDisabled)return te.info('Pushwoosh: push notifications are disabled by the "pushNotifications" init param'),void await this.warnAboutKeptSubscription();try{await this.defaultProcess()}catch(e){te.error(e,"Internal error: defaultProcess fail")}}else te.info("Pushwoosh: push service driver was not created, skipping push initialization")}async warnAboutKeptSubscription(){const{pushToken:e}=await this.data.getTokens();e&&te.error('Pushwoosh: push notifications are disabled by the "pushNotifications" init param, but this device is still subscribed and will keep receiving notifications. Call Pushwoosh.unsubscribe() to unsubscribe it.')}async initDriver(){if(this.isLegacySafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new $e(this.api,this.data,{webSitePushId:e})):void te.info("Safari push needs safariWebsitePushID in initParams; Safari 16+ can use web VAPID keys of the application instead.")}te.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new Ve(this.api,this.data,{}))}async sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window,s=function(){const{pathname:e}=window.location;try{return decodeURIComponent(e)}catch{return e}}(),i=await this.data.getDeviceType();this.api.postEvent(W,{url:t,path:s,title:e,device_type:i})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===u:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in F:this.eventBus.addEventHandler(F[e].name,s=>{const{prop:i}=F[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s&&this.sdkUsage.recordLegacyEvent(e),s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case f:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case y:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case v:this.eventBus.dispatchEvent("hide-notification",{notification:t});break;case S:this.eventBus.dispatchEvent("receive-inbox-message",{message:t})}}}return t})());
|
|
2
2
|
//# sourceMappingURL=npm.js.map
|