web-push-notifications 3.49.2 → 3.49.3
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/core/events.types.d.ts +1 -0
- package/npm.js +1 -1
- package/npm.js.map +1 -1
- package/package.json +1 -1
- package/service-worker.js +1 -1
package/core/events.types.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export interface EventHandlerMap {
|
|
|
5
5
|
'change-enabled-communication': EventHandler<EventPayload<{
|
|
6
6
|
isEnabled: boolean;
|
|
7
7
|
}>>;
|
|
8
|
+
'communication-disabled': EventHandler<EventPayload<Record<string, never>>>;
|
|
8
9
|
register: EventHandler<EventPayload<Record<string, never>>>;
|
|
9
10
|
unregister: EventHandler<EventPayload<Record<string, never>>>;
|
|
10
11
|
'show-subscription-widget': EventHandler<EventPayload<Record<string, never>>>;
|
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";var 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=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Pushwoosh:()=>ge});const s="/pushwoosh-service-worker.js",i="deviceRegistrationStatus",a="registered",r="unregistered",n="denied",o="granted",c="default",h="onReady",u="onSubscribe",d="onUnsubscribe",g="onRegister",l="onPermissionPrompt",p="onPermissionDenied",m="onPermissionGranted",w="onSWInitError",b="onPushDelivery",v="onNotificationClick",y="onNotificationClose",f="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",P="onUpdateInboxMessages",C="onShowNotificationPermissionDialog",k="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",I="onHideSubscriptionWidget",x="PW_SiteOpened",E={autoSubscribe:!0,serviceWorkerUrl:s};function M(){return globalThis}function T(){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 _=e=>"function"==typeof e,N={[g]:{name:"register"},[u]:{name:"subscribe"},[d]:{name:"unsubscribe"},[w]:{name:"initialize-service-worker-error",prop:"error"},[b]:{name:"receive-push",prop:"notification"},[v]:{name:"open-notification",prop:"notification"},[y]:{name:"hide-notification",prop:"notification"},[f]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[P]:{name:"update-inbox-messages",prop:"messages"},[C]:{name:"show-notification-permission-dialog"},[k]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[I]:{name:"hide-subscription-widget"},[p]:{name:"permission-denied"},[l]:{name:"permission-default"},[m]:{name:"permission-granted"}},W="keyValue",A="messages",R="log",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const U=[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})})];const B=[q(W,function(e){e.createObjectStore(W,{keyPath:"key"})}),q(R,function(e){const t=e.createObjectStore(R,{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(A,function(e){e.createObjectStore(A,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})})];class L{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()}}class V{constructor(e=new L){this.migrations={initial:B,"2018/11/26":U},this.dateModule=e}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter(e=>"initial"!==e).sort((e,t)=>{const s=new L(new Date(e)),i=new L(new Date(t));return s.getTimestamp()-i.getTimestamp()}).map(e=>this.migrations[e])}}class j{constructor(e,t=new V){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach(e=>{this.applyMigrationsPack(e)})}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function H(e,t){console.info("onversionchange",t),e.close()}let $;function F(e){return($||($=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=H.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=H.bind(null,s,t),new j(s).applyMigrations()}})),$).then(t=>new Promise((s,i)=>e(t,s,i)))}class K{_add(e){return F((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 F((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 F((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 G=(z=W,{get:(e,t)=>F((s,i,a)=>{const r=s.transaction(z).objectStore(z).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:()=>F((e,t,s)=>{const i={},a=e.transaction(z).objectStore(z).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)=>F((s,i,a)=>{const r=s.transaction([z],"readwrite").objectStore(z).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 z;const J=new class extends K{constructor(){super(...arguments),this.name=R,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)}},Y=new class extends K{constructor(){super(...arguments),this.name=A,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Q={error:1,info:2,debug:3};let X=3;const Z={setLevel(e){Q[e]||(e="error"),X=Q[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),J.add(e,t,s)}};Object.keys(Q).forEach(e=>{const t=Q[e];Z[e]=(...s)=>{t<=X&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class ee{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||T(),i=this.handlers[e];return i?(i.forEach(e=>{_(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}class te{constructor(e,t,s,i=new L){this.data=e,this.api=t,this.inboxModel=s,this.dateModule=i,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}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=s||await this.data.getDefaultNotificationImage(),h=i||await this.data.getDefaultNotificationTitle(),u=JSON.parse(t);return this.dateModule.date=new Date(1e3*parseInt(a)),this.dateModule.setLocal(),{title:h,imageUrl:c,code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,u),link:u?.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=JSON.parse(t.action_params),i=this.messageTypeFactory(t.action_type,s);2===i&&null!=s.l?document.location.href=s.l:3===i&&null!=s.l&&window.history.go(s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}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.inboxModel.updateMessages()}}class se{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 ie{dbVersionChangeHandler(e,t){console.info("onversionchange",t),e.close()}dbRequestSuccessHandler(e,t){const s=t.target.result;s.onversionchange=e=>{this.dbVersionChangeHandler(s,e)},e(s)}dbRequestUpgradeNeededHandler(e){const t=e.target.result;t.onversionchange=e=>{this.dbVersionChangeHandler(t,e)};new j(t).applyMigrations()}getDB(){return new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=t=>{this.dbRequestSuccessHandler(e,t)},s.onupgradeneeded=e=>{this.dbRequestUpgradeNeededHandler(e)},s.onerror=()=>t(s.error)})}async put(e,t,s){const i=await this.getDB(),a=new se(i,e),r=await a.put(t,s);return i.close(),r}async delete(e,t){const s=await this.getDB(),i=new se(s,e),a=await i.delete(t);return s.close(),a}async get(e,t,s){const i=await this.getDB(),a=new se(i,e),r=await a.get(t,s);return i.close(),r}async getAll(e){const t=await this.getDB(),s=new se(t,e),i=await s.getAll();return t.close(),i||[]}async count(e,t){const s=await this.getDB(),i=new se(s,e),a=await i.count(t);return s.close(),a}async countByIndex(e,t,s){const i=await this.getDB(),a=new se(i,e);a.index=t;const r=await a.countByIndex(s);return i.close(),r}}class ae{constructor(e,t,s,i=new ie,a=new L){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 te(this.data,this.api,this)})}}const re=e=>`params.${e}`;class ne{constructor(e=G){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","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"];for(const t of e)await this.store.set(re(t),void 0)}async setApplicationCode(e){await this.store.set(re("applicationCode"),e)}async getApplicationCode(){return this.store.get(re("applicationCode"))}async setApiToken(e){return await this.store.set(re("apiToken"),e)}async getApiToken(){return this.store.get(re("apiToken"))}async setHwid(e){await this.store.set(re("hwid"),e)}async getHwid(){return this.store.get(re("hwid"))}async setDeviceType(e){await this.store.set(re("deviceType"),e)}async getDeviceType(){return this.store.get(re("deviceType"))}async setDeviceModel(e){await this.store.set(re("deviceModel"),e)}async getDeviceModel(){return this.store.get(re("deviceModel"))}async setLanguage(e){await this.store.set(re("language"),e)}async getLanguage(){return this.store.get(re("language"),"en")}async setApiEntrypoint(e){await this.store.set(re("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(re("apiEntrypoint"),"https://cp.pushwoosh.com/json/1.3/")}async setTokens(e){await this.store.set(re("tokens"),e)}getTokens(){return this.store.get(re("tokens"))}async setApplicationServerKey(e){await this.store.set(re("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(re("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(re("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(re("isVapidChanged"),!1)}async setWebSitePushId(e){await this.store.set(re("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(re("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(re("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(re("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(re("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(re("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(re("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(re("userId"))}async setStatusUserIdWasChanged(e){await this.store.set(re("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(re("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(re("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(re("email"))}async setStatusEmailWasChanged(e){await this.store.set(re("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(re("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(re("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(re("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(re("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(re("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(re("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(re("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(re("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(re("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(re("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(re("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(re("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(re("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(re("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(re("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(re("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(re("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(re("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(re("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(re("sdkVersion"),e)}async getSdkVersion(){return this.store.get(re("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(re("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(re("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(re("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(re("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(re("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(re("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(re("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(re("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(re("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(re("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(re("features"),e)}async getFeatures(){return this.store.get(re("features"))}async setInitParams(e){await this.store.set(re("init"),e)}async getInitParams(){return this.store.get(re("init"))}async setInboxLastRequestCode(e){await this.store.set(re("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(re("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(re("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(re("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(re("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(re("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(re("delayedEvent"),e)}getDelayedEvent(){return this.store.get(re("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(re("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(re("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(re("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(re("promptLastSeenTime"),0)}}class oe{constructor(e=new ne,t=Z){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",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){return this.createRequest("postEvent",e)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}pageVisit(e,t){return this.createRequest("pageVisit",e,t)}setPurchase(e){return this.createRequest("setPurchase",e)}async createRequest(e,t,s){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=s||i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:M().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n}),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=`status: ${e.status}. statusText: ${e.statusText}.`;try{const s=await e.json();s&&s.status_message&&(t+=` status_code: ${s.status_code}. status_message: ${s.status_message}.`)}catch(e){}throw new Error(t)}const t=await e.json();if(200!==t.status_code)throw new Error(`Error code: ${t.status_code}. Error text: ${t.status_message}`);return t}}class ce{constructor(e,t=new ne,s=new oe,i=()=>!1){this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i}async checkDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(i);if(void 0===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(i,e&&s?a:r),t=localStorage.getItem(i)}return t===a}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(e)}async registerDevice(){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=await this.apiClient.registerDevice({...e,push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(i,a),this.eventBus.dispatchEvent("register",{}),s}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return localStorage.setItem(i,r),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(i,r),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("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 registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),t&&await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject("Invalid Email format");const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.apiClient.registerEmail({...a,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),r}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");if(!/^\+?[0-9]+$/.test(e))return Promise.reject("Invalid Phone number format: +1234567890");const{application:s,userId:i}=await this.getRequestParams(),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("Communication is disabled");if(!/^whatsapp:\+?[0-9]+$/.test(e))return Promise.reject("Invalid WhatsApp number format: whatsapp:+1234567890");const{application:s,userId:i}=await this.getRequestParams(),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 postEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");const s=await this.getRequestParams(),i=new Date,a=i.getTime(),r=Math.floor(a/1e3),n=r-i.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(t.msgHash)return Promise.reject("attribute msgHash already defined");t={...t,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:e,timestampUTC:r,timestampCurrent:n,attributes:t});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}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 pageVisit(e){const t=await this.getRequestParams(),s=await this.data.getFeatures(),i=s&&s.page_visit&&s.page_visit.entrypoint;if(i)return this.apiClient.pageVisit({...t,...e},i)}async setPurchase(e){const t=await this.getRequestParams();return this.apiClient.setPurchase({...t,...e})}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.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId(),i=await this.data.getDeviceType(),a=await this.data.getDeviceModel(),r=await this.data.getLanguage(),n=await this.data.getSdkVersion();return{application:e,hwid:t,userId:s||t,device_type:i,device_model:a,timezone:60*-(new Date).getTimezoneOffset(),language:r,v:n}}}class he{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()}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}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}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(" ")}}class ue{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===o}checkIsPermissionDefault(){return this.getPermission()===c}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 Z.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)return await this.data.setLastPermissionStatus(t),!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=${T()}`),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 de{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()===o}checkIsPermissionDefault(){return this.getPermission()===c}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 Z.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),!0):t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class ge{constructor(){this.ready=!1,this.moduleRegistry={},this.addEventHandler=(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 J.getAll();console.log(e)},async showKeyValues(){const e=await G.getAll();console.log(e)},async showMessages(){(await Y.getAll()).forEach(e=>console.log(e))}},this.eventBus=new ee,this.data=new ne,this.apiClient=new oe(this.data),this.api=new ce(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled),this.platformChecker=new he(M()),this.inboxModel=new ae(this.eventBus,this.data,this.api),this.pwinbox=new te(this.data,this.api,this.inboxModel)}push(e){if(_(e))this.subscribeToLegacyEvents(h,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){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.driver.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await this.driver.askPermission();const e=this.driver.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e})}const t=this.driver.getPermission(),s=await this.data.getStatusManualUnsubscribed(),i=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(t===o){this.eventBus.dispatchEvent("permission-granted",{});return(!i&&!s||e)&&await this.driver.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if(t===n)return this.eventBus.dispatchEvent("permission-denied",{}),void(i&&await this.driver.unsubscribe())}async unsubscribe(){try{await this.driver.unsubscribe()}catch(e){throw Z.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(i)===a}isDeviceUnregistered(){return localStorage.getItem(i)===r}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();this.driver.checkIsPermissionGranted()&&(await this.api.registerDevice(),await this.sendData())}else 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(),await this.data.setStatusDropAllData(!0)}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}async sendStatisticsVisitedPage(){const{document:{title:e},location:{origin:t,pathname:s,href:i}}=window;await this.api.pageVisit({title:e,url_path:`${t}${s}`,url:i})}async initialize(e){this.initParams={...E,...e};const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(Z.setLevel(t||e.logLevel||"error"),!this.isAvailableNotifications())return;if(!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();if((!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail()),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.platformChecker.getPlatformType()),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion()),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.49.2"),!this.isCommunicationDisabled){await this.finishInit();try{await this.inboxModel.updateMessages()}catch(e){Z.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.platformChecker.isSafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){await this.ensureHwid(),await this.loadConfig(),await this.open(),await this.sendData();await this.data.getApplicationServerKey()?await this.initPushNotifications(this.initParams):Z.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),"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 ensureHwid(e=!1){await this.data.getHwid()&&!e||await this.data.setHwid(this.initParams.applicationCode+"_"+T())}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.driver.getPermission();"granted"===e&&await this.data.setLastPermissionStatus(e);const t=await this.data.getStatusCommunicationDisabled(),s=await this.data.getStatusDropAllData(),i=await this.driver.checkIsNeedResubscribe();if(t||s)return void await this.unsubscribe();i&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const a=await this.data.getStatusManualUnsubscribed(),r=await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(e){case c:this.eventBus.dispatchEvent("permission-default",{}),r&&await this.unsubscribe();break;case n:this.eventBus.dispatchEvent("permission-denied",{}),r&&await this.unsubscribe();break;case o:this.eventBus.dispatchEvent("permission-granted",{}),a&&r&&await this.unsubscribe(),(!r&&!a||i)&&await this.subscribe(!0)}}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())}async sendData(){const e=this.initParams,t=await this.data.getUserId();e.userId&&"user_id"!==e.userId&&e.userId!==t&&await this.api.registerUser(e.userId,!1);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,task:async()=>{await this.api.setTags(e.tags)}}];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(){const e=await this.api.getConfig(["page_visit","vapid_key","web_in_apps","events","subscription_prompt"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(t.page_visit&&t.page_visit.enabled&&(await G.set("PAGE_VISITED_URL",t.page_visit.entrypoint),this.sendStatisticsVisitedPage()),t.events&&t.events.length){t.events.some(e=>e===x)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}}}async initPushNotifications(e){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.data.setInitParams(e),await this.initDriver();try{await this.defaultProcess()}catch(e){Z.error(e,"Internal error: defaultProcess fail")}}async initDriver(){if(this.platformChecker.isSafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new de(this.api,this.data,{webSitePushId:e})):void Z.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}Z.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new ue(this.api,this.data,{}))}sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window;this.api.postEvent(x,{url:t,title:e,device_type:this.platformChecker.platform})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===h:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in N:this.eventBus.addEventHandler(N[e].name,s=>{const{prop:i}=N[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case b:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case v:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case y: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";var 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=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Pushwoosh:()=>ge});const s="/pushwoosh-service-worker.js",i="deviceRegistrationStatus",a="registered",r="unregistered",n="denied",o="granted",c="default",h="onReady",u="onSubscribe",d="onUnsubscribe",g="onRegister",l="onPermissionPrompt",p="onPermissionDenied",m="onPermissionGranted",w="onSWInitError",b="onPushDelivery",v="onNotificationClick",y="onNotificationClose",f="onChangeCommunicationEnabled",S="onPutNewMessageToInboxStore",P="onUpdateInboxMessages",C="onShowNotificationPermissionDialog",k="onHideNotificationPermissionDialog",D="onShowSubscriptionWidget",I="onHideSubscriptionWidget",x="PW_SiteOpened",E={autoSubscribe:!0,serviceWorkerUrl:s};function M(){return globalThis}function T(){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 _=e=>"function"==typeof e,N={[g]:{name:"register"},[u]:{name:"subscribe"},[d]:{name:"unsubscribe"},[w]:{name:"initialize-service-worker-error",prop:"error"},[b]:{name:"receive-push",prop:"notification"},[v]:{name:"open-notification",prop:"notification"},[y]:{name:"hide-notification",prop:"notification"},[f]:{name:"change-enabled-communication",prop:"isEnabled"},[S]:{name:"receive-inbox-message",prop:"message"},[P]:{name:"update-inbox-messages",prop:"messages"},[C]:{name:"show-notification-permission-dialog"},[k]:{name:"hide-notification-permission-dialog",prop:"permission"},[D]:{name:"show-subscription-widget"},[I]:{name:"hide-subscription-widget"},[p]:{name:"permission-denied"},[l]:{name:"permission-default"},[m]:{name:"permission-granted"}},W="keyValue",A="messages",R="log",O="inboxMessages";function q(e,t){return function(s){s.objectStoreNames.contains(e)||t(s)}}const U=[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})})];const B=[q(W,function(e){e.createObjectStore(W,{keyPath:"key"})}),q(R,function(e){const t=e.createObjectStore(R,{keyPath:"id",autoIncrement:!0});t.createIndex("environment","environment",{unique:!1}),t.createIndex("date","date",{unique:!1}),t.createIndex("type","type",{unique:!1})}),q(A,function(e){e.createObjectStore(A,{keyPath:"id",autoIncrement:!0}).createIndex("date","date",{unique:!1})})];class L{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()}}class V{constructor(e=new L){this.migrations={initial:B,"2018/11/26":U},this.dateModule=e}get initial(){return this.migrations.initial}get dateSorted(){return Object.keys(this.migrations).filter(e=>"initial"!==e).sort((e,t)=>{const s=new L(new Date(e)),i=new L(new Date(t));return s.getTimestamp()-i.getTimestamp()}).map(e=>this.migrations[e])}}class j{constructor(e,t=new V){this.db=e,this.migrationsBuilder=t}applyMigrations(){this.applyMigrationsPack(this.migrationsBuilder.initial),this.migrationsBuilder.dateSorted.forEach(e=>{this.applyMigrationsPack(e)})}applyMigrationsPack(e){e.forEach(e=>{e(this.db)})}}function H(e,t){console.info("onversionchange",t),e.close()}let $;function F(e){return($||($=new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=s=>{const i=s.target.result;i.onversionchange=H.bind(null,i,t),e(i)},s.onerror=()=>t(s.error),s.onupgradeneeded=e=>{const s=e.target.result;s.onversionchange=H.bind(null,s,t),new j(s).applyMigrations()}})),$).then(t=>new Promise((s,i)=>e(t,s,i)))}class K{_add(e){return F((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 F((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 F((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 G=(z=W,{get:(e,t)=>F((s,i,a)=>{const r=s.transaction(z).objectStore(z).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:()=>F((e,t,s)=>{const i={},a=e.transaction(z).objectStore(z).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)=>F((s,i,a)=>{const r=s.transaction([z],"readwrite").objectStore(z).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 z;const J=new class extends K{constructor(){super(...arguments),this.name=R,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)}},Y=new class extends K{constructor(){super(...arguments),this.name=A,this.maxItems=25}add(e){return this._add({...e,date:new Date})}},Q={error:1,info:2,debug:3};let X=3;const Z={setLevel(e){Q[e]||(e="error"),X=Q[e]},write(e,t,s){return"error"===e?this.error(t):this.info(t),J.add(e,t,s)}};Object.keys(Q).forEach(e=>{const t=Q[e];Z[e]=(...s)=>{t<=X&&(console.groupCollapsed(e),console.info("",...s),console.trace("trace"),console.groupEnd())}});class ee{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||T(),i=this.handlers[e];return i?(i.forEach(e=>{_(e)&&setTimeout(()=>{e({...t,eventId:s})},0)}),s):s},this.handlers={}}}class te{constructor(e,t,s,i=new L){this.data=e,this.api=t,this.inboxModel=s,this.dateModule=i,this.publicMessageBuilder=this.publicMessageBuilder.bind(this)}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=s||await this.data.getDefaultNotificationImage(),h=i||await this.data.getDefaultNotificationTitle(),u=JSON.parse(t);return this.dateModule.date=new Date(1e3*parseInt(a)),this.dateModule.setLocal(),{title:h,imageUrl:c,code:r,message:n,sendDate:this.dateModule.date.toISOString(),type:this.messageTypeFactory(e,u),link:u?.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=JSON.parse(t.action_params),i=this.messageTypeFactory(t.action_type,s);2===i&&null!=s.l?document.location.href=s.l:3===i&&null!=s.l&&window.history.go(s.l),t.status=3,await this.inboxModel.putMessage(t),await this.api.inboxStatus(t.order,t.status)}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.inboxModel.updateMessages()}}class se{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 ie{dbVersionChangeHandler(e,t){console.info("onversionchange",t),e.close()}dbRequestSuccessHandler(e,t){const s=t.target.result;s.onversionchange=e=>{this.dbVersionChangeHandler(s,e)},e(s)}dbRequestUpgradeNeededHandler(e){const t=e.target.result;t.onversionchange=e=>{this.dbVersionChangeHandler(t,e)};new j(t).applyMigrations()}getDB(){return new Promise((e,t)=>{const s=indexedDB.open("PUSHWOOSH_SDK_STORE",7);s.onsuccess=t=>{this.dbRequestSuccessHandler(e,t)},s.onupgradeneeded=e=>{this.dbRequestUpgradeNeededHandler(e)},s.onerror=()=>t(s.error)})}async put(e,t,s){const i=await this.getDB(),a=new se(i,e),r=await a.put(t,s);return i.close(),r}async delete(e,t){const s=await this.getDB(),i=new se(s,e),a=await i.delete(t);return s.close(),a}async get(e,t,s){const i=await this.getDB(),a=new se(i,e),r=await a.get(t,s);return i.close(),r}async getAll(e){const t=await this.getDB(),s=new se(t,e),i=await s.getAll();return t.close(),i||[]}async count(e,t){const s=await this.getDB(),i=new se(s,e),a=await i.count(t);return s.close(),a}async countByIndex(e,t,s){const i=await this.getDB(),a=new se(i,e);a.index=t;const r=await a.countByIndex(s);return i.close(),r}}class ae{constructor(e,t,s,i=new ie,a=new L){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 te(this.data,this.api,this)})}}const re=e=>`params.${e}`;class ne{constructor(e=G){this.store=e}async clearAll(){const e=["applicationCode","apiToken","hwid","deviceType","deviceModel","language","apiEntrypoint","tokens","applicationServerKey","isVapidChanged","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"];for(const t of e)await this.store.set(re(t),void 0)}async setApplicationCode(e){await this.store.set(re("applicationCode"),e)}async getApplicationCode(){return this.store.get(re("applicationCode"))}async setApiToken(e){return await this.store.set(re("apiToken"),e)}async getApiToken(){return this.store.get(re("apiToken"))}async setHwid(e){await this.store.set(re("hwid"),e)}async getHwid(){return this.store.get(re("hwid"))}async setDeviceType(e){await this.store.set(re("deviceType"),e)}async getDeviceType(){return this.store.get(re("deviceType"))}async setDeviceModel(e){await this.store.set(re("deviceModel"),e)}async getDeviceModel(){return this.store.get(re("deviceModel"))}async setLanguage(e){await this.store.set(re("language"),e)}async getLanguage(){return this.store.get(re("language"),"en")}async setApiEntrypoint(e){await this.store.set(re("apiEntrypoint"),e)}async getApiEntrypoint(){return this.store.get(re("apiEntrypoint"),"https://cp.pushwoosh.com/json/1.3/")}async setTokens(e){await this.store.set(re("tokens"),e)}getTokens(){return this.store.get(re("tokens"))}async setApplicationServerKey(e){await this.store.set(re("applicationServerKey"),e)}async getApplicationServerKey(){return this.store.get(re("applicationServerKey"))}async setIsVapidChanged(e){await this.store.set(re("isVapidChanged"),e)}async getIsVapidChanged(){return this.store.get(re("isVapidChanged"),!1)}async setWebSitePushId(e){await this.store.set(re("webSitePushId"),e)}async getWebSitePushId(){return this.store.get(re("webSitePushId"))}async setDefaultNotificationImage(e){await this.store.set(re("defaultNotificationImage"),e)}async getDefaultNotificationImage(){return this.store.get(re("defaultNotificationImage"),"https://cp.pushwoosh.com/img/logo-medium.png")}async setDefaultNotificationTitle(e){await this.store.set(re("defaultNotificationTitle"),e)}async getDefaultNotificationTitle(){return this.store.get(re("defaultNotificationTitle"),"Pushwoosh notification")}async setUserId(e){await this.store.set(re("userId"),e?`${e}`:void 0)}async getUserId(){return this.store.get(re("userId"))}async setStatusUserIdWasChanged(e){await this.store.set(re("userIdWasChanged"),e)}async getStatusUserIdWasChanged(){return this.store.get(re("userIdWasChanged"),!1)}async setEmail(e){await this.store.set(re("email"),e?`${e}`:void 0)}async getEmail(){return this.store.get(re("email"))}async setStatusEmailWasChanged(e){await this.store.set(re("emailWasChanged"),e)}async getStatusEmailWasChanged(){return this.store.get(re("emailWasChanged"),!1)}async setSmsNumber(e){await this.store.set(re("smsNumber"),e?`${e}`:void 0)}async getSmsNumber(){return this.store.get(re("smsNumber"))}async setStatusSmsNumberWasChanged(e){await this.store.set(re("smsNumberWasChanged"),e)}async getStatusSmsNumberWasChanged(){return this.store.get(re("smsNumberWasChanged"),!1)}async setWhatsAppNumber(e){await this.store.set(re("whatsAppNumber"),e?`${e}`:void 0)}async getWhatsAppNumber(){return this.store.get(re("whatsAppNumber"))}async setStatusWhatsAppNumberWasChanged(e){await this.store.set(re("whatsAppNumberWasChanged"),e)}async getStatusWhatsAppNumberWasChanged(){return this.store.get(re("whatsAppNumberWasChanged"),!1)}async setLastPermissionStatus(e){await this.store.set(re("isLastPermissionStatus"),e)}async getLastPermissionStatus(){return this.store.get(re("isLastPermissionStatus"))}async setStatusManualUnsubscribed(e){await this.store.set(re("isManualUnsubscribed"),e)}getStatusManualUnsubscribed(){return this.store.get(re("isManualUnsubscribed"),!1)}async setStatusCommunicationDisabled(e){await this.store.set(re("isCommunicationDisabled"),e)}getStatusCommunicationDisabled(){return this.store.get(re("isCommunicationDisabled"),!1)}async setCommunicationEnabled(e){await this.store.set(re("communicationEnabled"),e)}getCommunicationEnabled(){return this.store.get(re("communicationEnabled"))}async setStatusDropAllData(e){await this.store.set(re("isDropAllData"),e)}getStatusDropAllData(){return this.store.get(re("isDropAllData"),!1)}async setSdkVersion(e){await this.store.set(re("sdkVersion"),e)}async getSdkVersion(){return this.store.get(re("sdkVersion"))}async setServiceWorkerVersion(e){await this.store.set(re("serviceWorkerVersion"),e)}getServiceWorkerVersion(){return this.store.get(re("serviceWorkerVersion"))}async setServiceWorkerUrl(e){e&&await this.store.set(re("serviceWorkerUrl"),e)}async getServiceWorkerUrl(){return this.store.get(re("serviceWorkerUrl"),s)}async setServiceWorkerScope(e){e&&await this.store.set(re("serviceWorkerScope"),e)}async getServiceWorkerScope(){return this.store.get(re("serviceWorkerScope"))}async setLastOpenMessage(e){await this.store.set(re("lastOpenMessage"),e)}getLastOpenMessage(){return this.store.get(re("lastOpenMessage"))}async setLastOpenApplicationTime(e){await this.store.set(re("lastOpenApplicationTime"),e)}async getLastOpenApplicationTime(){return this.store.get(re("lastOpenApplicationTime"))}async setFeatures(e){await this.store.set(re("features"),e)}async getFeatures(){return this.store.get(re("features"))}async setInitParams(e){await this.store.set(re("init"),e)}async getInitParams(){return this.store.get(re("init"))}async setInboxLastRequestCode(e){await this.store.set(re("inbox.lastRequestCode"),e)}async getInboxLastRequestCode(){return this.store.get(re("inbox.lastRequestCode"),"")}async setInboxLastRequestTime(e){await this.store.set(re("inbox.lastRequestTime"),e)}async getInboxLastRequestTime(){return this.store.get(re("inbox.lastRequestTime"),0)}async setInboxNewMessagesCount(e){await this.store.set(re("inbox.newMessagesCount"),e)}async getInboxNewMessagesCount(){return this.store.get(re("inbox.newMessagesCount"),0)}async setDelayedEvent(e){await this.store.set(re("delayedEvent"),e)}getDelayedEvent(){return this.store.get(re("delayedEvent"))}async setPromptDisplayCount(e){await this.store.set(re("promptDisplayCount"),e)}async getPromptDisplayCount(){return this.store.get(re("promptDisplayCount"),0)}async setPromptLastSeenTime(e){await this.store.set(re("promptLastSeenTime"),e)}async getPromptLastSeenTime(){return this.store.get(re("promptLastSeenTime"),0)}}class oe{constructor(e=new ne,t=Z){this.data=e,this.logger=t}checkDevice(e){return this.createRequest("checkDevice",e)}getConfig(e){return this.createRequest("getConfig",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){return this.createRequest("postEvent",e)}getInboxMessages(e){return this.createRequest("getInboxMessages",e)}inboxStatus(e){return this.createRequest("inboxStatus",e)}pageVisit(e,t){return this.createRequest("pageVisit",e,t)}setPurchase(e){return this.createRequest("setPurchase",e)}async createRequest(e,t,s){const i=await this.data.getApiEntrypoint(),a=await this.data.getApiToken(),r=s||i+e,n=a?{headers:{Authorization:`Token ${a}`,"Content-Type":"text/plain;charset=UTF-8",Origin:M().location.origin},credentials:"include"}:{},o=await fetch(r,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:JSON.stringify({request:t}),...n}),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=`status: ${e.status}. statusText: ${e.statusText}.`;try{const s=await e.json();s&&s.status_message&&(t+=` status_code: ${s.status_code}. status_message: ${s.status_message}.`)}catch(e){}throw new Error(t)}const t=await e.json();if(200!==t.status_code)throw new Error(`Error code: ${t.status_code}. Error text: ${t.status_message}`);return t}}class ce{constructor(e,t=new ne,s=new oe,i=()=>!1){this.eventBus=e,this.data=t,this.apiClient=s,this.getIsCommunicationDisabled=i}async checkDevice(){const e=await this.getRequestParams();return await this.apiClient.checkDevice(e)}async checkDeviceSubscribeForPushNotifications(e=!0){let t=localStorage.getItem(i);if(void 0===t||!e){const{exist:e,push_token_exist:s}=await this.checkDevice();localStorage.setItem(i,e&&s?a:r),t=localStorage.getItem(i)}return t===a}async getConfig(e){const t=await this.getRequestParams();return this.apiClient.getConfig({...t,features:e})}async applicationOpen(){const e=await this.getRequestParams();return await this.data.setLastOpenApplicationTime(Date.now()),this.apiClient.applicationOpen(e)}async registerDevice(){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=await this.apiClient.registerDevice({...e,push_token:t.pushToken,auth_token:t.authToken,public_key:t.publicKey});return await this.data.setStatusManualUnsubscribed(!1),localStorage.setItem(i,a),this.eventBus.dispatchEvent("register",{}),s}async unregisterDevice(){const e=await this.getRequestParams(),t=await this.apiClient.unregisterDevice(e);return localStorage.setItem(i,r),this.eventBus.dispatchEvent("unsubscribe",{}),t}async deleteDevice(){const e=await this.getRequestParams(),t=await this.apiClient.deleteDevice(e);return await this.data.setStatusManualUnsubscribed(!0),localStorage.setItem(i,r),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("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 registerUser(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.data.getDeviceType(),n=`${e}`,o=await this.apiClient.registerUser({...a,hwid:s,userId:n,ts_offset:60*-(new Date).getTimezoneOffset(),device_type:r});return await this.data.setUserId(n),t&&await this.data.setStatusUserIdWasChanged(!0),o}async registerEmail(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");if(!/^\S+@\S+\.\S+$/.test(e))return Promise.reject("Invalid Email format");const{hwid:s,device_type:i,...a}=await this.getRequestParams(),r=await this.apiClient.registerEmail({...a,email:e,ts_offset:60*-(new Date).getTimezoneOffset()});return await this.data.setEmail(e),t&&await this.data.setStatusEmailWasChanged(!0),r}async registerSmsNumber(e,t=!0){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");if(!/^\+?[0-9]+$/.test(e))return Promise.reject("Invalid Phone number format: +1234567890");const{application:s,userId:i}=await this.getRequestParams(),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("Communication is disabled");if(!/^whatsapp:\+?[0-9]+$/.test(e))return Promise.reject("Invalid WhatsApp number format: whatsapp:+1234567890");const{application:s,userId:i}=await this.getRequestParams(),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 postEvent(e,t){if(this.getIsCommunicationDisabled())return Promise.reject("Communication is disabled");const s=await this.getRequestParams(),i=new Date,a=i.getTime(),r=Math.floor(a/1e3),n=r-i.getTimezoneOffset()/60*3600,o=await this.data.getLastOpenMessage();if(o&&o.expiry>Date.now()){if(t.msgHash)return Promise.reject("attribute msgHash already defined");t={...t,msgHash:o.messageHash}}await this.data.setLastOpenMessage(void 0);const c=await this.apiClient.postEvent({...s,event:e,timestampUTC:r,timestampCurrent:n,attributes:t});return c&&c.code&&this.eventBus.dispatchEvent("receive-in-app-code",{code:c.code}),c}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 pageVisit(e){const t=await this.getRequestParams(),s=await this.data.getFeatures(),i=s&&s.page_visit&&s.page_visit.entrypoint;if(i)return this.apiClient.pageVisit({...t,...e},i)}async setPurchase(e){const t=await this.getRequestParams();return this.apiClient.setPurchase({...t,...e})}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.data.getApplicationCode(),t=await this.data.getHwid(),s=await this.data.getUserId(),i=await this.data.getDeviceType(),a=await this.data.getDeviceModel(),r=await this.data.getLanguage(),n=await this.data.getSdkVersion();return{application:e,hwid:t,userId:s||t,device_type:i,device_model:a,timezone:60*-(new Date).getTimezoneOffset(),language:r,v:n}}}class he{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()}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}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}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(" ")}}class ue{constructor(e,t,s){this.api=e,this.data=t,this.config=s}getPermission(){return Notification.permission}checkIsPermissionGranted(){return this.getPermission()===o}checkIsPermissionDefault(){return this.getPermission()===c}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 Z.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)return await this.data.setLastPermissionStatus(t),!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=${T()}`),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 de{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()===o}checkIsPermissionDefault(){return this.getPermission()===c}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 Z.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),!0):t}getPermissionInfo(){return safari.pushNotification.permission(this.config.webSitePushId)}}class ge{constructor(){this.ready=!1,this.moduleRegistry={},this.addEventHandler=(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 J.getAll();console.log(e)},async showKeyValues(){const e=await G.getAll();console.log(e)},async showMessages(){(await Y.getAll()).forEach(e=>console.log(e))}},this.eventBus=new ee,this.data=new ne,this.apiClient=new oe(this.data),this.api=new ce(this.eventBus,this.data,this.apiClient,()=>this.isCommunicationDisabled),this.platformChecker=new he(M()),this.inboxModel=new ae(this.eventBus,this.data,this.api),this.pwinbox=new te(this.data,this.api,this.inboxModel)}push(e){if(_(e))this.subscribeToLegacyEvents(h,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){if(this.isCommunicationDisabled)throw new Error("Communication is disabled!");if(this.driver.checkIsPermissionDefault()){this.eventBus.dispatchEvent("show-notification-permission-dialog",{}),await this.driver.askPermission();const e=this.driver.getPermission();this.eventBus.dispatchEvent("hide-notification-permission-dialog",{permission:e})}const t=this.driver.getPermission(),s=await this.data.getStatusManualUnsubscribed(),i=await this.api.checkDeviceSubscribeForPushNotifications(!1);if(t===o){this.eventBus.dispatchEvent("permission-granted",{});return(!i&&!s||e)&&await this.driver.subscribe(),void this.eventBus.dispatchEvent("subscribe",{})}if(t===n)return this.eventBus.dispatchEvent("permission-denied",{}),void(i&&await this.driver.unsubscribe())}async unsubscribe(){try{await this.driver.unsubscribe()}catch(e){throw Z.error(e,"Error occurred during the unsubscribe"),e}}async forceSubscribe(){await this.subscribe(!0)}isDeviceRegistered(){return localStorage.getItem(i)===a}isDeviceUnregistered(){return localStorage.getItem(i)===r}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();this.driver.checkIsPermissionGranted()&&(await this.api.registerDevice(),await this.sendData())}else 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(),await this.data.setStatusDropAllData(!0)}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}async sendStatisticsVisitedPage(){const{document:{title:e},location:{origin:t,pathname:s,href:i}}=window;await this.api.pageVisit({title:e,url_path:`${t}${s}`,url:i})}async initialize(e){this.initParams={...E,...e};const t=localStorage.getItem("PW_SET_LOGGER_LEVEL");if(Z.setLevel(t||e.logLevel||"error"),!this.isAvailableNotifications())return;if(!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();if((!r||r!==e.applicationCode||n)&&(await this.data.setHwid(""),await this.data.setUserId(),await this.data.setEmail()),await this.data.setApplicationCode(e.applicationCode),await this.data.setDeviceType(this.platformChecker.getPlatformType()),await this.data.setDeviceModel(this.platformChecker.getBrowserVersion()),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.49.3"),this.isCommunicationDisabled)this.eventBus.dispatchEvent("communication-disabled",{});else{await this.finishInit();try{await this.inboxModel.updateMessages()}catch(e){Z.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.platformChecker.isSafari){const e=/#P(.*)/,t=decodeURIComponent(document.location.hash);e.test(t)&&this.api.pushStat(e.exec(t)[1]).then(()=>history.pushState(null,"","#"))}}}async finishInit(){await this.ensureHwid(),await this.loadConfig(),await this.open(),await this.sendData();await this.data.getApplicationServerKey()?await this.initPushNotifications(this.initParams):Z.error("Pushwoosh: No vapid key found! Please, check your application settings in Pushwoosh dashboard."),this.ready=!0,this.eventBus.dispatchEvent("ready",{}),"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 ensureHwid(e=!1){await this.data.getHwid()&&!e||await this.data.setHwid(this.initParams.applicationCode+"_"+T())}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.driver.getPermission();"granted"===e&&await this.data.setLastPermissionStatus(e);const t=await this.data.getStatusCommunicationDisabled(),s=await this.data.getStatusDropAllData(),i=await this.driver.checkIsNeedResubscribe();if(t||s)return void await this.unsubscribe();i&&(await this.unsubscribe(),await this.data.setStatusManualUnsubscribed(!1),await this.data.setIsVapidChanged(!1));const a=await this.data.getStatusManualUnsubscribed(),r=await this.api.checkDeviceSubscribeForPushNotifications(!1);switch(e){case c:this.eventBus.dispatchEvent("permission-default",{}),r&&await this.unsubscribe();break;case n:this.eventBus.dispatchEvent("permission-denied",{}),r&&await this.unsubscribe();break;case o:this.eventBus.dispatchEvent("permission-granted",{}),a&&r&&await this.unsubscribe(),(!r&&!a||i)&&await this.subscribe(!0)}}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())}async sendData(){const e=this.initParams,t=await this.data.getUserId();e.userId&&"user_id"!==e.userId&&e.userId!==t&&await this.api.registerUser(e.userId,!1);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,task:async()=>{await this.api.setTags(e.tags)}}];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(){const e=await this.api.getConfig(["page_visit","vapid_key","web_in_apps","events","subscription_prompt"]),t=e&&e.features;if(await this.data.setFeatures(t),t){if(t.page_visit&&t.page_visit.enabled&&(await G.set("PAGE_VISITED_URL",t.page_visit.entrypoint),this.sendStatisticsVisitedPage()),t.events&&t.events.length){t.events.some(e=>e===x)&&this.sendPostEventVisitedPage()}if(t.vapid_key){const e=await this.data.getApplicationServerKey();await this.data.setApplicationServerKey(t.vapid_key),e!==t.vapid_key&&await this.data.setIsVapidChanged(!0)}}}async initPushNotifications(e){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.data.setInitParams(e),await this.initDriver();try{await this.defaultProcess()}catch(e){Z.error(e,"Internal error: defaultProcess fail")}}async initDriver(){if(this.platformChecker.isSafari){const{safariWebsitePushID:e}=await this.data.getInitParams();return e?void(this.driver=new de(this.api,this.data,{webSitePushId:e})):void Z.info("For work with Safari Push Notification add safariWebsitePushID to initParams!")}Z.info({isAvailableServiceWorker:this.platformChecker.isAvailableServiceWorker}),this.platformChecker.isAvailableServiceWorker&&(this.driver=new ue(this.api,this.data,{}))}sendPostEventVisitedPage(){const{document:{title:e},location:{href:t}}=window;this.api.postEvent(x,{url:t,title:e,device_type:this.platformChecker.platform})}subscribeToLegacyEvents(e,t){let s=!0;switch(!0){case"onLoad"===e:t();break;case e===h:if(this.ready){t(this.api);break}this.eventBus.addEventHandler("ready",()=>t(this.api));break;case e in N:this.eventBus.addEventHandler(N[e].name,s=>{const{prop:i}=N[e];t(this.api,i?s[i]:void 0)});break;default:s=!1}return s}emitLegacyEventsFromServiceWorker(e,t){switch(e){case b:this.eventBus.dispatchEvent("receive-push",{notification:t});break;case v:this.eventBus.dispatchEvent("open-notification",{notification:t});break;case y: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
|